[quantization] Implement prefill masks and RoPE verification in StaticGemma4Runtime#836
Merged
Merged
Conversation
…cGemma4Runtime Add real per-layer-type attention masks and RoPE to StaticGemma4Runtime. Co-authored-by: Cline TICO-DCO-1.0-Signed-off-by: d.savchenkov <d.savchenkov@partner.samsung.com>
Torrero
reviewed
Jul 23, 2026
Comment on lines
+1028
to
+1040
| ref_cos, ref_sin = rotary_emb(dummy_hidden, position_ids, layer_type) | ||
| rt_cos, rt_sin = rt_rope[layer_type] | ||
|
|
||
| torch.testing.assert_close( | ||
| rt_cos, | ||
| ref_cos, | ||
| msg=f"RoPE cos mismatch for layer_type={layer_type!r}", | ||
| ) | ||
| torch.testing.assert_close( | ||
| rt_sin, | ||
| ref_sin, | ||
| msg=f"RoPE sin mismatch for layer_type={layer_type!r}", | ||
| ) |
Contributor
There was a problem hiding this comment.
@dvsav
This comparison is unclear for me, in both cases you use HF's module rotary_emb with almost the same artificial dummy_hidden input. Could you please clarify your idea, or maybe I missed something.
Contributor
Author
There was a problem hiding this comment.
👍 I agree, but, I'll fix that in the following PR, if you don't mind.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Related issue: #768
Related PR: #822
What
Implements real per-layer-type attention masks and RoPE (Rotary Position Embedding) generation in
StaticGemma4Runtime, replacing the previous placeholder implementation. Adds Step 5 of the side-by-side verification flow (verify_step_masks_and_rope) that validates the runtime's masks and RoPE against Hugging Facetransformersreference outputs.Why
The static Gemma4 runtime requires CPU-owned, pre-computed attention masks and RoPE tensors that will be fed to NPU-executed decoder layers. Gemma4 E2B has a mixed layer-type architecture — a repeating pattern of 5 sliding-attention layers followed by 1 full-attention layer — each requiring distinct mask patterns and distinct RoPE configurations:
full_attention: proportional RoPE (partial_rotary_factor=0.25,global_head_dim=512,rope_theta=1_000_000) with a standard causal mask.sliding_attention: default RoPE (head_dim=256,rope_theta=10_000) with a sliding-window causal mask (sliding_window=512).The previous
build_prefill_masks_and_ropereturned shape-compatible zero/one placeholders. This PR replaces them with correct implementations and adds verification to ensure they exactly match HF'sGemma4TextRotaryEmbeddingandcreate_masks_for_generate.Key Design Decisions
Per-layer-type RoPE via HF module: The runtime calls the model's own
Gemma4TextRotaryEmbeddingmodule (self.model.model.language_model.rotary_emb) directly, passing thelayer_typeargument. This guarantees the runtime uses the exact sameinv_freqbuffers andattention_scalingthat the HF model uses, avoiding reimplementation errors.Key-only padding masking (matching HF convention): Both mask builders (
_build_full_attention_maskand_build_sliding_window_attention_mask) apply padding only viakey_valid(column masking). Query rows for padding positions are not zeroed out — they retain their causal/sliding-window pattern. This matches HF'screate_masks_for_generate, which only controls which keys are visible, not which queries are active. Padding query outputs are simply discarded downstream. An earlier version incorrectly includedquery_valid, which truncated padding rows to all-False and caused a pattern mismatch.Boolean pattern comparison for masks: HF may use different
mask_valuerepresentations or returnNonedepending on the attention implementation. The verification compares boolean attention patterns (allowed vs. forbidden) rather than exact float values, and temporarily forces_attn_implementation="eager"to obtain 4D float masks from HF'screate_masks_for_generate.Exact match for RoPE: Since the runtime and HF reference use the same module, RoPE comparison is an exact
torch.testing.assert_closecheck.Changes
All changes are in
tico/quantization/recipes/debug/static_gemma4_runtime.py(293 insertions, 29 deletions):_build_full_attention_mask: Builds a standard causal mask with key-only padding masking. Returns(B, 1, S, S)additive bias._build_sliding_window_attention_mask: Builds a sliding-window causal mask (kv_idx > q_idx - sliding_window) with key-only padding masking. Returns(B, 1, S, S)additive bias.build_prefill_masks_and_rope: Now computesposition_ids = arange(seq_len), builds both mask types from the text config'ssliding_window, and computes per-layer-type RoPE via the HFrotary_embmodule. Returns(attention_masks, position_embeddings)dicts keyed by layer type.verify_step_masks_and_rope: Side-by-side verification comparing runtime RoPE (exact match) and masks (boolean pattern match) against HF reference. Returns(rt_masks, rt_rope)to avoid recomputation in downstream steps.run_static_gemma4_runtime: Calls Step 5 after Step 4.Tests
No new unit test files in this PR — verification is done via the example script's side-by-side comparison flow. All 5 verification steps pass:
Example Script