xtuner icon indicating copy to clipboard operation
xtuner copied to clipboard

[Perf] Reuse single-element media tensors in qwen3_vl_sft_collator and SequenceContext.cat (follow-up of #2239)

Open ShilohYu opened this issue 4 weeks ago • 3 comments

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:

  1. qwen3_vl_sft_collator — xtuner/v1/datasets/collator.py:280,287: pixel_values / image_grid_thw are unconditionally torch.cat-ed even when the pack contains a single media item. The _reuse_single_or_cat helper added in #2239 sits in the same file and can be applied directly.

  2. 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 via SequenceContext.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 cat pattern 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.

ShilohYu avatar Nov 03 '26 14:11 ShilohYu

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.)

Sainath-Reddy7 avatar Nov 03 '26 15:11 Sainath-Reddy7

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.

Sainath-Reddy7 avatar Nov 03 '26 15:11 Sainath-Reddy7

Prerequisite #2239 is merged, so the held follow-up is up as promised: #2254.

Sainath-Reddy7 avatar Nov 04 '26 10:11 Sainath-Reddy7