Repository navigation
[scripts] Build Qwen3.5 MRoPE positions with the collator contract - #5758
Conversation
|
|
|
@claude review |
|
Claude finished @tianyu-l's task in 2m 18s —— View job Request changes: the MRoPE positions fix is right, but |
There was a problem hiding this comment.
Verdict: Request changes -- this fixes the MRoPE positions, but the script still can't run: run_tt passes batched (1, S) inputs to a model that now takes packed (T,) tokens.
What this PR does. In numerical_tests_qwen3_5.py, it adds patch_order="block" to the SimpleNamespace stand-in for the collator. It also adds a helper that squeezes the HF input_ids from (1, S) to (S,) before calling MultiModalCollator._build_mrope_positions, so positions come back as (S, 3), the rank that MRoPE._reshape_cache dispatches on. It also adds a 150-line CPU test file. The diagnosis of the two errors is correct (mm_collator.py:218, :230-232).
Example.
# main: build_inputs
_build_mrope_positions(SimpleNamespace(spatial_merge_size=2), ids_1S, ...) # AttributeError
# this PR: build_inputs passes; then run_tt
model(ids_1S, pixel_values=patches_1NP, positions=pos_S3, ...)
# _prepare_multimodal_embeds -> (1, S, D); Qwen35Attention: num_tokens = x_TD.shape[0] == 1
logits[:, -1:, :] # model returns (T, V): too many indicesMust fix
- The
## Summary (human-written)section is empty. The author needs to write it. scripts/checkpoint_conversion/numerical_tests_qwen3_5.py:205-- the tensors stored intt_inputsand read inrun_tt(tokens(1, S),patches.unsqueeze(0),logits[:, -1:, :]) still use the old batched layout. The real problem is that this script was never migrated to packed 1-D tokens. Fixing positions alone moves the failure frombuild_inputstorun_tt. Migrate the whole script, and run it once against a checkpoint. "Numerics: Not run" isn't enough for a script whose only job is a numerics check.scripts/checkpoint_conversion/numerical_tests_qwen3_5.py:84-123-- the single-use helper isn't needed onceinput_idsis squeezed at the source. Inline the call again.tests/unit_tests/cpu/scripts/test_qwen35_numerical_mrope.py-- delete it. It greps source code, retests Python attribute lookup, and turns import failures into skips.
Details
The smallest correct change is roughly 10 lines, all in numerical_tests_qwen3_5.py:
build_inputs: addpatch_order="block";input_ids_S = hf_in["input_ids"].squeeze(0); passinput_ids_Sto the existing inline_build_mrope_positionscall; store(input_ids_S, patches, grid_thw.unsqueeze(0), mrope_positions).run_tt:outputs.append(logits[-1:].unsqueeze(0).cpu()), or any form that matches the(1, 1, V)shaperun_hfreturns, socomparestays the same.
The custom _SDPA in run_tt already works with THK (transpose(1, 2) gives (H, T, K)), so it should not need changes. Unverified: whether anything else in the forward still assumes a batch dim. Running the script will show that.
#5153 touches run_tt's model build. Fixing the run_tt forward loop is in a different hunk, so a conflict is unlikely.
The stale (batch, seq, 3) comment at torchtitan/models/qwen3_5/model.py:714-715 comes from the same packed-layout migration. A one-line fix to (num_tokens, 3) / (num_tokens,) could go in this PR, since it is the same contract.
Not verified: the run_tt failure was found by reading the code (model.py:158, :598, multimodal.py:144), not by running it on a GPU.
| # returns grid_thw of shape (3,); the collator wants (num_images, 3). | ||
| mrope_positions = _mrope_positions_for_forward( | ||
| mrope_builder, | ||
| hf_in["input_ids"], |
There was a problem hiding this comment.
The positions are fixed, but the tt_inputs tuple built a few lines below still stores hf_in["input_ids"] as (1, S) and patches.unsqueeze(0) as (1, N, P). run_tt passes both to Qwen35Model.forward, and that forward is packed now: _prepare_multimodal_embeds returns (num_tokens, dim), Qwen35Attention.forward reads num_tokens = x_TD.shape[0], and get_vision_positions / scatter_vision_embeds expect (T,) / (T, D). So with (1, S) tokens the forward fails, or silently uses T = 1, after this line. logits[:, -1:, :] in run_tt also assumes 3-D logits, but the model returns (T, V).
The fix: squeeze once at the source and store packed tensors. For example input_ids_S = hf_in["input_ids"].squeeze(0), then use it in both this call and tt_inputs, store patches without the unsqueeze(0), and use logits[-1:] in run_tt. With that, _build_mrope_positions can be called inline with input_ids_S and the helper isn't needed.
There was a problem hiding this comment.
Squeezed input_ids once in build_inputs and stored that row with patches (no extra batch axis). grid_thw.unsqueeze(0) stays. run_tt takes logits[-1:].unsqueeze(0) so compare still sees (1, 1, V).
_SDPA was still transpose(1, 2), the old (B, L, H, K) layout. Packed Q/K/V are (T, H, K). The kernel boundary matches FlexInnerAttention: transpose(0, 1).unsqueeze(0) to (1, H, T, K), then the inverse. transpose(1, 2) would put head_dim on the sequence axis, and GQA would see different query and key sizes. Applied in 617a6af. The GPU script was not run.
| def _mrope_positions_for_forward( | ||
| mrope_builder, | ||
| tokens, | ||
| grid_thw, | ||
| *, | ||
| image_token_id, | ||
| video_token_id, | ||
| ): | ||
| """Return MRoPE positions at the rank Qwen3.5 MRoPE indexes. | ||
|
|
||
| The collator wants a 1-D token row and returns ``(num_tokens, 3)``. | ||
| ``MRoPE._reshape_cache`` takes that rank (``ndim == 2``, last dim 3). | ||
| A rank-3 ``(1, S, 3)`` tensor is not the MRoPE path. HF ``input_ids`` | ||
| arrive as ``(1, S)``; drop a leading batch of 1 before the call. | ||
|
|
||
| Args: | ||
| mrope_builder: Stand-in with ``spatial_merge_size`` and ``patch_order``. | ||
| tokens: Token ids, ``(num_tokens,)`` or ``(1, num_tokens)``. | ||
| grid_thw: Image grid ``(num_images, 3)``, or None when unused. | ||
| image_token_id: Placeholder id for image spans. | ||
| video_token_id: Placeholder id for video spans. | ||
|
|
||
| Returns: | ||
| ``(num_tokens, 3)`` temporal, height, and width position ids. | ||
| """ | ||
| if tokens.ndim == 2 and tokens.shape[0] == 1: | ||
| tokens = tokens.squeeze(0) | ||
| if tokens.ndim != 1: | ||
| raise ValueError( | ||
| f"MRoPE tokens must be a 1-D row, got shape {tuple(tokens.shape)}." | ||
| ) | ||
| return MultiModalCollator._build_mrope_positions( | ||
| mrope_builder, # pyrefly: ignore [bad-argument-type] | ||
| tokens, | ||
| grid_thw, | ||
| None, | ||
| None, | ||
| image_token_id=image_token_id, | ||
| video_token_id=video_token_id, | ||
| ) |
There was a problem hiding this comment.
This 40-line helper has one call site, and it only handles a shape that the call site controls. It accepts both (S,) and (1, S) and raises on anything else, but build_inputs always passes (1, S). Delete it. Squeeze input_ids once in build_inputs (see the comment at line 205) and keep the original inline MultiModalCollator._build_mrope_positions(...) call. Then the only change needed at the call site is the (S,) row.
There was a problem hiding this comment.
Inlined. _mrope_positions_for_forward is gone. build_inputs squeezes hf_in["input_ids"] and calls MultiModalCollator._build_mrope_positions directly. Positions stay (S, 3). 617a6af.
| class TestQwen35NumericalMropeSource(unittest.TestCase): | ||
| """Source checks that run without importing torchtitan.""" | ||
|
|
||
| def test_script_matches_collator_mrope_contract(self): | ||
| source = _SCRIPT.read_text() | ||
| tree = ast.parse(source) | ||
| has_block_order = any( | ||
| isinstance(node, ast.keyword) | ||
| and node.arg == "patch_order" | ||
| and isinstance(node.value, ast.Constant) | ||
| and node.value.value == "block" | ||
| for node in ast.walk(tree) | ||
| ) | ||
| self.assertTrue( | ||
| has_block_order, | ||
| 'numerical script must pass patch_order="block" into the MRoPE builder', | ||
| ) | ||
| self.assertIn('patch_order="block"', source) | ||
|
|
||
| saw_mrope_call = False | ||
| for call in ast.walk(tree): | ||
| if not isinstance(call, ast.Call): | ||
| continue | ||
| func = call.func | ||
| if not ( | ||
| isinstance(func, ast.Attribute) | ||
| and func.attr == "_build_mrope_positions" | ||
| ): | ||
| continue | ||
| saw_mrope_call = True | ||
| arguments = list(call.args) + [kw.value for kw in call.keywords] | ||
| for arg in arguments: | ||
| self.assertFalse( | ||
| _is_raw_hf_input_ids(arg), | ||
| "raw hf_in['input_ids'] is passed into _build_mrope_positions", | ||
| ) | ||
| self.assertTrue( | ||
| saw_mrope_call, | ||
| "numerical script must still call _build_mrope_positions", |
There was a problem hiding this comment.
Please delete this test file. None of its three tests earns its CI cost (.claude/rules/tests.md):
test_script_matches_collator_mrope_contractparses the script's source and checks for the literalpatch_order="block". That is a grep of the code, and it doesn't check runtime behavior.test_text_row_positions_match_on_all_axescovers the helper, which should be inlined. Without image tokens it only exercises the collator's text-onlyarangepath.test_builder_without_patch_order_raisesasserts that aSimpleNamespacewithout an attribute raisesAttributeError, which is Python behavior.
Also, _load_* turns any Exception into SkipTest, so a real import regression shows up as a skip, not a failure. Locally both runtime tests skipped. This script needs a GPU and a checkpoint, so the real check is running it once.
There was a problem hiding this comment.
Deleted tests/unit_tests/cpu/scripts/test_qwen35_numerical_mrope.py. The source walk stayed green while tt_inputs still stored (1, S) tokens and (1, N, P) patches. 617a6af.
|
@claude review again |
|
Claude finished @tianyu-l's task in 1m 35s —— View job Approve, but please address the items below before merging: every code item from the last review is resolved. Before merging, the human-written summary needs filling in and the script needs one run against a checkpoint. See review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The script now passes packed tensors end to end (build_inputs -> run_tt -> compare), and every code item from the last review is resolved.
What changed since the last review (617a6af). build_inputs squeezes input_ids once to (S,) and calls _build_mrope_positions inline, so positions come back as (S, 3). tt_inputs stores (S,) tokens, (N, P) patches, and a (1, 3) grid. run_tt takes logits[-1:].unsqueeze(0), which matches HF's (1, 1, V). The _SDPA reference now converts packed (T, H, K) the same way FlexInnerAttention does (attention.py:660-682). The helper and the CPU test are deleted.
Example.
# before: build_inputs raised AttributeError (no patch_order), then ValueError ((1, S) tokens)
# after:
tokens_S, patches_NP, grid_13, pos_S3 = tt_inputs[0]
logits_TV = model(tokens_S, pixel_values=patches_NP, grid_thw=grid_13, positions=pos_S3, ...)
logits_TV[-1:].unsqueeze(0) # (1, 1, V), same as run_hf
# _SDPA: q_THK -> (1, H, T, K) -> SDPA -> (T, H, V) (text: Qwen35Attention, vision: VisionAttention)Earlier must-fix items
- Script still batched in
tt_inputs/run_tt: resolved. - Single-use
_mrope_positions_for_forwardhelper: resolved (inlined). - CPU test that greps the source: resolved (deleted).
- Correction to my last review: I said
_SDPA"already works withTHK". That was wrong. With(T, H, K)inputs,transpose(1, 2)gives(T, K, H), not(H, T, K). The author'stranspose(0, 1).unsqueeze(0)fix is correct.
Must fix
- The
## Summary (human-written)section is still empty. The author needs to write it. - Run the script once against a Qwen3.5 checkpoint and paste the KL / top-1 / pixel-match output in the PR. The changes check out by reading the code, but this script exists to check numerics, so one real run is the proof it works. Whoever has a GPU and the checkpoint can do it.
Should consider
torchtitan/models/qwen3_5/model.py:714-715still sayspositionsis(batch, seq, 3)/(batch, seq). The real contract is(num_tokens, 3)/(num_tokens,). This is a one-line fix in this PR or a follow-up. Leaving it to anothermodel.pyPR is fine too.
Details
Checked at HEAD:
- Text path:
Qwen35Attention.forward(model.py:158-185) passesxq_THK/xk_THK/xv_THVwithscaleandenable_gqa._SDPApasses both through, andenable_gqanow sees matching head-dim axes.attention_metadataisNonebecauserun_ttdoesn't pass it (model.py:724-728), so the single-document guard holds. - GDN layers get
attention_metadata=Noneand run withcu_seqlens=None(gdn.py:413-414), which is correct for one document. - Vision path:
VisionAttention.forward(common/vision_encoder.py:219-223) callsself.flex_attentionwith(T, H, Dh). The non-causal_SDPAignores the block-diagonal mask, which is correct for one image per sample.Qwen35VisionEncoder.forwardcheckspixel_values.shape[0]against the grid (vision_encoder.py:422-428), and(N, P)patches pass that check. - No conflict with #5153 (model build) or #5728 (
mm_collator.py).
Not verified: the end-to-end GPU run (see must-fix 2).
Summary (human-written)
Why
scripts/checkpoint_conversion/numerical_tests_qwen3_5.pybuilds MRoPE ids inbuild_inputsby callingMultiModalCollator._build_mrope_positionson atypes.SimpleNamespace(spatial_merge_size=merge_size)and onhf_in["input_ids"].The method reads
self.patch_orderfirst and raisesValueErrorunless it is"block". The stand-in has nopatch_order, so the call raisesAttributeErrorbefore that check. The real collator default is"block".The method docstring says
tokensis(num_tokens,). It doestokens.unsqueeze(0)and later returnsmrope_positions.squeeze(0), shape(num_tokens, 3).processor.apply_chat_template(..., return_tensors="pt")yieldsinput_idsof shape(1, S). Unsqueeze makes that(1, 1, S), andbatch_size, seq_len = tokens.shaperaisesValueError: too many values to unpack (expected 2).Qwen35Model.forwarddoes not indexpositionsitself. It passes them to each layer.MRoPE._reshape_cacheuses the 3-axis cache only whenpositions.ndim == 2and the last dimension is 3, i.e.(num_tokens, 3). The collator already returns that rank aftersqueeze(0), andpreprocess_inputsforwards the same rank. A stored(1, S, 3)tensor would skip MRoPE and fall through to plain RoPE. The old script comment asked for(1, S, 3); that comment does not match the index. The forward comment that still says(batch, seq, 3)is the same mismatch and is left alone.vision_to_patchesreturnsgrid_thwof shape(3,). The collator indexesgrid_thw[image_index]as one image's(t, h, w), sogrid_thw.unsqueeze(0)to(num_images, 3)stays.Example.
With
patch_order="block"but the same(1, 5)tokens:build_inputsnow squeezes the processor row to(S,)before the collator call, so positions come back(S, 3).tt_inputsstores that row andpatchesof shape(N, P).run_ttreads packed(T, V)logits.What changed
build_inputssetspatch_order="block", squeezeshf_in["input_ids"]to(S,), and callsMultiModalCollator._build_mrope_positionsinline. The one-off helper is gone.(S,), patches(N, P),grid_thw(num_images, 3), positions(S, 3).patches.unsqueeze(0)is gone.grid_thw.unsqueeze(0)stays.run_tt's reference SDPA takes packed(T, H, K)the wayFlexInnerAttentiondoes:transpose(0, 1).unsqueeze(0)to(1, H, T, K), then the inverse.transpose(1, 2)was the old(B, L, H, K)layout.logits[-1:].unsqueeze(0), shape(1, 1, V), matchingrun_hf.tests/unit_tests/cpu/scripts/test_qwen35_numerical_mrope.py. It grepped the script and skipped on import.mm_collator.pyis unchanged. Themodel.half()/to_empty/init_statesorder inrun_ttis unchanged.Alternatives considered
(S,)and(1, S). No.build_inputsis the only caller and it owns the processor row.run_tton batched(1, S)tokens and(1, N, P)patches. No. The vision encoder checkspixel_values.shape[0]against the patch grid, and the text forward is packed(num_tokens,)._SDPAontranspose(1, 2). No. That swaps heads withhead_dimonce Q/K/V are(T, H, K). GQA then sees different query and key embedding sizes._build_mrope_positionstreat a missingpatch_orderas"block". No. The method already requires"block". [BC][engine] One sum-then-scale path: losses return sums, optim_step divides by the step's loss-token count #5728 ownsmm_collator.py.(1, S, 3). No. Rank 3 is not the MRoPE path inMRoPE._reshape_cache.MultiModalCollator. No. That needs a dataset context and a tokenizer.User-facing changes
build_inputsraisesAttributeErrorbecause the MRoPE stand-in has nopatch_orderpatch_order="block"input_ids(1, S)make_build_mrope_positionsraiseValueErroron the shape unpack(S, 3)run_ttpasses tokens(1, S)and patches(1, N, P)into a packed forward(S,), patches(N, P)logits[:, -1:, :]assumes 3-D logitslogits[-1:].unsqueeze(0)matches HF(1, 1, V)Numerics
Not run. The script needs a downloaded Qwen3.5 checkpoint and a GPU. This does not change a training step. It changes the script's forward shapes so that check can run.
Testing
py_compileofscripts/checkpoint_conversion/numerical_tests_qwen3_5.pysucceeded with/opt/homebrew/anaconda3/bin/python. The script was not executed. There is no local checkpoint and no GPU.The CPU test file was removed. It AST-walked the source, asserted
AttributeErrorfor a missing attribute, and turned import errors into skips. An existingtests/unit_tests/cpu/models/qwen3_5/test_qwen3_5_mrope_positions.pyalready locks the(num_tokens, 3)contract. This machine still cannot collect that file (spmd_typeshas norules).Known issues / follow-ups
#5153 is open and edits this script only around model construction: it moves
model.half()beforeto_empty/init_statesand factors_build_tt_model. This PR does not touch those lines. The SDPA and logit-index edits are later inrun_tt.#5728 edits
mm_collator.py. This PR does not.Qwen35Model.forwardstill comments that multimodalpositionsare(batch, seq, 3).MRoPE._reshape_cacheandpreprocess_inputsuse(num_tokens, 3). Not changed here. Open PRs already editmodel.py.