[Perf] Reuse single-element media tensors in qwen3_vl_sft_collator and SequenceContext.cat (follow-up of #2239)
Background
#2239 removed full torch.cat copies for single-media packs on the GLM-5.3 SFT
path (collator helper _reuse_single_or_cat, tokenize fn, and the compose model
entry). The same "single-element list still pays a full copy" pattern remains at
two sites outside that PR's scope:
-
qwen3_vl_sft_collator—xtuner/v1/datasets/collator.py:280,287:pixel_values/image_grid_thware unconditionallytorch.cat-ed even when the pack contains a single media item. The_reuse_single_or_cathelper added in #2239 sits in the same file and can be applied directly. -
SequenceContext.cat—xtuner/v1/data_proto/sequence_context.py:393-403(pixel_values/pixel_values_videos) and:415,418(image_grid_thw/video_grid_thw): single-element lists are unconditionally copied. This is on the RL path — the RL controller merges seq_ctx lists viaSequenceContext.cat(xtuner/v1/rl/trainer/controller.py:236).
Impact
No correctness issue today. GLM-5.3 SFT does not go through either site, so this is pure follow-up: qwen3_vl SFT benefits for single-media packs; the RL path benefits if rollout packing of media seq_ctx becomes hot.
Suggested fix
- Apply the same
len == 1 → reuse, else catpattern at both sites. - Mind the invariant pinned in #2239: a reused tensor shares storage with its source, so the downstream path must stay read-only — add the same kind of comment + a "media tensor bitwise unchanged after use" test assertion.
Taking this one — apply _reuse_single_or_cat at both sites (qwen3_vl_sft_collator and SequenceContext.cat), keep the read-only invariant comment from #2239, and add the bitwise-unchanged test assertion. PR shortly. (Prepared with an AI coding agent at my direction; the PR will note the same.)
One note after cloning: the _reuse_single_or_cat helper this issue references lives in #2239, which is still open, so it isn't on main yet. I'll hold this follow-up until #2239 merges (executing now would duplicate the helper and conflict) — and will put the PR up promptly once it lands. If you'd rather I implement the len == 1 reuse inline instead of reusing the helper, happy to do that sooner; otherwise this stays blocked on #2239 by design.
Prerequisite #2239 is merged, so the held follow-up is up as promised: #2254.