3535 12B tower. Our port runs only the VALID tokens at their ORIGINAL absolute
3636 positions. That is equivalent -- pads are masked out of attention and are
3737 causally before every valid token, and the feature extractor zeroes their
38- rows anyway -- but "is equivalent" is a claim, so section 3 emits the full
38+ rows anyway -- but "is equivalent" is a claim, so section 4 emits the full
3939 left-padded oracle run and the C++ suite holds the short run's valid rows
4040 to the padded run's valid rows. If the equivalence is ever false, that gate
4141 is what says so, and a 100x cost claim stops resting on an argument.
4242
4343 * ONE arithmetic width per state, both ways round. Section 2 is the oracle in
44- float32 and section 4 the SAME oracle in bfloat16. Our forward carries the
45- stream in bf16 and widens only on the way out (gemma4.h,
46- Gemma4HiddenStatesResult), so bf16 is the dtype-MATCHED arm and f32 is the
47- arm that would catch a reduction-order defect a bf16 store absorbs. Gating
48- only one of them has burned this project before.
44+ float32 and section 3 the SAME oracle in bfloat16; sections 4 and 4b are
45+ that pair again for the left-padded run. Our forward carries the stream in
46+ bf16 and widens only on the way out (gemma4.h, Gemma4HiddenStatesResult),
47+ so bf16 is the dtype-MATCHED arm and f32 is the arm that would catch a
48+ reduction-order defect a bf16 store absorbs. Gating only one of them has
49+ burned this project before.
50+
51+ Every leg runs on a DEEP COPY of the module. `nn.Module.to(dtype)` converts
52+ in place and bf16 rounding is destructive, so before that fix the two
53+ "float32" legs after the bf16 one were executing over bf16-ROUNDED weights
54+ -- MEASURED at up to 3.90e-02 per state, of the same order as the noise
55+ floor the tolerance itself is derived from.
56+
57+ * The ROPE TABLES, in f32 (section 6), because `partial_rotary_factor` is not
58+ resolvable from the hidden states at any fixture size this generator can
59+ build. Section 6's note carries the measurement that establishes it.
4960
5061Both sides rebuild every weight from one deterministic FNV-1a + splitmix64
5162stream keyed by the parameter's own HuggingFace NAME, exactly as
8495from __future__ import annotations
8596
8697import argparse
98+ import copy
8799import json
88100import os
89101import subprocess
@@ -317,7 +329,20 @@ def build_tower(real_config: dict):
317329
318330
319331def run_tower (inner , ids , mask , dtype , positions = None ):
320- m = inner .to (dtype ).eval ()
332+ """One oracle leg, on a DEEP COPY of the module.
333+
334+ `nn.Module.to(dtype)` converts parameters and buffers IN PLACE, so the
335+ obvious `inner.to(dtype)` / `inner.to(torch.float32)` round trip does not
336+ restore anything: bf16 rounding is destructive, and every leg after the
337+ first bf16 one would run over bf16-ROUNDED weights while calling itself
338+ float32. MEASURED on this fixture before the fix: re-running the identical
339+ f32 call after the bf16 leg moved a state by up to 3.90e-02, which is
340+ ~40x the f32 legs' own round-off and of the same order as the bf16 noise
341+ floor the gate is calibrated on. Sections 4 and 5 were silently
342+ order-dependent because of it. Copying is cheap here -- the reduced tower
343+ is a few hundred KB -- and it makes every leg independent of leg order.
344+ """
345+ m = copy .deepcopy (inner ).to (dtype ).eval ()
321346 kwargs = {}
322347 if positions is not None :
323348 # The absolute positions the tokens occupy in the padded batch. Left
@@ -332,9 +357,45 @@ def run_tower(inner, ids, mask, dtype, positions=None):
332357 output_hidden_states = True ,
333358 ** kwargs ,
334359 )
335- states = [h [0 ].to (torch .float32 ).contiguous ().numpy () for h in out .hidden_states ]
336- inner .to (torch .float32 )
337- return states
360+ return [h [0 ].to (torch .float32 ).contiguous ().numpy () for h in out .hidden_states ]
361+
362+
363+ def rope_cos_sin (config , layer_type : str , head_dim : int , positions ) -> np .ndarray :
364+ """The oracle's OWN cos|sin table for one layer type, in float32.
365+
366+ Why this is emitted at all: `partial_rotary_factor` is NOT resolvable from
367+ the hidden states. MEASURED on this fixture, the whole difference between
368+ the config's 0.25 and a port that ignored it and rotated fully is 1.09e-01
369+ at the worst state against a bf16 noise floor of 9.99e-02 -- a ratio of
370+ 1.09, i.e. inside the tolerance the same states are gated at. Enlarging the
371+ fixture does not rescue it: at (head_dim 16/32, seq 32) the ratio FALLS to
372+ 0.65, because bf16 accumulation noise grows at least as fast as the rope
373+ contribution does. So the end-to-end states are the wrong instrument, and
374+ the right one is the table itself, in f32, with no accumulation in it.
375+
376+ Built by the real `Gemma4UnifiedTextRotaryEmbedding`, which is what routes
377+ `rope_type: "proportional"` to `_compute_proportional_rope_parameters`
378+ (modeling_gemma4_unified.py:206-218 -- the ROPE_INIT_FUNCTIONS lookup at :207
379+ and the call at :218; modeling_rope_utils.py:187-254) and so is the only
380+ thing that decides how many angle pairs are zero-padded.
381+
382+ Returns [len(positions), head_dim]: the first head_dim/2 columns are cos
383+ over the distinct angle pairs and the second half is sin, which is the
384+ layout `BuildProportionalRopeCache` writes.
385+ """
386+ from transformers .models .gemma4_unified .modeling_gemma4_unified import ( # noqa: PLC0415
387+ Gemma4UnifiedTextRotaryEmbedding ,
388+ )
389+
390+ rope = Gemma4UnifiedTextRotaryEmbedding (config )
391+ pos = torch .tensor ([list (positions )], dtype = torch .long )
392+ x = torch .zeros (1 , len (positions ), head_dim , dtype = torch .float32 )
393+ cos , sin = rope (x , pos , layer_type = layer_type )
394+ pairs = head_dim // 2
395+ # Upstream duplicates each angle (`emb = cat((freqs, freqs))`) so cos/sin are
396+ # head_dim wide over head_dim/2 DISTINCT angles; take one copy of each.
397+ table = torch .cat ((cos [0 , :, :pairs ], sin [0 , :, :pairs ]), dim = - 1 )
398+ return table .to (torch .float32 ).contiguous ().numpy ()
338399
339400
340401# ---------------------------------------------------------------------------
@@ -408,6 +469,11 @@ def main() -> int:
408469 plain_f32 = run_tower (inner , TOKENS , [1 ] * SEQ , torch .float32 )
409470 plain_bf16 = run_tower (inner , TOKENS , [1 ] * SEQ , torch .bfloat16 )
410471 padded_f32 = run_tower (inner , padded_ids , padded_mask , torch .float32 )
472+ # The padded run at the SHIPPED dtype too. Without it the left-padded rows
473+ # have no dtype-matched oracle, and anything gated against them -- the
474+ # prompt-to-conditioning path, which is left-padded by construction -- has
475+ # no measured floor to be held to, only a borrowed one.
476+ padded_bf16 = run_tower (inner , padded_ids , padded_mask , torch .bfloat16 )
411477 # The equivalence claim, isolated INSIDE the oracle and in f32 so no dtype
412478 # noise is mixed into it: the same valid tokens, told their absolute
413479 # positions, run WITHOUT the pads. If upstream's own two answers agree, the
@@ -523,19 +589,60 @@ def main() -> int:
523589 "// [state][padded_seq * hidden]. Rows 0..kLtxTowerNumPad-1 are pad rows and\n "
524590 "// their contents are upstream's garbage-but-masked values; the gate reads\n "
525591 "// only the VALID tail and holds section 2 to it.\n "
592+ "// Every leg runs on a DEEP COPY of the module, so this one is not\n "
593+ "// downstream of the bf16 leg's rounding and the sections are independent\n "
594+ "// of the order they are produced in.\n "
526595 )
527596 for i , s in enumerate (padded_f32 ):
528597 emit_f32 (out , f"kLtxTowerPaddedStateF32_{ i } " , s )
529598
599+ out .write (
600+ "// --- section 4b: the LEFT-PADDED run, BFLOAT16 (the SHIPPED dtype) ---\n "
601+ "// The dtype-MATCHED arm for anything gated on the left-padded rows, and\n "
602+ "// with section 4 it is also the padded run's own measured noise floor.\n "
603+ )
604+ for i , s in enumerate (padded_bf16 ):
605+ emit_f32 (out , f"kLtxTowerPaddedStateBf16_{ i } " , s )
606+
530607 out .write (
531608 "// --- section 5: the equivalence, measured INSIDE the oracle ---\n "
532609 "// Per state, max|short-run-at-absolute-positions - padded-run's valid rows|,\n "
533- "// both f32, so this number carries NO dtype noise. It is upstream's own\n "
534- "// answer to 'is dropping the pads free?'. Our port inherits it; the C++\n "
535- "// gate checks the two claims separately so a failure says which one broke.\n "
610+ "// both f32 and both on independently deep-copied modules, so this number\n "
611+ "// carries NO dtype noise. It is upstream's own answer to 'is dropping the\n "
612+ "// pads free?'. Our port inherits it; the C++ gate checks the two claims\n "
613+ "// separately so a failure says which one broke.\n "
536614 )
537615 emit_f32 (out , "kLtxTowerPadEquivalence" , equivalence )
538616
617+ # SECTION 6 -- the rope table, because the hidden states cannot see it.
618+ #
619+ # `partial_rotary_factor` decides how many of the full-attention layers'
620+ # angle pairs are rotated and how many are zero-padded to identity. It is
621+ # config-carried, shape-invisible, and -- MEASURED, not assumed -- also
622+ # invisible in the gated hidden states: setting it to 1.0 displaces the
623+ # worst state by 1.09e-01 against a bf16 floor of 9.99e-02 (ratio 1.09),
624+ # and a larger fixture makes that WORSE, not better (0.65 at head_dim
625+ # 16/32, seq 32), because bf16 accumulation noise grows at least as fast.
626+ # A gate whose tolerance is bf16 noise cannot resolve it, so the table
627+ # itself is emitted and compared in f32.
628+ full_head_dim = GLOBAL_HEAD_DIM
629+ rope_positions = list (range (PADDED_SEQ ))
630+ rope_full = rope_cos_sin (config .text_config , "full_attention" ,
631+ full_head_dim , rope_positions )
632+ out .write (
633+ "// --- section 6: the ORACLE's FULL-attention rope cos|sin table, f32 ---\n "
634+ "// [position][global_head_dim]: first half cos, second half sin, over the\n "
635+ "// global_head_dim/2 DISTINCT angle pairs (upstream stores each twice).\n "
636+ "// `rope_type: proportional` at theta 1e6 and partial_rotary_factor 0.25,\n "
637+ "// so the trailing pairs are cos=1, sin=0. Emitted because the partial\n "
638+ "// factor is NOT resolvable from the hidden states -- see the note above --\n "
639+ "// and because a table that silently rotated every pair would still produce\n "
640+ "// 13 finite, plausibly-scaled states.\n "
641+ )
642+ emit_scalar (out , "kLtxTowerRopePositions" , len (rope_positions ))
643+ out .write ("\n " )
644+ emit_f32 (out , "kLtxTowerRopeFullCosSin" , rope_full )
645+
539646 out .write ("} // namespace vllm_test\n " )
540647
541648 sys .stderr .write (
0 commit comments