From 0af5506215ace5f9882c1e579f6f026bcff0a3e4 Mon Sep 17 00:00:00 2001 From: Hubert <163992334+hubert-marek@users.noreply.github.com> Date: Mon, 20 Jul 2026 20:33:51 -0700 Subject: [PATCH] feat(sft): multimodal (VLM) SFT (#3075) * feat(sft): multimodal (VLM) SFT Renderer-produced multimodal samples flow end to end through SFT: - SFTDataset keeps the renderer's MultiModalData: image-safe truncation (never cuts inside a placeholder run, drops truncated-out images, and skips samples whose EOS was truncated away), mm_token_type_ids kept aligned through EOS append and causal shift, video inputs rejected explicitly. _flatten_mm_items folds per-image processor outputs into model-forward kwargs (pixel_values, image_grid_thw, ...). - Cat packing concatenates mm_kwargs across samples in a pack and represents text-only spans as zeros in mm_token_type_ids; stack bucketing emits multimodal samples solo. Collates move mm tensors to CUDA and keep packed rows batch-size 1. - Local data_files normalization wraps string message content into typed content blocks under a multimodal flag so Arrow can unify text and image rows. - setup_processor loads the AutoProcessor and attaches it to the renderer; VLM SFT fails fast without one; weight checkpoints save the processor alongside the tokenizer. - Dense Qwen3.5 gains the composite VLM body (HF vision encoder + custom text model) with MRoPE positions from mm_token_type_ids and registers in _CUSTOM_VLM_MAPPING; VLM training requires a custom PrimeRL implementation. Both dense and MoE VLM bodies always run the vision encoder (dummy input on text-only microbatches, kept in the backward graph) for FSDP/EP collective symmetry. - Config: VLM SFT requires micro_batch_size=1; unfreezing the vision encoder is incompatible with LoRA; the renderer-vs-VLM rejection is gone (renderers own multimodal tokenization now). --- README.md | 2 +- .../ci/nightly/multimodal_color_codeword.toml | 5 +- docs/advanced.md | 16 +- docs/training.md | 3 +- examples/vlm_sft/sft.toml | 35 ++++ examples/vlm_sft_moe/sft.toml | 55 ++++++ .../src/prime_rl/configs/sft.py | 34 +++- .../src/prime_rl/configs/shared.py | 2 +- .../src/prime_rl/configs/trainer.py | 6 + src/prime_rl/trainer/ckpt.py | 9 +- src/prime_rl/trainer/lora.py | 3 +- src/prime_rl/trainer/model.py | 66 +++++-- src/prime_rl/trainer/models/__init__.py | 1 + src/prime_rl/trainer/models/layers/lm_head.py | 10 +- .../models/qwen3_5/modeling_qwen3_5.py | 170 ++++++++++++++++-- .../qwen3_5_moe/modeling_qwen3_5_moe.py | 98 +++++----- src/prime_rl/trainer/sft/data.py | 141 ++++++++++++++- src/prime_rl/trainer/sft/train.py | 27 ++- .../unit/train/models/test_qwen3_5_moe_vlm.py | 42 ----- tests/unit/train/sft/test_sft_dataset.py | 109 ++++++++++- 20 files changed, 660 insertions(+), 174 deletions(-) create mode 100644 examples/vlm_sft/sft.toml create mode 100644 examples/vlm_sft_moe/sft.toml diff --git a/README.md b/README.md index 33b51244..3f6ebf15 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac | GLM-5 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8` | yes | ✅ | ✅ | | Qwen3 MoE (`qwen3_moe`) | `Qwen/Qwen3-30B-A3B`, … | yes | ✅ | ✅ | | Qwen3.5 MoE (`qwen3_5_moe`) | `Qwen/Qwen3.5-35B-A3B`, … | yes | ✅ | ✅ | -| Qwen3 / Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#multimodal-training) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ | +| Qwen3 / Qwen3.5 VLMs | see [advanced.md](docs/advanced.md#multimodal-training) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ❌ | | Poolside Laguna (`laguna`) | `poolside/Laguna-XS.2` | yes | ✅ | ✅ | | MiniMax M2 (`minimax_m2`) | `MiniMax/MiniMax-M2` | yes | ✅ | ✅ | | Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ✅ | diff --git a/configs/ci/nightly/multimodal_color_codeword.toml b/configs/ci/nightly/multimodal_color_codeword.toml index b8f6b458..be84b97c 100644 --- a/configs/ci/nightly/multimodal_color_codeword.toml +++ b/configs/ci/nightly/multimodal_color_codeword.toml @@ -1,4 +1,4 @@ -# Based on configs/multimodal/rl_color_codeword.toml but tuned for CI +# Based on configs/debug/multimodal.toml but tuned for CI. max_steps = 25 seq_len = 4096 @@ -7,7 +7,7 @@ num_train_gpus = 4 num_infer_gpus = 4 [model] -name = "Qwen/Qwen3-VL-4B-Instruct" +name = "Qwen/Qwen3.5-4B" [model.vlm] vision_encoder_attr = "model.visual" @@ -28,6 +28,7 @@ harness = { id = "null", runtime = { type = "subprocess" } } [trainer] [trainer.model] +impl = "custom" optimization_dtype = "bfloat16" reduce_dtype = "bfloat16" diff --git a/docs/advanced.md b/docs/advanced.md index 5d829052..c4c1ba9b 100644 --- a/docs/advanced.md +++ b/docs/advanced.md @@ -28,7 +28,7 @@ impl = "custom" # or "hf" to force the HF path | GLM-5 / GLM-5.2 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8`, `zai-org/GLM-5.2`, `zai-org/GLM-5.2-FP8` | ✅ | ✅ | | Qwen3 MoE | `Qwen/Qwen3-30B-A3B`, … | ✅ | ✅ | | Qwen3.5 MoE | `Qwen/Qwen3.5-35B-A3B`, … | ✅ | ✅ | -| Qwen3 / Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ✅ | +| Qwen3 / Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ❌ | | Laguna | `poolside/Laguna-XS.2` | ✅ | ✅ | | MiniMax M2 | `MiniMax/MiniMax-M2` | ✅ | ✅ | | Nemotron H | `nvidia/Nemotron-3-Nano-30B-A3B`, … | ✅ | ❌ | @@ -72,20 +72,17 @@ The built-in VLM registry covers: | Family | `model_type` | Vision attr | LM attr | |---|---|---|---| -| Qwen3-VL | `qwen3_vl` | `model.visual` | `model.language_model` | -| Qwen3-VL MoE | `qwen3_vl_moe` | `model.visual` | `model.language_model` | | Qwen3.5 | `qwen3_5` | `model.visual` | `model.language_model` | | Qwen3.5-MoE | `qwen3_5_moe` | `model.visual` | `model.language_model` | -For a model not in the table, look up the attribute paths on the loaded HF model with `model.named_children()` and set them under `[model.vlm]` directly. - ### Enabling VLM Mode Add `[model.vlm]` and bfloat16 dtypes: ```toml [model] -name = "Qwen/Qwen3-VL-4B-Instruct" +name = "Qwen/Qwen3.5-4B" +impl = "custom" optimization_dtype = "bfloat16" reduce_dtype = "bfloat16" @@ -97,12 +94,11 @@ language_model_attr = "model.language_model" The weight-broadcast key prefix is derived as `{language_model_attr}.layers.` automatically. -To add a new model family permanently, append an entry to `VLM_REGISTRY` in `src/prime_rl/utils/vlm.py`. +VLM training requires a registered custom PrimeRL implementation. ### Limitations -- **Vision encoder frozen by default.** Set `freeze_vision_encoder = false` to fine-tune it; in that case it's FSDP-sharded per block. The combination `freeze_vision_encoder = false` + LoRA is rejected by a config validator — LoRA freezes everything non-adapter, so unfreezing the encoder under LoRA would be a silent no-op. -- **No multimodal-safe truncation.** Token sequences are truncated to `seq_len`, but `pixel_values` and `image_grid_thw` pass through unchanged. If a sample's tokens overflow, image tokens may get dropped while image tensors still describe the full image set. Set `seq_len` to cover your longest sample. +- **Vision encoder frozen by default.** The default LoRA targets do not match Qwen3.5 vision modules. Set `freeze_vision_encoder = false` to fine-tune the encoder; this is incompatible with LoRA because LoRA freezes all non-adapter parameters. - **bfloat16 mandatory.** The trainer config validator refuses any other `optimization_dtype` / `reduce_dtype` for VLMs — vLLM serves VLMs in bfloat16 and a mismatch breaks the importance ratio. - **Higher KL mismatch with multi-image inputs.** Expect noisier `mismatch_kl` than text-only; this is from minor numerical differences between the trainer's and vLLM's image processing. - **Images aren't logged to monitors.** Sample logging captures the prompt text but not the actual images. @@ -160,4 +156,4 @@ salloc -N 1 --gres=gpu:1 bash -c 'bash scripts/install_nixl_from_source.sh' uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl ``` -The script writes UCX 1.19 to `third_party/ucx/`; the bundled sbatch templates prepend it to `LD_LIBRARY_PATH` so it overrides the system version. Re-run both commands after every `uv sync`, since the lock pins the wheel. \ No newline at end of file +The script writes UCX 1.19 to `third_party/ucx/`; the bundled sbatch templates prepend it to `LD_LIBRARY_PATH` so it overrides the system version. Re-run both commands after every `uv sync`, since the lock pins the wheel. diff --git a/docs/training.md b/docs/training.md index ace9fcea..ce2bacae 100644 --- a/docs/training.md +++ b/docs/training.md @@ -156,8 +156,9 @@ enable_thinking = false If a model needs another template control, add it to that model's renderer config in `renderers` (for example a new field on the relevant `*RendererConfig`) and consume it in the renderer implementation. -**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `—` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS. +**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS, and VLM families such as Qwen3-VL/Qwen3.5. +**VLM training requires a custom PrimeRL implementation.** Training a model with `[model.vlm]` set (SFT or RL) requires `model.impl = "custom"` and only works for models with a registered PrimeRL VLM class (currently Qwen3.5 dense and MoE). See [Algorithms § Multi-Turn Trajectories](algorithms.md#multi-turn-trajectories) for the full picture. diff --git a/examples/vlm_sft/sft.toml b/examples/vlm_sft/sft.toml new file mode 100644 index 00000000..6b8cd193 --- /dev/null +++ b/examples/vlm_sft/sft.toml @@ -0,0 +1,35 @@ +max_steps = 20 + +[ckpt] +[ckpt.weights] +save_adapter_separately = true + +[model] +name = "Qwen/Qwen3.5-0.8B" +optimization_dtype = "bfloat16" +reduce_dtype = "bfloat16" +impl = "custom" + +[renderer] +name = "auto" + +[model.vlm] +vision_encoder_attr = "model.visual" +language_model_attr = "model.language_model" +freeze_vision_encoder = true + +[model.lora] +rank = 16 + +[model.ac] +freq = 1 + +[data] +type = "sft" +name = "your-org/your-multimodal-dataset" +batch_size = 1 +micro_batch_size = 1 +seq_len = 16384 + +[optim] +lr = 1e-5 diff --git a/examples/vlm_sft_moe/sft.toml b/examples/vlm_sft_moe/sft.toml new file mode 100644 index 00000000..4bdf43bc --- /dev/null +++ b/examples/vlm_sft_moe/sft.toml @@ -0,0 +1,55 @@ +# Multimodal (VLM) SFT on a Mixture-of-Experts model — single 8xH200 node. +max_steps = 1000 +dist_timeout_seconds = 3600 + +[model] +name = "Qwen/Qwen3.6-35B-A3B" +optimization_dtype = "bfloat16" +reduce_dtype = "bfloat16" +impl = "custom" +attn = "flash_attention_2" +ep = 8 # keep in sync with deployment.num_gpus + +[renderer] +name = "auto" + +[model.vlm] +vision_encoder_attr = "model.visual" +language_model_attr = "model.language_model" +freeze_vision_encoder = true + +[model.lora] +rank = 32 +alpha = 32 +target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", "experts"] + +# MoE + mode="full" recomputes the router, whose non-deterministic top-k routing +# raises CheckpointError; selective AC excluding routed_experts avoids that. +[model.ac] +mode = "selective" +targets = ["norm", "attn_proj", "linear_attn"] + +[data] +type = "sft" +name = "your-org/your-multimodal-dataset" +batch_size = 8 +micro_batch_size = 1 # required for VLM SFT +seq_len = 16384 + +[data.loss_mask] +system = false +user = false +assistant = true +tool = false + +[optim] +lr = 1e-5 + +[ckpt] +interval = 200 +[ckpt.weights] +save_adapter_separately = true + +[deployment] +type = "single_node" +num_gpus = 8 diff --git a/packages/prime-rl-configs/src/prime_rl/configs/sft.py b/packages/prime-rl-configs/src/prime_rl/configs/sft.py index ff052d37..401d9c02 100644 --- a/packages/prime-rl-configs/src/prime_rl/configs/sft.py +++ b/packages/prime-rl-configs/src/prime_rl/configs/sft.py @@ -301,6 +301,31 @@ class SFTConfig(BaseConfig): raise ValueError("Validation micro batch size must be 1 when CP is enabled") return self + @model_validator(mode="after") + def vlm_freeze_incompatible_with_lora(self): + if self.model.vlm is not None and not self.model.vlm.freeze_vision_encoder and self.model.lora is not None: + raise ValueError( + "freeze_vision_encoder=false is incompatible with LoRA. " + "LoRA freezes all non-adapter parameters including the vision encoder." + ) + return self + + @model_validator(mode="after") + def validate_vlm_constraints(self): + if self.model.vlm is None: + return self + if self.model.optimization_dtype != "bfloat16" or self.model.reduce_dtype != "bfloat16": + raise ValueError( + "VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference." + ) + if self.model.cp > 1: + raise ValueError("VLM SFT does not support context parallelism yet.") + if self.data.micro_batch_size != 1: + raise ValueError("VLM SFT requires data.micro_batch_size = 1.") + if self.val is not None and self.val.data.micro_batch_size != 1: + raise ValueError("VLM SFT requires val.data.micro_batch_size = 1.") + return self + @model_validator(mode="after") def dont_do_massive_traces(self): if self.trace_path: @@ -312,15 +337,6 @@ class SFTConfig(BaseConfig): ) return self - @model_validator(mode="after") - def validate_renderer_vs_vlm(self): - if self.model.vlm is not None: - raise ValueError( - "renderer-only SFT does not support VLMs yet. The renderer tokenizes " - "text-only message dicts client-side and cannot handle image inputs." - ) - return self - @model_validator(mode="after") def validate_lora_adapter_saving(self): if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately: diff --git a/packages/prime-rl-configs/src/prime_rl/configs/shared.py b/packages/prime-rl-configs/src/prime_rl/configs/shared.py index c63bcc9c..860736d9 100644 --- a/packages/prime-rl-configs/src/prime_rl/configs/shared.py +++ b/packages/prime-rl-configs/src/prime_rl/configs/shared.py @@ -94,7 +94,7 @@ class VLMConfig(BaseConfig): """Dotted attribute path to the language model module (e.g. ``model.language_model``).""" freeze_vision_encoder: bool = True - """Freeze the vision encoder. When False, it is trainable and FSDP-sharded per-block. No effect with LoRA (LoRA freezes all non-adapter parameters).""" + """Freeze the vision encoder parameters during training.""" class BaseModelConfig(BaseConfig): diff --git a/packages/prime-rl-configs/src/prime_rl/configs/trainer.py b/packages/prime-rl-configs/src/prime_rl/configs/trainer.py index 73e1051a..0ffe18d2 100644 --- a/packages/prime-rl-configs/src/prime_rl/configs/trainer.py +++ b/packages/prime-rl-configs/src/prime_rl/configs/trainer.py @@ -235,6 +235,12 @@ class ModelConfig(BaseModelConfig): raise ValueError("Trust remote code is only supported with the HF implementation or auto mode.") return self + @model_validator(mode="after") + def vlm_only_with_custom_impl(self): + if self.vlm is not None and self.impl != "custom": + raise ValueError("VLM training requires model.impl='custom'") + return self + @model_validator(mode="after") def cp_only_with_flash_attn(self): if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]: diff --git a/src/prime_rl/trainer/ckpt.py b/src/prime_rl/trainer/ckpt.py index d699b5f0..83728c8d 100644 --- a/src/prime_rl/trainer/ckpt.py +++ b/src/prime_rl/trainer/ckpt.py @@ -18,6 +18,7 @@ from torch.nn import Module from torch.optim.lr_scheduler import LRScheduler from torch.optim.optimizer import Optimizer from torchdata.stateful_dataloader import StatefulDataLoader +from transformers.processing_utils import ProcessorMixin from transformers.tokenization_utils import PreTrainedTokenizer from prime_rl.configs.trainer import CheckpointConfig, LoRAConfig, WeightCheckpointConfig @@ -377,6 +378,7 @@ class WeightCheckpointManager: lora_state_dict: dict[str, Tensor] | None, model, tokenizer: PreTrainedTokenizer, + processor: ProcessorMixin | None = None, ): """Save HF-compatible weight checkpoint to a given path.""" if self.world.is_master: @@ -403,6 +405,10 @@ class WeightCheckpointManager: gen_config = deepcopy(model.generation_config) gen_config.use_cache = True gen_config.save_pretrained(path) + # Processor first: it saves its own (unmodified) tokenizer, which the + # configured tokenizer (pad token, custom chat template) must override. + if processor is not None: + processor.save_pretrained(path) tokenizer.save_pretrained(path) if lora_state_dict is not None: @@ -426,6 +432,7 @@ class WeightCheckpointManager: step: int, model: nn.Module, tokenizer: PreTrainedTokenizer, + processor: ProcessorMixin | None = None, ): """Save a HF-compatible weight-only checkpoint for a given step.""" step_path = self.get_step_path(step) @@ -471,7 +478,7 @@ class WeightCheckpointManager: self.logger.debug(f"Reverted to HF hub format in {time.perf_counter() - start_time:.2f} seconds") # Save weight checkpoint on master rank - self.save_to_path(step_path, state_dict, lora_state_dict, model, tokenizer) + self.save_to_path(step_path, state_dict, lora_state_dict, model, tokenizer, processor) self.mark_stable(step) bisect.insort(self.ckpt_steps, step) diff --git a/src/prime_rl/trainer/lora.py b/src/prime_rl/trainer/lora.py index 11390360..e5b00036 100644 --- a/src/prime_rl/trainer/lora.py +++ b/src/prime_rl/trainer/lora.py @@ -162,8 +162,7 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None: ) if not target_modules: - logger.warning("No target modules found for LoRA. Check your target_modules patterns.") - return + raise ValueError(f"No LoRA target modules found for patterns {config.target_modules}.") for module_name in target_modules: base_module = _get_module_by_name(model, module_name) diff --git a/src/prime_rl/trainer/model.py b/src/prime_rl/trainer/model.py index 14ab8a1f..1b564d51 100644 --- a/src/prime_rl/trainer/model.py +++ b/src/prime_rl/trainer/model.py @@ -348,8 +348,8 @@ def freeze_moe_router(model: nn.Module) -> None: for param in mlp.router.parameters(): param.requires_grad = False num_frozen += 1 - # HuggingFace implementation: gate attribute (nn.Linear) - elif hasattr(mlp, "gate") and isinstance(mlp.gate, nn.Linear): + # HuggingFace implementation: gate may have been wrapped with LoRA. + elif hasattr(mlp, "gate") and isinstance(mlp.gate, nn.Module): for param in mlp.gate.parameters(): param.requires_grad = False num_frozen += 1 @@ -622,6 +622,12 @@ def get_model( f"but model.impl resolved to 'hf'. Set model.impl='custom' explicitly." ) + if config.vlm is not None and not (is_vlm_arch and custom_vlm_cls): + raise ValueError( + "VLM training requires a registered custom PrimeRL VLM implementation; " + f"{getattr(model_config, 'model_type', config.name)!r} has none." + ) + with device: if impl_to_use == "custom" and custom_vlm_cls is not None: model_cls = custom_vlm_cls @@ -653,10 +659,6 @@ def get_model( ) logger.debug(f"Loaded model {config.name} in {time.perf_counter() - load_model_start_time:.2f} seconds") - # For VLM models, optionally freeze the vision encoder - if is_vlm_training and config.vlm.freeze_vision_encoder: - freeze_vision_encoder(model, override_attr=config.vlm.vision_encoder_attr) - assert model.lm_head.weight.dtype == dtype, ( f"LM head dtype wasnt loaded correctly {model.lm_head.weight.dtype} != {dtype}" ) @@ -680,6 +682,23 @@ def setup_tokenizer(config: TokenizerConfig) -> PreTrainedTokenizer: return tokenizer +def setup_processor(config: ModelConfig): + """Load an ``AutoProcessor`` for VLM models. Returns ``None`` for text-only models.""" + from transformers import AutoProcessor + + logger = get_logger() + try: + processor = AutoProcessor.from_pretrained(config.name, trust_remote_code=config.trust_remote_code) + except (ValueError, OSError, KeyError) as e: + logger.debug(f"No AutoProcessor available for {config.name} ({type(e).__name__}); treating as text-only.") + return None + if not (getattr(processor, "image_processor", None) or getattr(processor, "video_processor", None)): + logger.debug(f"AutoProcessor for {config.name} has no image/video processor; treating as text-only.") + return None + logger.info(f"Loaded multimodal processor: {type(processor).__name__}") + return processor + + def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims): mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=DTYPE_MAP[config.reduce_dtype]) offload_policy: OffloadPolicy = CPUOffloadPolicy(pin_memory=True) if config.fsdp_cpu_offload else OffloadPolicy() @@ -891,7 +910,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral state_dict = model.state_dict() state_dict = strip_lora_from_state_dict(state_dict) if model.config.tie_word_embeddings: - del state_dict["lm_head.weight"] + state_dict.pop("lm_head.weight") dcp_load( state_dict, storage_reader=HuggingFaceStorageReader(path=snapshot_path.as_posix()), @@ -1099,6 +1118,21 @@ def apply_ep(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDims) ) +def configure_trainable_parameters(model: nn.Module, config: ModelConfig) -> nn.Module | None: + """Apply LoRA and identify any vision encoder that must remain frozen.""" + frozen_vision_encoder = None + if config.vlm is not None and config.vlm.freeze_vision_encoder: + frozen_vision_encoder = get_vision_encoder(model, override=config.vlm.vision_encoder_attr) + elif config.vlm is None: + frozen_vision_encoder = get_vision_encoder(model) + if frozen_vision_encoder is not None: + get_logger().info("Training a VLM checkpoint on text-only data; freezing the vision encoder") + + if config.lora is not None: + apply_lora_to_model(model, config.lora) + return frozen_vision_encoder + + def _move_buffers_to_cuda(model: nn.Module, config: ModelConfig) -> None: """FSDP CPU offloading only manages parameters, not buffers. Move buffers to CUDA.""" if not config.fsdp_cpu_offload: @@ -1197,9 +1231,7 @@ def setup_model( apply_quantization(model, config) - # Apply LoRA before FSDP setup - if config.lora is not None: - apply_lora_to_model(model, config.lora) + frozen_vision_encoder = configure_trainable_parameters(model, config) if config.freeze_moe_router: freeze_moe_router(model) @@ -1222,6 +1254,12 @@ def setup_model( if config.lora is not None: freeze_all_except_lora_and_specified(model, config.lora) + if frozen_vision_encoder is not None: + freeze_vision_encoder( + model, + override_attr=config.vlm.vision_encoder_attr if config.vlm is not None else None, + ) + # the right order is AC -> Compile -> FSDP if config.ac is not None: apply_ac(model, config.ac) @@ -1273,12 +1311,10 @@ def forward( # "image_grid_thw": ...} for Qwen3-VL; just {"pixel_values": ...} # for Gemma3). Passed straight through to ``model(**kwargs)`` so # the model's HF forward signature is the schema. ``mm_token_type_ids`` - # is split out because it's prime-rl-computed (from token ids), - # not a renderer/processor output. + # is split out because it comes from the renderer rather than the processor. mm_kwargs: dict[str, Tensor] | None = None, mm_token_type_ids: Int[Tensor, "batch seq"] | None = None, ) -> PrimeLmOutput: - # Build kwargs for model forward kwargs = { "input_ids": input_ids, "labels": labels, @@ -1292,10 +1328,6 @@ def forward( kwargs.update(mm_kwargs) if mm_token_type_ids is not None: kwargs["mm_token_type_ids"] = mm_token_type_ids - # ``position_ids`` for MRoPE families: Qwen3-VL's HF forward - # recomputes 3D positions from ``image_grid_thw`` and breaks if - # given the trainer's pre-computed 1D ``position_ids``. Detect - # via the mm_kwargs shape so we don't enumerate model_types. if "image_grid_thw" not in mm_kwargs: kwargs["position_ids"] = position_ids else: diff --git a/src/prime_rl/trainer/models/__init__.py b/src/prime_rl/trainer/models/__init__.py index 14b52331..3b062de1 100644 --- a/src/prime_rl/trainer/models/__init__.py +++ b/src/prime_rl/trainer/models/__init__.py @@ -75,6 +75,7 @@ def supports_custom_impl(model_config: PretrainedConfig) -> bool: # Used by get_model() to dispatch VLMs that have a custom text model implementation. # Points to the same unified class — the config drives text-only vs VLM behavior. _CUSTOM_VLM_MAPPING: dict[str, type] = { + "qwen3_5": Qwen3_5ForCausalLM, "qwen3_5_moe": Qwen3_5MoeForCausalLM, } diff --git a/src/prime_rl/trainer/models/layers/lm_head.py b/src/prime_rl/trainer/models/layers/lm_head.py index 6ea0f562..6bff021d 100644 --- a/src/prime_rl/trainer/models/layers/lm_head.py +++ b/src/prime_rl/trainer/models/layers/lm_head.py @@ -265,12 +265,10 @@ def _patch_model_forward(model: nn.Module) -> None: if position_ids is None and not is_multimodal: reference_tensor = input_ids if input_ids is not None else inputs_embeds position_ids = torch.arange(1, reference_tensor.shape[1] + 1, device=reference_tensor.device).unsqueeze(0) - outputs = self.model( - input_ids=input_ids, - position_ids=position_ids, - inputs_embeds=inputs_embeds, - **kwargs, - ) + model_kwargs = {"input_ids": input_ids, "position_ids": position_ids, **kwargs} + if inputs_embeds is not None: + model_kwargs["inputs_embeds"] = inputs_embeds + outputs = self.model(**model_kwargs) hidden_states = outputs.last_hidden_state # Slice hidden states for logits_to_keep diff --git a/src/prime_rl/trainer/models/qwen3_5/modeling_qwen3_5.py b/src/prime_rl/trainer/models/qwen3_5/modeling_qwen3_5.py index 36b0c26c..666b8f8a 100644 --- a/src/prime_rl/trainer/models/qwen3_5/modeling_qwen3_5.py +++ b/src/prime_rl/trainer/models/qwen3_5/modeling_qwen3_5.py @@ -4,6 +4,7 @@ from typing import Optional, Union import torch from torch import Tensor, nn from transformers.cache_utils import Cache +from transformers.configuration_utils import PretrainedConfig from transformers.generation import GenerationMixin from transformers.modeling_layers import GradientCheckpointingLayer from transformers.modeling_outputs import BaseModelOutputWithPast @@ -11,6 +12,7 @@ from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig from transformers.models.qwen3_5.modeling_qwen3_5 import ( Qwen3_5PreTrainedModel as HFQwen3_5PreTrainedModel, ) +from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5VisionModel from transformers.processing_utils import Unpack from transformers.utils import TransformersKwargs @@ -25,6 +27,7 @@ from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import ( Qwen3_5MoeRotaryEmbedding, normalize_qwen3_5_attn_implementation, ) +from prime_rl.trainer.models.qwen3_5_moe.mrope import build_qwen3_5_mrope_position_ids from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens @@ -185,6 +188,12 @@ class Qwen3_5Model(Qwen3_5PreTrainedModel): self.post_init() + def get_input_embeddings(self): + return self.embed_tokens + + def set_input_embeddings(self, value): + self.embed_tokens = value + def forward( self, input_ids: Optional[torch.LongTensor] = None, @@ -221,7 +230,102 @@ class Qwen3_5Model(Qwen3_5PreTrainedModel): return BaseModelOutputWithPast(last_hidden_state=hidden_states) +class Qwen3_5VLMModel(nn.Module): + """Composite VLM body: HF vision encoder + custom PrimeRL dense text model.""" + + def __init__(self, config: PretrainedConfig): + super().__init__() + self.config = config + self.visual = Qwen3_5VisionModel._from_config(config.vision_config) + self.language_model = Qwen3_5Model(config.text_config) + + def get_input_embeddings(self): + return self.language_model.get_input_embeddings() + + def set_input_embeddings(self, value): + self.language_model.set_input_embeddings(value) + + def _dummy_vision_inputs(self, device: torch.device) -> tuple[torch.Tensor, torch.Tensor]: + vcfg = self.config.vision_config + m = vcfg.spatial_merge_size + num_patches = m * m + patch_dim = vcfg.in_channels * vcfg.temporal_patch_size * vcfg.patch_size * vcfg.patch_size + pixel_values = torch.zeros(num_patches, patch_dim, device=device, dtype=self.visual.dtype) + grid_thw = torch.tensor([[1, m, m]], dtype=torch.long, device=device) + return pixel_values, grid_thw + + def prepare_inputs_embeds_and_position_ids( + self, + input_ids: torch.LongTensor, + position_ids: torch.LongTensor | None = None, + pixel_values: torch.Tensor | None = None, + image_grid_thw: torch.LongTensor | None = None, + mm_token_type_ids: torch.LongTensor | None = None, + *, + seq_lens: torch.LongTensor, + ) -> tuple[torch.FloatTensor, torch.LongTensor]: + inputs_embeds = self.language_model.embed_tokens(input_ids) + + has_images = pixel_values is not None + vision_grid_thw = image_grid_thw + if has_images: + pixel_values = pixel_values.type(self.visual.dtype) + else: + pixel_values, vision_grid_thw = self._dummy_vision_inputs(inputs_embeds.device) + + vision_output = self.visual(pixel_values, grid_thw=vision_grid_thw, return_dict=True) + image_embeds = vision_output.pooler_output.to(inputs_embeds.device, inputs_embeds.dtype) + + if has_images: + image_mask = input_ids == self.config.image_token_id + image_mask = image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device) + inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds) + else: + inputs_embeds = inputs_embeds + image_embeds.sum() * 0.0 + + if position_ids is None: + if image_grid_thw is not None: + position_ids = build_qwen3_5_mrope_position_ids( + input_ids=input_ids, + mm_token_type_ids=mm_token_type_ids, + image_grid_thw=image_grid_thw, + spatial_merge_size=self.config.vision_config.spatial_merge_size, + seq_lens=seq_lens, + ) + else: + position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0) + + return inputs_embeds, position_ids + + def forward( + self, + input_ids: torch.LongTensor, + position_ids: torch.LongTensor | None = None, + pixel_values: torch.Tensor | None = None, + image_grid_thw: torch.LongTensor | None = None, + mm_token_type_ids: torch.LongTensor | None = None, + *, + seq_lens: torch.LongTensor, + ) -> BaseModelOutputWithPast: + inputs_embeds, position_ids = self.prepare_inputs_embeds_and_position_ids( + input_ids=input_ids, + position_ids=position_ids, + pixel_values=pixel_values, + image_grid_thw=image_grid_thw, + mm_token_type_ids=mm_token_type_ids, + seq_lens=seq_lens, + ) + + return self.language_model( + inputs_embeds=inputs_embeds, + position_ids=position_ids, + seq_lens=seq_lens, + ) + + class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin): + """Unified dense Qwen3.5 model for both text-only and VLM configs.""" + _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} _checkpoint_conversion_mapping = {} _tp_plan = {"lm_head": "colwise_gather_output"} @@ -229,16 +333,25 @@ class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin): def __init__(self, config, **kwargs): super().__init__(config, **kwargs) - self.model = Qwen3_5Model(config) - self.vocab_size = config.vocab_size - self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + self._is_vlm = hasattr(config, "vision_config") + + if self._is_vlm: + self.model = Qwen3_5VLMModel(config) + text_config = config.text_config + self._tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"} + else: + self.model = Qwen3_5Model(config) + text_config = config + + self.vocab_size = text_config.vocab_size + self.lm_head = nn.Linear(text_config.hidden_size, text_config.vocab_size, bias=False) self.post_init() def get_input_embeddings(self): - return self.model.embed_tokens + return self.model.get_input_embeddings() def set_input_embeddings(self, value): - self.model.embed_tokens = value + self.model.set_input_embeddings(value) def set_decoder(self, decoder): self.model = decoder @@ -257,6 +370,9 @@ class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin): use_cache: Optional[bool] = None, logits_to_keep: Union[int, torch.Tensor] = 0, temperature: Union[torch.Tensor, None] = None, + pixel_values: Optional[torch.Tensor] = None, + image_grid_thw: Optional[torch.LongTensor] = None, + mm_token_type_ids: Optional[torch.LongTensor] = None, *, seq_lens: torch.LongTensor, **kwargs: Unpack[TransformersKwargs], @@ -264,18 +380,22 @@ class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin): assert use_cache is None, "use_cache is not supported for custom qwen3_5 for now" assert past_key_values is None, "past_key_values is not supported for custom qwen3_5 for now" - if position_ids is None: - if inputs_embeds is not None: - position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0) - elif input_ids is not None: - position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).unsqueeze(0) - - outputs = self.model( - input_ids=input_ids, - position_ids=position_ids, - inputs_embeds=inputs_embeds, - seq_lens=seq_lens, - ) + if self._is_vlm: + outputs = self.model( + input_ids=input_ids, + position_ids=position_ids, + pixel_values=pixel_values, + image_grid_thw=image_grid_thw, + mm_token_type_ids=mm_token_type_ids, + seq_lens=seq_lens, + ) + else: + outputs = self.model( + input_ids=input_ids, + position_ids=position_ids, + inputs_embeds=inputs_embeds, + seq_lens=seq_lens, + ) hidden_states = outputs.last_hidden_state slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep @@ -286,11 +406,25 @@ class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin): ) def init_buffers_post_meta(self): - lm_rope = self.model.rotary_emb + if self._is_vlm: + lm_rope = self.model.language_model.rotary_emb + else: + lm_rope = self.model.rotary_emb + if hasattr(lm_rope, "rope_init_fn"): inv_freq, lm_rope.attention_scaling = lm_rope.rope_init_fn(lm_rope.config, lm_rope.inv_freq.device) lm_rope.inv_freq.copy_(inv_freq) + if self._is_vlm: + vis_rope = self.model.visual.rotary_pos_emb + if hasattr(vis_rope, "inv_freq"): + dim = vis_rope.inv_freq.shape[0] + inv_freq = 1.0 / ( + 10000.0 + ** (torch.arange(0, dim * 2, 2, dtype=torch.float32, device=vis_rope.inv_freq.device) / (dim * 2)) + ) + vis_rope.inv_freq.copy_(inv_freq) + __all__ = [ "Qwen3_5ForCausalLM", diff --git a/src/prime_rl/trainer/models/qwen3_5_moe/modeling_qwen3_5_moe.py b/src/prime_rl/trainer/models/qwen3_5_moe/modeling_qwen3_5_moe.py index 381cb5f1..f47163d6 100644 --- a/src/prime_rl/trainer/models/qwen3_5_moe/modeling_qwen3_5_moe.py +++ b/src/prime_rl/trainer/models/qwen3_5_moe/modeling_qwen3_5_moe.py @@ -656,6 +656,12 @@ class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel): self.post_init() + def get_input_embeddings(self): + return self.embed_tokens + + def set_input_embeddings(self, value): + self.embed_tokens = value + def forward( self, input_ids: Optional[torch.LongTensor] = None, @@ -674,8 +680,6 @@ class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel): if position_ids is None: position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0) - if position_ids.ndim == 3 and inputs_embeds.shape[0] != 1: - raise ValueError("3D Qwen3.5 MRoPE positions require batch size 1 for varlen attention") cu_seqlens, max_seqlen = get_cu_seqlens_from_seq_lens( seq_lens.to(device=inputs_embeds.device), total_tokens=inputs_embeds.shape[1] ) @@ -726,10 +730,10 @@ class Qwen3_5MoeVLMModel(nn.Module): self.language_model = Qwen3_5MoeModel(_build_text_config(config)) def get_input_embeddings(self): - return self.language_model.embed_tokens + return self.language_model.get_input_embeddings() def set_input_embeddings(self, value): - self.language_model.embed_tokens = value + self.language_model.set_input_embeddings(value) def _dummy_vision_inputs(self, device: torch.device) -> tuple[torch.Tensor, torch.Tensor]: """Smallest valid vision input: a single merged token (grid [1, m, m]).""" @@ -741,42 +745,26 @@ class Qwen3_5MoeVLMModel(nn.Module): grid_thw = torch.tensor([[1, m, m]], dtype=torch.long, device=device) return pixel_values, grid_thw - def forward( + def prepare_inputs_embeds_and_position_ids( self, - input_ids: torch.LongTensor | None = None, + input_ids: torch.LongTensor, position_ids: torch.LongTensor | None = None, - inputs_embeds: torch.FloatTensor | None = None, pixel_values: torch.Tensor | None = None, image_grid_thw: torch.LongTensor | None = None, mm_token_type_ids: torch.LongTensor | None = None, - routed_experts: torch.LongTensor | None = None, *, seq_lens: torch.LongTensor, - **kwargs, - ) -> MoeModelOutputWithPast: - if inputs_embeds is None: - inputs_embeds = self.language_model.embed_tokens(input_ids) + ) -> tuple[torch.FloatTensor, torch.LongTensor]: + inputs_embeds = self.language_model.embed_tokens(input_ids) - if image_grid_thw is not None and input_ids is None: - raise ValueError("input_ids are required to compute Qwen3.5 multimodal MRoPE positions") - if image_grid_thw is not None and mm_token_type_ids is None: - raise ValueError( - "Qwen3.5 multimodal forward requires mm_token_type_ids to compute MRoPE positions correctly" - ) - if image_grid_thw is not None and position_ids is not None and position_ids.ndim != 3: - raise ValueError( - f"Qwen3.5 multimodal forward requires 3D MRoPE position_ids; got shape={tuple(position_ids.shape)}" - ) - - # Keep distributed collectives in the same order when a batch mixes text-only - # and image samples across ranks. The frozen dummy pass is discarded below. + # Always run the vision encoder for collective symmetry: under FSDP + EP + # all ranks share one process group, so every rank must issue the vision + # encoder's collectives in the same order each step. Text-only microbatches + # keep the dummy embeds in the graph with zero contribution so trainable + # vision modules also participate in backward collectives. has_images = pixel_values is not None vision_grid_thw = image_grid_thw if has_images: - if input_ids is None: - raise ValueError("input_ids are required when scattering Qwen3.5 image features") - if image_grid_thw is None: - raise ValueError("image_grid_thw is required when pixel_values are provided") pixel_values = pixel_values.type(self.visual.dtype) else: pixel_values, vision_grid_thw = self._dummy_vision_inputs(inputs_embeds.device) @@ -786,19 +774,10 @@ class Qwen3_5MoeVLMModel(nn.Module): if has_images: image_mask = input_ids == self.config.image_token_id - image_token_count = int(image_mask.sum().item()) - image_feature_count = int(image_embeds.shape[0]) - if image_token_count != image_feature_count: - raise ValueError( - "Qwen VLM image token/feature mismatch before scatter: " - f"image_token_id={self.config.image_token_id}, " - f"image_tokens={image_token_count}, image_features={image_feature_count}, " - f"input_ids_shape={tuple(input_ids.shape)}, " - f"pixel_values_shape={tuple(pixel_values.shape)}, " - f"image_grid_thw_shape={tuple(image_grid_thw.shape) if image_grid_thw is not None else None}" - ) image_mask = image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device) inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds) + else: + inputs_embeds = inputs_embeds + image_embeds.sum() * 0.0 if position_ids is None: if image_grid_thw is not None: @@ -812,6 +791,28 @@ class Qwen3_5MoeVLMModel(nn.Module): else: position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0) + return inputs_embeds, position_ids + + def forward( + self, + input_ids: torch.LongTensor, + position_ids: torch.LongTensor | None = None, + pixel_values: torch.Tensor | None = None, + image_grid_thw: torch.LongTensor | None = None, + mm_token_type_ids: torch.LongTensor | None = None, + routed_experts: torch.LongTensor | None = None, + *, + seq_lens: torch.LongTensor, + ) -> MoeModelOutputWithPast: + inputs_embeds, position_ids = self.prepare_inputs_embeds_and_position_ids( + input_ids=input_ids, + position_ids=position_ids, + pixel_values=pixel_values, + image_grid_thw=image_grid_thw, + mm_token_type_ids=mm_token_type_ids, + seq_lens=seq_lens, + ) + return self.language_model( inputs_embeds=inputs_embeds, position_ids=position_ids, @@ -872,15 +873,10 @@ class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin): self.post_init() def get_input_embeddings(self): - if self._is_vlm: - return self.model.get_input_embeddings() - return self.model.embed_tokens + return self.model.get_input_embeddings() def set_input_embeddings(self, value): - if self._is_vlm: - self.model.set_input_embeddings(value) - else: - self.model.embed_tokens = value + self.model.set_input_embeddings(value) def set_decoder(self, decoder): self.model = decoder @@ -971,18 +967,10 @@ class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin): assert use_cache is None, "use_cache is not supported for custom qwen3_5_moe for now" assert past_key_values is None, "past_key_values is not supported for custom qwen3_5_moe for now" - has_vlm_image_inputs = self._is_vlm and image_grid_thw is not None - if position_ids is None and not has_vlm_image_inputs: - if inputs_embeds is not None: - position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0) - elif input_ids is not None: - position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).unsqueeze(0) - if self._is_vlm: outputs: MoeModelOutputWithPast = self.model( input_ids=input_ids, position_ids=position_ids, - inputs_embeds=inputs_embeds, pixel_values=pixel_values, image_grid_thw=image_grid_thw, mm_token_type_ids=mm_token_type_ids, diff --git a/src/prime_rl/trainer/sft/data.py b/src/prime_rl/trainer/sft/data.py index 392603dc..7aa27b5f 100644 --- a/src/prime_rl/trainer/sft/data.py +++ b/src/prime_rl/trainer/sft/data.py @@ -3,10 +3,11 @@ import uuid from collections import defaultdict from typing import Any, Literal, TypedDict, cast +import numpy as np import torch from datasets import Dataset, interleave_datasets, load_dataset from jaxtyping import Bool, Int -from renderers.base import Renderer, build_training_sample +from renderers.base import MultiModalData, PlaceholderRange, Renderer, build_training_sample from torch import Tensor from torch.distributed.checkpoint.stateful import Stateful from torch.utils.data import IterableDataset, get_worker_info @@ -25,6 +26,8 @@ class Sample(TypedDict): loss_mask: list[bool] target_ids: list[int] seq_lens: list[int] + mm_kwargs: dict[str, Tensor] | None + mm_token_type_ids: list[int] | None class Batch(TypedDict): @@ -33,6 +36,8 @@ class Batch(TypedDict): target_ids: Int[Tensor, "batch seq"] loss_mask: Bool[Tensor, "batch seq"] seq_lens: Int[Tensor, "packed"] + mm_kwargs: dict[str, Tensor] | None + mm_token_type_ids: Int[Tensor, "batch seq"] | None class StatefulIterableDataset(Stateful, IterableDataset): @@ -103,12 +108,27 @@ class FakeDataset(StatefulIterableDataset): "position_ids": position_ids, "loss_mask": loss_mask, "seq_lens": [seq_len], + "mm_kwargs": None, + "mm_token_type_ids": None, } self.num_samples["fake"] += 1 self.num_tokens["fake"] += len(input_ids) yield fake_sample +def _flatten_mm_items(mm_items: dict[str, list[dict[str, Any]]]) -> dict[str, Tensor]: + """Fold per-item renderer outputs into model-forward tensors.""" + out: dict[str, Tensor] = {} + for items in mm_items.values(): + for item in items: + for key, value in item.items(): + if not isinstance(value, (np.ndarray, Tensor)): + continue + tensor = torch.as_tensor(value) + out[key] = torch.cat([out[key], tensor], dim=0) if key in out else tensor + return out + + def _drop_null_fields(value: Any, path: tuple[str, ...] = ()) -> Any: """Recursively strip ``None``-valued keys from dict structures. @@ -129,6 +149,34 @@ def _drop_null_fields(value: Any, path: tuple[str, ...] = ()) -> Any: return value +def _find_image_safe_cut(budget: int, mm: MultiModalData | None) -> int: + """Return the largest cut at most ``budget`` outside placeholder runs.""" + if mm is None or not mm.mm_placeholders: + return budget + cut = budget + for ranges in mm.mm_placeholders.values(): + for placeholder in ranges: + if placeholder.offset < cut < placeholder.offset + placeholder.length: + cut = placeholder.offset + return cut + + +def _truncate_mm_data(mm: MultiModalData, cut: int) -> MultiModalData: + """Drop multimodal items whose placeholder ranges extend past ``cut``.""" + new_placeholders: dict[str, list[PlaceholderRange]] = {} + new_items: dict[str, list[dict[str, Any]]] = {} + new_hashes: dict[str, list[str]] = {} + for content_type, ranges in mm.mm_placeholders.items(): + keep = [index for index, placeholder in enumerate(ranges) if placeholder.offset + placeholder.length <= cut] + if not keep: + continue + new_placeholders[content_type] = [ranges[index] for index in keep] + new_items[content_type] = [mm.mm_items[content_type][index] for index in keep] + if content_type in mm.mm_hashes: + new_hashes[content_type] = [mm.mm_hashes[content_type][index] for index in keep] + return MultiModalData(mm_hashes=new_hashes, mm_placeholders=new_placeholders, mm_items=new_items) + + class SFTDataset(StatefulIterableDataset): """A dataset wrapping a HF SFT dataset with prompt/completion or raw messages format.""" @@ -143,6 +191,7 @@ class SFTDataset(StatefulIterableDataset): loss_mask_config: LossMaskConfig = LossMaskConfig(), max_examples: int | None = None, max_epochs: int | None = None, + multimodal: bool = False, ): super().__init__() self.logger = get_logger() @@ -155,6 +204,7 @@ class SFTDataset(StatefulIterableDataset): self.loss_mask_config = loss_mask_config self.max_examples = max_examples self.max_epochs = max_epochs + self.multimodal = multimodal # If specified, select a subset of the dataset if self.max_examples is not None: @@ -254,11 +304,39 @@ class SFTDataset(StatefulIterableDataset): ) input_ids = list(sample.token_ids) loss_mask = list(sample.loss_mask) + mm = sample.multi_modal_data + mm_token_type_ids = list(sample.mm_token_type_ids) if sample.mm_token_type_ids is not None else None + if mm is not None and mm.mm_items and not self.multimodal: + raise ValueError( + "Renderer produced multimodal data but [model.vlm] is not set. " + "Set [model.vlm] to train on multimodal samples." + ) # Causal shift: model predicts next token from current. - target_ids = input_ids.copy()[1:] + target_ids = input_ids[1:] loss_mask = loss_mask[1:] input_ids = input_ids[:-1] + if mm_token_type_ids is not None: + mm_token_type_ids = mm_token_type_ids[:-1] + + was_mm_truncated = False + if mm is not None and len(input_ids) > self.seq_len: + was_mm_truncated = True + cut = _find_image_safe_cut(self.seq_len, mm) + self.logger.debug( + f"Truncating example {example.get('__index', '')} from " + f"{len(input_ids)} → {cut} tokens (budget={self.seq_len})" + ) + input_ids = input_ids[:cut] + target_ids = target_ids[:cut] + loss_mask = loss_mask[:cut] + if mm_token_type_ids is not None: + mm_token_type_ids = mm_token_type_ids[:cut] + if mm.mm_items: + mm = _truncate_mm_data(mm, cut) + + if was_mm_truncated and not set(self.renderer.get_stop_token_ids()) & set(target_ids): + return None if sum(loss_mask[: self.seq_len]) == 0: self.logger.warning( @@ -274,12 +352,22 @@ class SFTDataset(StatefulIterableDataset): "A renderer stop token must be present in target_ids" ) + mm_kwargs: dict[str, Tensor] | None = None + if mm is not None and mm.mm_items: + mm_kwargs = _flatten_mm_items(mm.mm_items) + if any("video" in key for key in mm_kwargs): + raise ValueError("Video SFT is not supported; sample contains video inputs") + if mm_token_type_ids is not None: + assert len(mm_token_type_ids) == len(input_ids) + return { "input_ids": input_ids, "target_ids": target_ids, "loss_mask": loss_mask, "position_ids": list(range(len(input_ids))), "seq_lens": [len(input_ids)], + "mm_kwargs": mm_kwargs, + "mm_token_type_ids": mm_token_type_ids, } def __iter__(self): @@ -327,7 +415,7 @@ class SFTDataset(StatefulIterableDataset): class CatDataset(StatefulIterableDataset): - """A dataset that concatenates samples into a single sequence with a fixed length.""" + """Concatenate text and multimodal samples into one fixed-length row.""" def __init__(self, dataset: StatefulIterableDataset, seq_len: int): self.logger = get_logger() @@ -347,6 +435,8 @@ class CatDataset(StatefulIterableDataset): def __iter__(self): packed_samples = defaultdict(list) + packed_samples["mm_kwargs"] = None + packed_samples["mm_token_type_ids"] = None seq_len = 0 pending_sample = self.pending_sample @@ -365,18 +455,48 @@ class CatDataset(StatefulIterableDataset): yield self._finalize_pack(packed_samples, self.seq_len) self.pending_sample = None packed_samples = defaultdict(list) + packed_samples["mm_kwargs"] = None + packed_samples["mm_token_type_ids"] = None seq_len = 0 + existing_len = len(packed_samples["input_ids"]) for key in ("input_ids", "position_ids", "loss_mask", "target_ids"): value = sample[key] assert isinstance(value, list) packed_samples[key].extend(value) packed_samples["seq_lens"].append(sample_len) + + sample_mm_kwargs = sample.get("mm_kwargs") + sample_mm_type_ids = sample.get("mm_token_type_ids") + if sample_mm_kwargs is None: + if packed_samples["mm_token_type_ids"] is not None: + packed_samples["mm_token_type_ids"].extend([0] * sample_len) + else: + if packed_samples["mm_kwargs"] is not None and ( + (packed_samples["mm_token_type_ids"] is None) != (sample_mm_type_ids is None) + ): + raise ValueError("Cannot pack multimodal samples with mixed mm_token_type_ids") + + if packed_samples["mm_kwargs"] is None: + packed_samples["mm_kwargs"] = dict(sample_mm_kwargs) + else: + if packed_samples["mm_kwargs"].keys() != sample_mm_kwargs.keys(): + raise ValueError("Cannot pack multimodal samples with different mm_kwargs keys") + for key, value in sample_mm_kwargs.items(): + packed_samples["mm_kwargs"][key] = torch.cat([packed_samples["mm_kwargs"][key], value], dim=0) + + if packed_samples["mm_token_type_ids"] is None and sample_mm_type_ids is not None: + packed_samples["mm_token_type_ids"] = [0] * existing_len + if packed_samples["mm_token_type_ids"] is not None: + packed_samples["mm_token_type_ids"].extend(sample_mm_type_ids or [0] * sample_len) + seq_len += sample_len if seq_len >= self.seq_len: yield self._finalize_pack(packed_samples, self.seq_len) packed_samples = defaultdict(list) + packed_samples["mm_kwargs"] = None + packed_samples["mm_token_type_ids"] = None seq_len = 0 if seq_len > 0: @@ -402,17 +522,30 @@ class CatDataset(StatefulIterableDataset): result["loss_mask"].extend([False] * pad_len) result["target_ids"].extend([0] * pad_len) result["seq_lens"][-1] += pad_len + result["mm_kwargs"] = packed["mm_kwargs"] + if packed["mm_token_type_ids"] is not None: + result["mm_token_type_ids"] = packed["mm_token_type_ids"][:seq_len] + [0] * pad_len + else: + result["mm_token_type_ids"] = None return result def cat_collate(samples: list[Sample]) -> Batch: (sample,) = samples + mm_kwargs = sample.get("mm_kwargs") + mm_token_type_ids = sample.get("mm_token_type_ids") return { "input_ids": torch.tensor(sample["input_ids"], dtype=torch.long, device="cuda").unsqueeze(0), "position_ids": torch.tensor(sample["position_ids"], dtype=torch.long, device="cuda").unsqueeze(0), "loss_mask": torch.tensor(sample["loss_mask"], dtype=torch.bool, device="cuda").unsqueeze(0), "target_ids": torch.tensor(sample["target_ids"], dtype=torch.long, device="cuda").unsqueeze(0), "seq_lens": torch.tensor(sample["seq_lens"], dtype=torch.long, device="cuda"), + "mm_kwargs": {key: value.to("cuda") for key, value in mm_kwargs.items()} if mm_kwargs is not None else None, + "mm_token_type_ids": ( + torch.tensor(mm_token_type_ids, dtype=torch.long, device="cuda").unsqueeze(0) + if mm_token_type_ids is not None + else None + ), } @@ -492,6 +625,7 @@ def setup_dataset( max_epochs: int | None = None, raw_dataset: Dataset | None = None, renderer: Renderer | None = None, + multimodal: bool = False, ) -> StatefulIterableDataset: if config.type == "fake": return FakeDataset( @@ -514,6 +648,7 @@ def setup_dataset( loss_mask_config=config.loss_mask, non_dp_size=non_dp_size, max_epochs=max_epochs, + multimodal=multimodal, ) else: raise ValueError(f"Invalid dataset type: {config.type}") diff --git a/src/prime_rl/trainer/sft/train.py b/src/prime_rl/trainer/sft/train.py index 499c75d6..ef9dc75b 100644 --- a/src/prime_rl/trainer/sft/train.py +++ b/src/prime_rl/trainer/sft/train.py @@ -28,6 +28,7 @@ from prime_rl.trainer.model import ( forward, get_load_balance_stats, is_tt_moe_model, + setup_processor, setup_tokenizer, resolve_auto_attn, setup_model, @@ -162,6 +163,9 @@ def train(config: SFTConfig): logger.info(f"Initializing tokenizer ({config.tokenizer})") tokenizer = setup_tokenizer(config.tokenizer) + processor = setup_processor(config.model) + if config.model.vlm is not None and processor is None: + raise ValueError(f"[model.vlm] is set but no multimodal processor could be loaded for {config.model.name!r}") # Fake data never renders messages, so a model without a hand-coded renderer # can still be used to benchmark step time / memory. Validation data is @@ -169,6 +173,8 @@ def train(config: SFTConfig): renderer = None if config.data.type != "fake" or config.val is not None: renderer = create_renderer(tokenizer, config.renderer) + if processor is not None and hasattr(renderer, "_processor"): + renderer._processor = processor logger.info(f"Initialized {type(renderer).__name__} for {config.tokenizer.name}") # Set up the optimizer @@ -189,7 +195,8 @@ def train(config: SFTConfig): # Set up the dataset and dataloader logger.info(f"Initializing data ({config.data})") - dataset = setup_dataset(tokenizer, config.data, config.model.cp, renderer=renderer) + multimodal = config.model.vlm is not None + dataset = setup_dataset(tokenizer, config.data, config.model.cp, renderer=renderer, multimodal=multimodal) dataloader = setup_dataloader(dataset, config.data) dataiter = iter(dataloader) @@ -234,6 +241,8 @@ def train(config: SFTConfig): target_ids = micro_batch["target_ids"].to("cuda") loss_mask = micro_batch["loss_mask"].to("cuda") seq_lens = micro_batch["seq_lens"].to("cuda") + mm_kwargs = micro_batch.get("mm_kwargs") + mm_type_ids = micro_batch.get("mm_token_type_ids") if cp_enabled: total_tokens = input_ids.shape[1] @@ -268,10 +277,19 @@ def train(config: SFTConfig): seq_lens=seq_lens, labels=target_ids, temperature=temperature, + mm_kwargs=mm_kwargs, + mm_token_type_ids=mm_type_ids, ) loss_sum = -out["logprobs"][loss_mask].sum() else: - out = forward(model, input_ids, position_ids, seq_lens=seq_lens) + out = forward( + model, + input_ids, + position_ids, + mm_kwargs=mm_kwargs, + mm_token_type_ids=mm_type_ids, + seq_lens=seq_lens, + ) logits = out["logits"] B, L, V = logits.shape token_loss = CrossEntropyLoss(reduction="none")(logits.view(-1, V), target_ids.view(-1)).view(B, L) @@ -324,6 +342,7 @@ def train(config: SFTConfig): max_epochs=1, raw_dataset=val_raw_dataset, renderer=renderer, + multimodal=multimodal, ) val_dataloader = setup_dataloader(val_dataset, config.val.data) @@ -480,7 +499,7 @@ def train(config: SFTConfig): if weight_ckpt_manager is not None: logger.info(f"Saving weight checkpoint at step {progress.step}") save_ckpt_start_time = time.perf_counter() - weight_ckpt_manager.save(progress.step, model, tokenizer) + weight_ckpt_manager.save(progress.step, model, tokenizer, processor) save_ckpt_time += time.perf_counter() - save_ckpt_start_time weight_ckpt_manager.maybe_clean() else: @@ -616,7 +635,7 @@ def train(config: SFTConfig): # Write final weight checkpoint if weight_ckpt_manager is not None: logger.info("Writing final weight checkpoint") - weight_ckpt_manager.save(progress.step, model, tokenizer) + weight_ckpt_manager.save(progress.step, model, tokenizer, processor) weight_ckpt_manager.maybe_clean() logger.info(f"Peak memory: {max(to_col_format(monitor.history)['perf/peak_memory']):.1f} GiB") diff --git a/tests/unit/train/models/test_qwen3_5_moe_vlm.py b/tests/unit/train/models/test_qwen3_5_moe_vlm.py index bc8fde66..a0c87a68 100644 --- a/tests/unit/train/models/test_qwen3_5_moe_vlm.py +++ b/tests/unit/train/models/test_qwen3_5_moe_vlm.py @@ -197,48 +197,6 @@ def test_vlm_weight_roundtrip(): assert torch.equal(roundtripped[original_vision_key], original_vision_weight) -def test_vlm_forward_requires_mm_token_type_ids(): - """Image MRoPE needs renderer-supplied modality token types.""" - config = _tiny_vlm_config() - with torch.device("cuda"), default_dtype(torch.bfloat16): - model = Qwen3_5MoeForCausalLM(config) - inject_prime_lm_head(model) - - pixel_values, image_grid_thw, n_img_tokens = _make_image_inputs(config) - input_ids = torch.full((1, n_img_tokens), config.image_token_id, device="cuda") - - with pytest.raises(ValueError, match="mm_token_type_ids"): - model( - input_ids=input_ids, - pixel_values=pixel_values, - image_grid_thw=image_grid_thw, - seq_lens=_seq_lens(input_ids), - ) - - -def test_vlm_forward_rejects_2d_positions_with_images(): - """Trainer 1D/2D packed positions are not valid image MRoPE coordinates.""" - config = _tiny_vlm_config() - with torch.device("cuda"), default_dtype(torch.bfloat16): - model = Qwen3_5MoeForCausalLM(config) - inject_prime_lm_head(model) - - pixel_values, image_grid_thw, n_img_tokens = _make_image_inputs(config) - input_ids = torch.full((1, n_img_tokens), config.image_token_id, device="cuda") - mm_token_type_ids = _make_mm_token_type_ids(input_ids, config.image_token_id) - position_ids = torch.arange(n_img_tokens, device="cuda").unsqueeze(0) - - with pytest.raises(ValueError, match="3D MRoPE position_ids"): - model( - input_ids=input_ids, - position_ids=position_ids, - pixel_values=pixel_values, - image_grid_thw=image_grid_thw, - mm_token_type_ids=mm_token_type_ids, - seq_lens=_seq_lens(input_ids), - ) - - def test_vlm_router_replay(): """routed_experts bypasses router computation in VLM multimodal forward.""" config = _tiny_vlm_config() diff --git a/tests/unit/train/sft/test_sft_dataset.py b/tests/unit/train/sft/test_sft_dataset.py index fc72cb53..ac09a33e 100644 --- a/tests/unit/train/sft/test_sft_dataset.py +++ b/tests/unit/train/sft/test_sft_dataset.py @@ -1,12 +1,14 @@ from collections import Counter import pytest +import torch from datasets import Dataset, interleave_datasets from renderers import create_renderer -from renderers.base import RenderedTokens +from renderers.base import MultiModalData, PlaceholderRange, RenderedTokens, RenderedTrainingSample from transformers import AutoTokenizer -from prime_rl.trainer.sft.data import SFTDataset, _drop_null_fields +import prime_rl.trainer.sft.data as sft_data +from prime_rl.trainer.sft.data import CatDataset, SFTDataset, _drop_null_fields from prime_rl.trainer.utils import print_sample _BOS_TOKEN_ID = 0 @@ -399,3 +401,106 @@ def test_null_messages_falls_back_to_prompt_and_completion(): ) assert next(iter(mixed_row_dataset)) == next(iter(expected_dataset)) + + +def test_vlm_truncation_does_not_append_trainable_eos(monkeypatch): + mm = MultiModalData( + mm_placeholders={"image": [PlaceholderRange(offset=1, length=1)]}, + mm_items={"image": [{"pixel_values": torch.ones(1, 1), "image_grid_thw": torch.tensor([[1, 1, 1]])}]}, + ) + + def fake_build_training_sample(*args, **kwargs): + return RenderedTrainingSample( + token_ids=[10, 11, 12, _STOP_TOKEN_ID], + loss_mask=[False, False, False, True], + multi_modal_data=mm, + mm_token_type_ids=[0, 1, 0, 0], + ) + + monkeypatch.setattr(sft_data, "build_training_sample", fake_build_training_sample) + dataset = SFTDataset(Dataset.from_list([]), _DummyRenderer(), seq_len=2, multimodal=True) + + assert dataset._process({"messages": [{"role": "assistant", "content": "ignored"}]}) is None + + +def _sft_sample( + input_ids: list[int], + *, + mm_kwargs: dict[str, torch.Tensor] | None = None, + mm_token_type_ids: list[int] | None = None, +) -> dict: + return { + "input_ids": input_ids, + "position_ids": list(range(len(input_ids))), + "loss_mask": [True] * len(input_ids), + "target_ids": [x + 1 for x in input_ids], + "seq_lens": [len(input_ids)], + "mm_kwargs": mm_kwargs, + "mm_token_type_ids": mm_token_type_ids, + } + + +def test_cat_dataset_packs_multimodal_samples(): + dataset = CatDataset( + [ + _sft_sample( + [1, 2], + mm_kwargs={ + "pixel_values": torch.ones(2, 3), + "image_grid_thw": torch.tensor([[1, 1, 2]]), + }, + mm_token_type_ids=[0, 1], + ), + _sft_sample( + [3, 4, 5], + mm_kwargs={ + "pixel_values": 2 * torch.ones(3, 3), + "image_grid_thw": torch.tensor([[1, 1, 3]]), + }, + mm_token_type_ids=[0, 1, 1], + ), + ], + seq_len=5, + ) + + packed = next(iter(dataset)) + + assert packed["input_ids"] == [1, 2, 3, 4, 5] + assert packed["seq_lens"] == [2, 3] + assert packed["mm_token_type_ids"] == [0, 1, 0, 1, 1] + assert packed["mm_kwargs"]["pixel_values"].shape == (5, 3) + assert packed["mm_kwargs"]["image_grid_thw"].tolist() == [[1, 1, 2], [1, 1, 3]] + + +def test_cat_dataset_packs_text_and_multimodal_samples_together(): + dataset = CatDataset( + [ + _sft_sample([1]), + _sft_sample( + [2, 3], + mm_kwargs={ + "pixel_values": torch.ones(2, 3), + "image_grid_thw": torch.tensor([[1, 1, 2]]), + }, + mm_token_type_ids=[0, 1], + ), + _sft_sample([4]), + _sft_sample([5, 6]), + ], + seq_len=5, + ) + + dataiter = iter(dataset) + packed = next(dataiter) + text_pack = next(dataiter) + + assert packed["input_ids"] == [1, 2, 3, 4, 0] + assert packed["loss_mask"] == [True, True, True, True, False] + assert packed["seq_lens"] == [1, 2, 2] + assert packed["mm_kwargs"] is not None + assert packed["mm_token_type_ids"] == [0, 0, 1, 0, 0] + assert text_pack["input_ids"] == [5, 6, 0, 0, 0] + assert text_pack["loss_mask"] == [True, True, False, False, False] + assert text_pack["seq_lens"] == [5] + assert text_pack["mm_kwargs"] is None + assert text_pack["mm_token_type_ids"] is None