Skip to content

[scripts] Build Qwen3.5 MRoPE positions with the collator contract - #5758

Merged
tianyu-l merged 5 commits into
pytorch:mainfrom
YeonwooSung:pr/fix-qwen35-numerical-mrope
Nov 3, 2026
Merged

tianyu-l merged 5 commits into
pytorch:mainfrom
YeonwooSung:pr/fix-qwen35-numerical-mrope

Conversation

@YeonwooSung

@YeonwooSung YeonwooSung commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Why

scripts/checkpoint_conversion/numerical_tests_qwen3_5.py builds MRoPE ids in build_inputs by calling MultiModalCollator._build_mrope_positions on a types.SimpleNamespace(spatial_merge_size=merge_size) and on hf_in["input_ids"].

The method reads self.patch_order first and raises ValueError unless it is "block". The stand-in has no patch_order, so the call raises AttributeError before that check. The real collator default is "block".

The method docstring says tokens is (num_tokens,). It does tokens.unsqueeze(0) and later returns mrope_positions.squeeze(0), shape (num_tokens, 3). processor.apply_chat_template(..., return_tensors="pt") yields input_ids of shape (1, S). Unsqueeze makes that (1, 1, S), and batch_size, seq_len = tokens.shape raises ValueError: too many values to unpack (expected 2).

Qwen35Model.forward does not index positions itself. It passes them to each layer. MRoPE._reshape_cache uses the 3-axis cache only when positions.ndim == 2 and the last dimension is 3, i.e. (num_tokens, 3). The collator already returns that rank after squeeze(0), and preprocess_inputs forwards 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_patches returns grid_thw of shape (3,). The collator indexes grid_thw[image_index] as one image's (t, h, w), so grid_thw.unsqueeze(0) to (num_images, 3) stays.

Example.

mrope_builder = types.SimpleNamespace(spatial_merge_size=2)
MultiModalCollator._build_mrope_positions(
    mrope_builder,
    torch.zeros(1, 5, dtype=torch.long),  # HF input_ids
    torch.zeros(1, 3),
    None,
    None,
    image_token_id=99,
    video_token_id=98,
)
# AttributeError: 'types.SimpleNamespace' object has no attribute 'patch_order'

With patch_order="block" but the same (1, 5) tokens:

ValueError: too many values to unpack (expected 2)

build_inputs now squeezes the processor row to (S,) before the collator call, so positions come back (S, 3). tt_inputs stores that row and patches of shape (N, P). run_tt reads packed (T, V) logits.

What changed

  • build_inputs sets patch_order="block", squeezes hf_in["input_ids"] to (S,), and calls MultiModalCollator._build_mrope_positions inline. The one-off helper is gone.
  • Stored tensors match the packed forward: tokens (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 way FlexInnerAttention does: transpose(0, 1).unsqueeze(0) to (1, H, T, K), then the inverse. transpose(1, 2) was the old (B, L, H, K) layout.
  • Last-token logits are logits[-1:].unsqueeze(0), shape (1, 1, V), matching run_hf.
  • Deleted tests/unit_tests/cpu/scripts/test_qwen35_numerical_mrope.py. It grepped the script and skipped on import.

mm_collator.py is unchanged. The model.half() / to_empty / init_states order in run_tt is unchanged.

Alternatives considered

  • Keep a helper that accepts both (S,) and (1, S). No. build_inputs is the only caller and it owns the processor row.
  • Leave run_tt on batched (1, S) tokens and (1, N, P) patches. No. The vision encoder checks pixel_values.shape[0] against the patch grid, and the text forward is packed (num_tokens,).
  • Leave _SDPA on transpose(1, 2). No. That swaps heads with head_dim once Q/K/V are (T, H, K). GQA then sees different query and key embedding sizes.
  • Make _build_mrope_positions treat a missing patch_order as "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 owns mm_collator.py.
  • Unsqueeze positions to (1, S, 3). No. Rank 3 is not the MRoPE path in MRoPE._reshape_cache.
  • Construct a real MultiModalCollator. No. That needs a dataset context and a tokenizer.

User-facing changes

Before After
build_inputs raises AttributeError because the MRoPE stand-in has no patch_order The stand-in sets patch_order="block"
Processor input_ids (1, S) make _build_mrope_positions raise ValueError on the shape unpack The call gets a 1-D row. Stored positions are (S, 3)
run_tt passes tokens (1, S) and patches (1, N, P) into a packed forward tokens (S,), patches (N, P)
logits[:, -1:, :] assumes 3-D logits logits[-1:].unsqueeze(0) matches HF (1, 1, V)
No config or CLI flag No config or CLI flag

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_compile of scripts/checkpoint_conversion/numerical_tests_qwen3_5.py succeeded 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 AttributeError for a missing attribute, and turned import errors into skips. An existing tests/unit_tests/cpu/models/qwen3_5/test_qwen3_5_mrope_positions.py already locks the (num_tokens, 3) contract. This machine still cannot collect that file (spmd_types has no rules).

Known issues / follow-ups

#5153 is open and edits this script only around model construction: it moves model.half() before to_empty / init_states and factors _build_tt_model. This PR does not touch those lines. The SDPA and logit-index edits are later in run_tt.

#5728 edits mm_collator.py. This PR does not.

Qwen35Model.forward still comments that multimodal positions are (batch, seq, 3). MRoPE._reshape_cache and preprocess_inputs use (num_tokens, 3). Not changed here. Open PRs already edit model.py.

@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 3, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 3, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@github-actions
github-actions Bot requested a review from ivy-zhou November 3, 2026 02:20
@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 18s —— View job


Request changes: the MRoPE positions fix is right, but run_tt still passes batched (1, S) inputs to the packed-token model, so the script still fails. See review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 indices

Must fix

  1. The ## Summary (human-written) section is empty. The author needs to write it.
  2. scripts/checkpoint_conversion/numerical_tests_qwen3_5.py:205 -- the tensors stored in tt_inputs and read in run_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 from build_inputs to run_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.
  3. scripts/checkpoint_conversion/numerical_tests_qwen3_5.py:84-123 -- the single-use helper isn't needed once input_ids is squeezed at the source. Inline the call again.
  4. 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: add patch_order="block"; input_ids_S = hf_in["input_ids"].squeeze(0); pass input_ids_S to the existing inline _build_mrope_positions call; 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) shape run_hf returns, so compare stays 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"],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +84 to +123
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,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +59 to +97
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",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please delete this test file. None of its three tests earns its CI cost (.claude/rules/tests.md):

  • test_script_matches_collator_mrope_contract parses the script's source and checks for the literal patch_order="block". That is a grep of the code, and it doesn't check runtime behavior.
  • test_text_row_positions_match_on_all_axes covers the helper, which should be inlined. Without image tokens it only exercises the collator's text-only arange path.
  • test_builder_without_patch_order_raises asserts that a SimpleNamespace without an attribute raises AttributeError, 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

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

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. Script still batched in tt_inputs / run_tt: resolved.
  2. Single-use _mrope_positions_for_forward helper: resolved (inlined).
  3. CPU test that greps the source: resolved (deleted).
  4. Correction to my last review: I said _SDPA "already works with THK". That was wrong. With (T, H, K) inputs, transpose(1, 2) gives (T, K, H), not (H, T, K). The author's transpose(0, 1).unsqueeze(0) fix is correct.

Must fix

  1. The ## Summary (human-written) section is still empty. The author needs to write it.
  2. 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-715 still says positions is (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 another model.py PR is fine too.
Details

Checked at HEAD:

  • Text path: Qwen35Attention.forward (model.py:158-185) passes xq_THK/xk_THK/xv_THV with scale and enable_gqa. _SDPA passes both through, and enable_gqa now sees matching head-dim axes. attention_metadata is None because run_tt doesn't pass it (model.py:724-728), so the single-document guard holds.
  • GDN layers get attention_metadata=None and run with cu_seqlens=None (gdn.py:413-414), which is correct for one document.
  • Vision path: VisionAttention.forward (common/vision_encoder.py:219-223) calls self.flex_attention with (T, H, Dh). The non-causal _SDPA ignores the block-diagonal mask, which is correct for one image per sample. Qwen35VisionEncoder.forward checks pixel_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).

@tianyu-l
tianyu-l merged commit 96b6f0a into pytorch:main Nov 3, 2026
@YeonwooSung
YeonwooSung deleted the pr/fix-qwen35-numerical-mrope branch November 3, 2026 04:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants