feat(rl): pack multimodal samples with context parallelism (#3103)
* feat(rl): pack multimodal samples Multimodal RL samples no longer force one-sample micro-batches: eager image samples pack with text spans and compatible mm_kwargs samples from the same run/LoRA, with per-sample boundaries kept in seq_lens. Packing is always on — VLM training is custom-implementation-only and the custom Qwen3.5 models advertise supports_packed_multimodal_training; a config validator requires varlen flash attention for VLM training and validate_multi_modal_pack fails loudly at startup for models without packed-MM support. Ported from #2889 minus its gating (pack_multimodal knob, resolve_pack_multimodal) and its tokenizer packer params (removed on main since). (cherry picked from commit 027edc2c510c35ab5666e8f9cbf160f58b1fba48) * fix: fail loudly when RL micro batches carry multimodal data without [model.vlm] Mirrors the SFT-side check: transported mm samples would otherwise flow into forward unvalidated (no packability, attn, or freeze policy checks). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(rl): preserve multimodal packing across workers Keep multimodal bins intact during worker balancing and reject malformed multimodal samples before they can stop shared multi-run packing.
This commit is contained in:
@@ -14,6 +14,7 @@ This page covers workflows for developing on `prime-rl` itself — running the t
|
|||||||
- [Implement the Modeling Code](#implement-the-modeling-code)
|
- [Implement the Modeling Code](#implement-the-modeling-code)
|
||||||
- [Register a Mini Preset](#register-a-mini-preset)
|
- [Register a Mini Preset](#register-a-mini-preset)
|
||||||
- [Run the Smoke Test](#run-the-smoke-test)
|
- [Run the Smoke Test](#run-the-smoke-test)
|
||||||
|
- [Adding a Custom VLM Implementation](#adding-a-custom-vlm-implementation)
|
||||||
|
|
||||||
## Test Suite
|
## Test Suite
|
||||||
|
|
||||||
@@ -137,3 +138,15 @@ Before merging a new model, you need to ensure the following:
|
|||||||
- The small smoke test passes.
|
- The small smoke test passes.
|
||||||
|
|
||||||
In the PR that adds the new model, you also need to provide a table covering the KL mismatch across 20 steps on `math` environment with `batch_size=64`. All the entries in the table must lower than 0.015. If this is not met, the PR will not be merged (unless reasonable justification is provided). This is to ensure all our models are consistent and their implementations match the implementations in the inference framework.
|
In the PR that adds the new model, you also need to provide a table covering the KL mismatch across 20 steps on `math` environment with `batch_size=64`. All the entries in the table must lower than 0.015. If this is not met, the PR will not be merged (unless reasonable justification is provided). This is to ensure all our models are consistent and their implementations match the implementations in the inference framework.
|
||||||
|
|
||||||
|
## Adding a Custom VLM Implementation
|
||||||
|
|
||||||
|
VLM training (any run with `[model.vlm]` set, SFT or RL) is custom-implementation-only: `get_model` rejects models without a custom PrimeRL VLM class at load time. To make a new VLM family trainable, extend a custom text model with a composite VLM body — the Qwen3.5 dense (`models/qwen3_5/`) and MoE (`models/qwen3_5_moe/`) implementations are the reference. The pieces, in dependency order:
|
||||||
|
|
||||||
|
1. **Custom text model first.** The VLM body wraps a custom `*ForCausalLM` (see [Adding a New Model](#adding-a-new-model)), so the text side — including its state-dict conversion and KL-mismatch table — comes first.
|
||||||
|
2. **Composite VLM body.** A `*VLMModel` that holds the HF vision encoder and the custom text model, with a `prepare_inputs_embeds_and_position_ids` step: embed tokens, run the vision encoder, scatter image embeddings over placeholder tokens, and build MRoPE 3D positions from `mm_token_type_ids` (the renderer owns the token→modality mapping). The unified `*ForCausalLM` dispatches on the config: composite config → VLM path, text config → text path.
|
||||||
|
3. **Always run the vision encoder.** Text-only micro-batches must feed the encoder dummy pixels and graft the result into the graph with zero contribution (`inputs_embeds + image_embeds.sum() * 0.0`) so FSDP/EP collectives stay symmetric across ranks when the encoder is trainable.
|
||||||
|
4. **Packed-boundary consumption.** Samples pack into shared rows with per-document boundaries in `seq_lens`; every custom model's `forward()` declares the typed `seq_lens`/`seq_lens_are_pre_shard` parameters (the trainer passes them unconditionally) and must honor the boundaries — varlen flash `cu_seqlens`, linear-attention state resets per document, and a loud rejection on attention paths that can't (see the packed-batch guard in any modeling file). Set `supports_packed_multimodal_training` on the VLM model once packed rows are handled — RL fails loudly at startup for VLM models without it.
|
||||||
|
5. **Registration.** Register the composite `model_type` in `_CUSTOM_VLM_MAPPING` (`models/__init__.py`) so `get_model` dispatches to the custom class, and describe the family in `VLM_REGISTRY` (`utils/vlm.py`).
|
||||||
|
6. **Context parallelism (optional).** CP-capable VLMs implement `set_context_parallel_attributes` and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for MRoPE batches under ulysses.
|
||||||
|
7. **Validation.** Same bar as text models: the KL-mismatch table for the text path, plus an SFT run and an RL run on a real multimodal dataset (the `color-codeword` environment is the reference task).
|
||||||
|
|||||||
@@ -322,8 +322,6 @@ class SFTConfig(BaseConfig):
|
|||||||
raise ValueError(
|
raise ValueError(
|
||||||
"VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference."
|
"VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference."
|
||||||
)
|
)
|
||||||
if self.model.cp > 1 and self.model.cp_style != "ulysses":
|
|
||||||
raise ValueError("VLM models require cp_style='ulysses' for context parallelism")
|
|
||||||
if self.data.micro_batch_size != 1:
|
if self.data.micro_batch_size != 1:
|
||||||
raise ValueError("VLM SFT requires 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:
|
if self.val is not None and self.val.data.micro_batch_size != 1:
|
||||||
|
|||||||
@@ -242,6 +242,12 @@ class ModelConfig(BaseModelConfig):
|
|||||||
raise ValueError("VLM training requires model.impl='custom'")
|
raise ValueError("VLM training requires model.impl='custom'")
|
||||||
return self
|
return self
|
||||||
|
|
||||||
|
@model_validator(mode="after")
|
||||||
|
def vlm_cp_requires_ulysses(self):
|
||||||
|
if self.vlm is not None and self.cp > 1 and self.cp_style != "ulysses":
|
||||||
|
raise ValueError("VLM models require cp_style='ulysses' for context parallelism")
|
||||||
|
return self
|
||||||
|
|
||||||
@model_validator(mode="after")
|
@model_validator(mode="after")
|
||||||
def validate_cp(self):
|
def validate_cp(self):
|
||||||
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]:
|
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]:
|
||||||
|
|||||||
@@ -94,11 +94,25 @@ def _truncate_mm(
|
|||||||
return cut, sliced
|
return cut, sliced
|
||||||
|
|
||||||
|
|
||||||
|
def multimodal_sample_error(sample: TrainingSample) -> str | None:
|
||||||
|
mm_token_type_ids = sample.mm_token_type_ids
|
||||||
|
if mm_token_type_ids is not None and len(mm_token_type_ids) != len(sample.token_ids):
|
||||||
|
return (
|
||||||
|
"mm_token_type_ids length must match token_ids length "
|
||||||
|
f"({len(mm_token_type_ids)} != {len(sample.token_ids)})"
|
||||||
|
)
|
||||||
|
if sample.mm_kwargs is not None and "image_grid_thw" in sample.mm_kwargs and mm_token_type_ids is None:
|
||||||
|
return "image_grid_thw multimodal samples require mm_token_type_ids"
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch:
|
def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch:
|
||||||
"""
|
"""
|
||||||
Prepare a problem for sequence packing training.
|
Prepare a problem for sequence packing training.
|
||||||
Tokenize and prepare tensors.
|
Tokenize and prepare tensors.
|
||||||
"""
|
"""
|
||||||
|
if error := multimodal_sample_error(training_example):
|
||||||
|
raise ValueError(error)
|
||||||
input_ids = training_example.token_ids
|
input_ids = training_example.token_ids
|
||||||
loss_mask = training_example.mask
|
loss_mask = training_example.mask
|
||||||
inference_logprobs = training_example.logprobs
|
inference_logprobs = training_example.logprobs
|
||||||
@@ -186,10 +200,6 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
|||||||
)
|
)
|
||||||
assert len(routed_experts.data) == len(input_ids) * _routed_experts_row_size(routed_experts)
|
assert len(routed_experts.data) == len(input_ids) * _routed_experts_row_size(routed_experts)
|
||||||
|
|
||||||
if mm_token_type_ids is not None:
|
|
||||||
assert len(mm_token_type_ids) == len(input_ids), (
|
|
||||||
f"mm_token_type_ids: {len(mm_token_type_ids)}, input_ids: {len(input_ids)}"
|
|
||||||
)
|
|
||||||
assert len(env_names) == len(input_ids), f"env_names: {len(env_names)}, input_ids: {len(input_ids)}"
|
assert len(env_names) == len(input_ids), f"env_names: {len(env_names)}, input_ids: {len(input_ids)}"
|
||||||
|
|
||||||
return MicroBatch(
|
return MicroBatch(
|
||||||
@@ -230,17 +240,45 @@ class _MicroBatchBin:
|
|||||||
def first_sample(self) -> MicroBatch:
|
def first_sample(self) -> MicroBatch:
|
||||||
return self.samples[0][1]
|
return self.samples[0][1]
|
||||||
|
|
||||||
def can_add(self, sample: MicroBatch, max_seq_len: int) -> bool:
|
@property
|
||||||
|
def first_lora_idx(self) -> int:
|
||||||
|
return self.samples[0][0]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def first_multimodal_sample(self) -> MicroBatch | None:
|
||||||
|
for _, sample in self.samples:
|
||||||
|
if _is_multimodal_sample(sample):
|
||||||
|
return sample
|
||||||
|
return None
|
||||||
|
|
||||||
|
def can_add(self, sample: MicroBatch, max_seq_len: int, lora_idx: int) -> bool:
|
||||||
# Loss routing is per token (component weight streams), so samples of
|
# Loss routing is per token (component weight streams), so samples of
|
||||||
# different loss types pack together freely — only modality, length and
|
# different loss types pack together freely. Multimodal packing is still
|
||||||
# routed-experts presence constrain packing.
|
# constrained by modality sidecars, length, routed experts, and LoRA/run.
|
||||||
first_sample = self.first_sample
|
first_sample = self.first_sample
|
||||||
return (
|
if self.length + len(sample.input_ids) > max_seq_len:
|
||||||
not _is_multimodal_sample(first_sample)
|
return False
|
||||||
and not _is_multimodal_sample(sample)
|
if (first_sample.routed_experts is None) != (sample.routed_experts is None):
|
||||||
and self.length + len(sample.input_ids) <= max_seq_len
|
return False
|
||||||
and (first_sample.routed_experts is None) == (sample.routed_experts is None)
|
|
||||||
)
|
sample_is_mm = _is_multimodal_sample(sample)
|
||||||
|
existing_mm_sample = self.first_multimodal_sample
|
||||||
|
if existing_mm_sample is None and not sample_is_mm:
|
||||||
|
return True
|
||||||
|
if self.first_lora_idx != lora_idx:
|
||||||
|
return False
|
||||||
|
if existing_mm_sample is not None and sample_is_mm:
|
||||||
|
dst = existing_mm_sample.mm_kwargs
|
||||||
|
src = sample.mm_kwargs
|
||||||
|
assert dst is not None and src is not None
|
||||||
|
return set(dst) == set(src) and all(
|
||||||
|
dst[key].dtype == src[key].dtype
|
||||||
|
and len(dst[key].shape) > 0
|
||||||
|
and len(dst[key].shape) == len(src[key].shape)
|
||||||
|
and dst[key].shape[1:] == src[key].shape[1:]
|
||||||
|
for key in dst
|
||||||
|
)
|
||||||
|
return True
|
||||||
|
|
||||||
def add(self, lora_idx: int, sample: MicroBatch) -> None:
|
def add(self, lora_idx: int, sample: MicroBatch) -> None:
|
||||||
self.samples.append((lora_idx, sample))
|
self.samples.append((lora_idx, sample))
|
||||||
@@ -285,6 +323,7 @@ def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
|
|||||||
env_names: list[str] = []
|
env_names: list[str] = []
|
||||||
ref_logprobs: list[float] | None = [] if has_ref_logprobs else None
|
ref_logprobs: list[float] | None = [] if has_ref_logprobs else None
|
||||||
mm_token_type_ids: list[int] | None = [] if has_mm_token_type_ids else None
|
mm_token_type_ids: list[int] | None = [] if has_mm_token_type_ids else None
|
||||||
|
mm_kwargs: dict[str, EncodedTensor] | None = None
|
||||||
streams: dict[str, list[float] | None] = {name: ([] if has_stream[name] else None) for name in STREAM_FILL}
|
streams: dict[str, list[float] | None] = {name: ([] if has_stream[name] else None) for name in STREAM_FILL}
|
||||||
seq_lens: list[int] = []
|
seq_lens: list[int] = []
|
||||||
routed_experts: RoutedExperts | None = None
|
routed_experts: RoutedExperts | None = None
|
||||||
@@ -318,13 +357,19 @@ def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
|
|||||||
assert routed_experts.shape[1:] == sample.routed_experts.shape[1:]
|
assert routed_experts.shape[1:] == sample.routed_experts.shape[1:]
|
||||||
routed_experts.data += sample.routed_experts.data
|
routed_experts.data += sample.routed_experts.data
|
||||||
routed_experts.shape[0] += sample.routed_experts.shape[0]
|
routed_experts.shape[0] += sample.routed_experts.shape[0]
|
||||||
|
if sample.mm_kwargs is not None:
|
||||||
|
if mm_kwargs is None:
|
||||||
|
mm_kwargs = copy.deepcopy(sample.mm_kwargs)
|
||||||
|
else:
|
||||||
|
for key in mm_kwargs:
|
||||||
|
mm_kwargs[key].data += sample.mm_kwargs[key].data
|
||||||
|
mm_kwargs[key].shape[0] += sample.mm_kwargs[key].shape[0]
|
||||||
seq_lens.extend(sample.seq_lens)
|
seq_lens.extend(sample.seq_lens)
|
||||||
lora_num_tokens[lora_idx] += sample_len
|
lora_num_tokens[lora_idx] += sample_len
|
||||||
|
|
||||||
sequence_lengths = [len(sample.input_ids) for _, sample in bin_content.samples]
|
sequence_lengths = [len(sample.input_ids) for _, sample in bin_content.samples]
|
||||||
assert sum(sequence_lengths) == len(input_ids), (sequence_lengths, len(input_ids))
|
assert sum(sequence_lengths) == len(input_ids), (sequence_lengths, len(input_ids))
|
||||||
assert sum(seq_lens) == len(input_ids), (seq_lens, len(input_ids))
|
assert sum(seq_lens) == len(input_ids), (seq_lens, len(input_ids))
|
||||||
first_sample = bin_content.first_sample
|
|
||||||
|
|
||||||
return MicroBatch(
|
return MicroBatch(
|
||||||
input_ids=input_ids,
|
input_ids=input_ids,
|
||||||
@@ -339,7 +384,7 @@ def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
|
|||||||
routed_experts=routed_experts,
|
routed_experts=routed_experts,
|
||||||
mm_token_type_ids=mm_token_type_ids,
|
mm_token_type_ids=mm_token_type_ids,
|
||||||
env_names=env_names,
|
env_names=env_names,
|
||||||
mm_kwargs=first_sample.mm_kwargs if _is_multimodal_sample(first_sample) else None,
|
mm_kwargs=mm_kwargs,
|
||||||
rl_weights=streams["rl_weights"],
|
rl_weights=streams["rl_weights"],
|
||||||
ce_weights=streams["ce_weights"],
|
ce_weights=streams["ce_weights"],
|
||||||
ref_kl_weights=streams["ref_kl_weights"],
|
ref_kl_weights=streams["ref_kl_weights"],
|
||||||
@@ -354,7 +399,7 @@ def _expand_bins_by_splitting(
|
|||||||
candidates = [
|
candidates = [
|
||||||
(bin_content.workload(bin_cost), idx)
|
(bin_content.workload(bin_cost), idx)
|
||||||
for idx, bin_content in enumerate(bins)
|
for idx, bin_content in enumerate(bins)
|
||||||
if len(bin_content.samples) > 1
|
if len(bin_content.samples) > 1 and bin_content.first_multimodal_sample is None
|
||||||
]
|
]
|
||||||
if not candidates:
|
if not candidates:
|
||||||
break
|
break
|
||||||
@@ -376,8 +421,9 @@ def packed_samples_into_micro_bs(
|
|||||||
We follow the First Fit Decreasing algorithm to pack the samples into bins and minimize potential padding while never truncating.
|
We follow the First Fit Decreasing algorithm to pack the samples into bins and minimize potential padding while never truncating.
|
||||||
With per-token temperatures, samples can be packed together regardless of their temperature values.
|
With per-token temperatures, samples can be packed together regardless of their temperature values.
|
||||||
|
|
||||||
NOTE: Multimodal samples (with mm_kwargs) are NOT packed together as they have variable-sized
|
Multimodal samples pack with text spans from the same run/LoRA and with
|
||||||
vision data that doesn't pack well. Each multimodal sample becomes its own micro batch.
|
compatible eager ``mm_kwargs`` samples. Packed batches preserve sample
|
||||||
|
boundaries in ``seq_lens``.
|
||||||
"""
|
"""
|
||||||
# Sort by (lora_idx, -length) for packing efficiency
|
# Sort by (lora_idx, -length) for packing efficiency
|
||||||
samples.sort(key=lambda x: (x[0], -len(x[1].input_ids)))
|
samples.sort(key=lambda x: (x[0], -len(x[1].input_ids)))
|
||||||
@@ -385,9 +431,10 @@ def packed_samples_into_micro_bs(
|
|||||||
bins: list[_MicroBatchBin] = []
|
bins: list[_MicroBatchBin] = []
|
||||||
|
|
||||||
for idx, sample in samples:
|
for idx, sample in samples:
|
||||||
# Try to find a bin that can fit this sequence (only pack text-only samples)
|
# Try to find a bin that can fit this sequence. Multimodal samples only
|
||||||
|
# pack when their sidecar tensors are compatible.
|
||||||
for bin_content in bins:
|
for bin_content in bins:
|
||||||
if bin_content.can_add(sample, max_seq_len):
|
if bin_content.can_add(sample, max_seq_len, idx):
|
||||||
bin_content.add(idx, sample)
|
bin_content.add(idx, sample)
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -371,6 +371,7 @@ class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin):
|
|||||||
def __init__(self, config, **kwargs):
|
def __init__(self, config, **kwargs):
|
||||||
super().__init__(config, **kwargs)
|
super().__init__(config, **kwargs)
|
||||||
self._is_vlm = hasattr(config, "vision_config")
|
self._is_vlm = hasattr(config, "vision_config")
|
||||||
|
self.supports_packed_multimodal_training = self._is_vlm
|
||||||
|
|
||||||
if self._is_vlm:
|
if self._is_vlm:
|
||||||
self.model = Qwen3_5VLMModel(config)
|
self.model = Qwen3_5VLMModel(config)
|
||||||
|
|||||||
@@ -892,6 +892,7 @@ class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin):
|
|||||||
def __init__(self, config, **kwargs):
|
def __init__(self, config, **kwargs):
|
||||||
super().__init__(config, **kwargs)
|
super().__init__(config, **kwargs)
|
||||||
self._is_vlm = hasattr(config, "vision_config")
|
self._is_vlm = hasattr(config, "vision_config")
|
||||||
|
self.supports_packed_multimodal_training = self._is_vlm
|
||||||
|
|
||||||
if self._is_vlm:
|
if self._is_vlm:
|
||||||
self.model = Qwen3_5MoeVLMModel(config)
|
self.model = Qwen3_5MoeVLMModel(config)
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ from abc import ABC, abstractmethod
|
|||||||
from collections import deque
|
from collections import deque
|
||||||
from collections.abc import Callable, Sequence
|
from collections.abc import Callable, Sequence
|
||||||
|
|
||||||
from prime_rl.trainer.batch import prepare_batch
|
from prime_rl.trainer.batch import multimodal_sample_error, prepare_batch
|
||||||
from prime_rl.trainer.runs import get_multi_run_manager
|
from prime_rl.trainer.runs import get_multi_run_manager
|
||||||
from prime_rl.transport import (
|
from prime_rl.transport import (
|
||||||
MicroBatch,
|
MicroBatch,
|
||||||
@@ -177,6 +177,8 @@ class MultiPacker(BasePacker):
|
|||||||
False,
|
False,
|
||||||
f"Run wrote a sample with ref logprobs length != sample length ({len(sample.ref_logprobs)} != {sample_length})",
|
f"Run wrote a sample with ref logprobs length != sample length ({len(sample.ref_logprobs)} != {sample_length})",
|
||||||
)
|
)
|
||||||
|
if error := multimodal_sample_error(sample):
|
||||||
|
return False, error
|
||||||
return True, None
|
return True, None
|
||||||
|
|
||||||
def _get_batch(self) -> None:
|
def _get_batch(self) -> None:
|
||||||
|
|||||||
@@ -154,6 +154,9 @@ def train(config: TrainerConfig):
|
|||||||
logger.info(f"Initializing tokenizer ({config.tokenizer})")
|
logger.info(f"Initializing tokenizer ({config.tokenizer})")
|
||||||
tokenizer = setup_tokenizer(config.tokenizer)
|
tokenizer = setup_tokenizer(config.tokenizer)
|
||||||
|
|
||||||
|
if config.model.vlm is not None and not getattr(model, "supports_packed_multimodal_training", False):
|
||||||
|
raise ValueError("Packed multimodal training requires model support")
|
||||||
|
|
||||||
# Set up the loss function for the RL loss type (ce / ref_kl are fixed)
|
# Set up the loss function for the RL loss type (ce / ref_kl are fixed)
|
||||||
logger.info(f"Setting up loss function ({config.loss})")
|
logger.info(f"Setting up loss function ({config.loss})")
|
||||||
rl_loss_fn = setup_rl_loss_fn(config.loss)
|
rl_loss_fn = setup_rl_loss_fn(config.loss)
|
||||||
@@ -368,6 +371,11 @@ def train(config: TrainerConfig):
|
|||||||
# tensor to CUDA and let the model's forward sort them.
|
# tensor to CUDA and let the model's forward sort them.
|
||||||
mm_kwargs_raw = micro_batch.get("mm_kwargs")
|
mm_kwargs_raw = micro_batch.get("mm_kwargs")
|
||||||
mm_kwargs = {k: v.to("cuda") for k, v in mm_kwargs_raw.items()} if mm_kwargs_raw else None
|
mm_kwargs = {k: v.to("cuda") for k, v in mm_kwargs_raw.items()} if mm_kwargs_raw else None
|
||||||
|
if mm_kwargs is not None and config.model.vlm is None:
|
||||||
|
raise ValueError(
|
||||||
|
"Received multimodal samples but [model.vlm] is not set. "
|
||||||
|
"Set [model.vlm] to train on multimodal samples."
|
||||||
|
)
|
||||||
mm_token_type_ids = (
|
mm_token_type_ids = (
|
||||||
micro_batch["mm_token_type_ids"].to("cuda")
|
micro_batch["mm_token_type_ids"].to("cuda")
|
||||||
if micro_batch.get("mm_token_type_ids") is not None
|
if micro_batch.get("mm_token_type_ids") is not None
|
||||||
@@ -378,30 +386,30 @@ def train(config: TrainerConfig):
|
|||||||
|
|
||||||
labels = shift_tensor_left(input_ids)
|
labels = shift_tensor_left(input_ids)
|
||||||
|
|
||||||
# VLM + CP is not supported: MRoPE requires global positions but CP shards the sequence
|
seq_lens_are_pre_shard = False
|
||||||
if cp_enabled and mm_kwargs is not None:
|
|
||||||
raise NotImplementedError("Context parallelism is not supported with VLM/multimodal training")
|
|
||||||
|
|
||||||
if cp_enabled:
|
if cp_enabled:
|
||||||
input_ids, forward_position_ids = setup_cp_params(
|
# MRoPE batches must merge image embeddings before sharding.
|
||||||
input_ids,
|
defer_vlm_cp_to_model = mm_kwargs is not None and "image_grid_thw" in mm_kwargs
|
||||||
position_ids,
|
if not defer_vlm_cp_to_model:
|
||||||
cp_rank,
|
input_ids, position_ids = setup_cp_params(
|
||||||
cp_size,
|
input_ids,
|
||||||
cp_group,
|
position_ids,
|
||||||
seq_lens=seq_lens,
|
cp_rank,
|
||||||
cp_style=config.model.cp_style,
|
cp_size,
|
||||||
)
|
cp_group,
|
||||||
|
seq_lens=seq_lens,
|
||||||
|
cp_style=config.model.cp_style,
|
||||||
|
)
|
||||||
|
seq_lens_are_pre_shard = True
|
||||||
labels = shard_for_cp(labels, cp_rank=cp_rank, cp_world_size=cp_size)
|
labels = shard_for_cp(labels, cp_rank=cp_rank, cp_world_size=cp_size)
|
||||||
if routed_experts is not None:
|
if routed_experts is not None and not defer_vlm_cp_to_model:
|
||||||
routed_experts = shard_for_cp(routed_experts, cp_rank=cp_rank, cp_world_size=cp_size)
|
routed_experts = shard_for_cp(routed_experts, cp_rank=cp_rank, cp_world_size=cp_size)
|
||||||
else:
|
|
||||||
forward_position_ids = position_ids
|
|
||||||
|
|
||||||
if config.model.lora:
|
if config.model.lora:
|
||||||
lora_num_tokens = micro_batch["lora_num_tokens"].to("cuda")
|
lora_num_tokens = micro_batch["lora_num_tokens"].to("cuda")
|
||||||
if cp_enabled:
|
if cp_enabled:
|
||||||
chunk_size = input_ids.shape[1]
|
chunk_size = labels.shape[1]
|
||||||
# Convert to cumsum, adjust for CP chunk, convert back to num_tokens
|
# Convert to cumsum, adjust for CP chunk, convert back to num_tokens
|
||||||
cu_offsets = lora_num_tokens.cumsum(dim=0, dtype=torch.int32)
|
cu_offsets = lora_num_tokens.cumsum(dim=0, dtype=torch.int32)
|
||||||
adjusted_cu = torch.clip(cu_offsets - chunk_size * cp_rank, min=0, max=chunk_size)
|
adjusted_cu = torch.clip(cu_offsets - chunk_size * cp_rank, min=0, max=chunk_size)
|
||||||
@@ -421,13 +429,13 @@ def train(config: TrainerConfig):
|
|||||||
out = forward(
|
out = forward(
|
||||||
model,
|
model,
|
||||||
input_ids,
|
input_ids,
|
||||||
forward_position_ids,
|
position_ids,
|
||||||
labels=labels,
|
labels=labels,
|
||||||
temperature=temperatures,
|
temperature=temperatures,
|
||||||
mm_kwargs=mm_kwargs,
|
mm_kwargs=mm_kwargs,
|
||||||
mm_token_type_ids=mm_token_type_ids,
|
mm_token_type_ids=mm_token_type_ids,
|
||||||
seq_lens=seq_lens,
|
seq_lens=seq_lens,
|
||||||
seq_lens_are_pre_shard=cp_enabled,
|
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||||
routed_experts=routed_experts,
|
routed_experts=routed_experts,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -448,6 +448,51 @@ def test_prepare_sample_truncates_mm_at_image_boundary():
|
|||||||
assert n_placeholders == mb.mm_kwargs["pixel_values"].shape[0] # ppt == 1 here
|
assert n_placeholders == mb.mm_kwargs["pixel_values"].shape[0] # ppt == 1 here
|
||||||
|
|
||||||
|
|
||||||
|
def test_prepare_batch_packs_multimodal_with_text():
|
||||||
|
mm_sample = TrainingSample(
|
||||||
|
token_ids=[10, 11, 12],
|
||||||
|
mask=[False, True, True],
|
||||||
|
logprobs=[0.0, -0.1, -0.2],
|
||||||
|
temperatures=[1.0, 1.0, 1.0],
|
||||||
|
advantages=[0.0, 1.0, 1.0],
|
||||||
|
env_name="mm-env",
|
||||||
|
mm_token_type_ids=[0, 1, 0],
|
||||||
|
mm_kwargs={
|
||||||
|
"pixel_values": _encoded(np.array([[1.0, 2.0]], dtype=np.float32)),
|
||||||
|
"image_grid_thw": _encoded(np.array([[1, 2, 2]], dtype=np.int64)),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
text_sample = TrainingSample(
|
||||||
|
token_ids=[20, 21],
|
||||||
|
mask=[False, True],
|
||||||
|
logprobs=[0.0, -0.3],
|
||||||
|
temperatures=[0.7, 0.7],
|
||||||
|
advantages=[0.0, 1.0],
|
||||||
|
env_name="text-env",
|
||||||
|
)
|
||||||
|
|
||||||
|
batches_per_gpu = prepare_batch(
|
||||||
|
rollouts=[mm_sample, text_sample],
|
||||||
|
seq_len=8,
|
||||||
|
num_train_workers=2,
|
||||||
|
idxs=[0, 0],
|
||||||
|
num_loras=1,
|
||||||
|
bin_cost=build_bin_cost(None),
|
||||||
|
)
|
||||||
|
|
||||||
|
real_batches = [batch for batch in _flatten_batches(batches_per_gpu) if _has_loss_tokens(batch)]
|
||||||
|
assert len(real_batches) == 1
|
||||||
|
batch = real_batches[0]
|
||||||
|
assert batch.seq_lens == [3, 2]
|
||||||
|
assert batch.sequence_lengths == [3, 2]
|
||||||
|
assert batch.position_ids == [0, 1, 2, 0, 1]
|
||||||
|
assert batch.mm_token_type_ids == [0, 1, 0, 0, 0]
|
||||||
|
assert batch.mm_kwargs is not None
|
||||||
|
assert batch.mm_kwargs["pixel_values"].shape == [1, 2]
|
||||||
|
assert batch.mm_kwargs["image_grid_thw"].shape == [1, 3]
|
||||||
|
assert batch.env_names == ["mm-env"] * 3 + ["text-env"] * 2
|
||||||
|
|
||||||
|
|
||||||
def test_prepare_sample_none_routed_experts():
|
def test_prepare_sample_none_routed_experts():
|
||||||
"""When routed_experts is None, micro_batch.routed_experts is None."""
|
"""When routed_experts is None, micro_batch.routed_experts is None."""
|
||||||
sample = TrainingSample(
|
sample = TrainingSample(
|
||||||
|
|||||||
@@ -268,6 +268,24 @@ def test_orchestrator_vlm_requires_renderer():
|
|||||||
assert config.renderer is not None
|
assert config.renderer is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_trainer_rejects_vlm_cp_with_ring():
|
||||||
|
config = {
|
||||||
|
"model": {
|
||||||
|
"cp": 2,
|
||||||
|
"impl": "custom",
|
||||||
|
"optimization_dtype": "bfloat16",
|
||||||
|
"reduce_dtype": "bfloat16",
|
||||||
|
"vlm": {
|
||||||
|
"vision_encoder_attr": "model.visual",
|
||||||
|
"language_model_attr": "model.language_model",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
with pytest.raises(ValidationError, match="cp_style='ulysses'"):
|
||||||
|
TrainerConfig.model_validate(config)
|
||||||
|
|
||||||
|
|
||||||
def test_selective_activation_checkpointing_requires_custom_impl():
|
def test_selective_activation_checkpointing_requires_custom_impl():
|
||||||
with pytest.raises(ValidationError, match="Selective activation checkpointing requires model.impl='custom'"):
|
with pytest.raises(ValidationError, match="Selective activation checkpointing requires model.impl='custom'"):
|
||||||
TrainerModelConfig.model_validate({"impl": "hf", "ac": {"mode": "selective"}})
|
TrainerModelConfig.model_validate({"impl": "hf", "ac": {"mode": "selective"}})
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Generator
|
from typing import Generator
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
import pytest
|
import pytest
|
||||||
import tomli_w
|
import tomli_w
|
||||||
import torch
|
import torch
|
||||||
@@ -12,7 +13,7 @@ from prime_rl.trainer.rl.packer import MultiPacker
|
|||||||
from prime_rl.trainer.runs import setup_multi_run_manager
|
from prime_rl.trainer.runs import setup_multi_run_manager
|
||||||
from prime_rl.trainer.utils import build_bin_cost
|
from prime_rl.trainer.utils import build_bin_cost
|
||||||
from prime_rl.trainer.world import reset_world
|
from prime_rl.trainer.world import reset_world
|
||||||
from prime_rl.transport.types import TrainingSample
|
from prime_rl.transport.types import EncodedTensor, TrainingSample
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True, scope="module")
|
@pytest.fixture(autouse=True, scope="module")
|
||||||
@@ -52,6 +53,66 @@ def make_training_sample() -> TrainingSample:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _encoded_tensor(data, dtype) -> EncodedTensor:
|
||||||
|
arr = np.asarray(data, dtype=dtype)
|
||||||
|
return EncodedTensor(dtype=str(arr.dtype), shape=list(arr.shape), data=arr.tobytes())
|
||||||
|
|
||||||
|
|
||||||
|
def _decode_encoded_tensor(encoded: EncodedTensor):
|
||||||
|
return np.frombuffer(encoded.data, dtype=np.dtype(encoded.dtype)).reshape(encoded.shape).tolist()
|
||||||
|
|
||||||
|
|
||||||
|
def _mm_sample(value: float, env_name: str = "test-env") -> TrainingSample:
|
||||||
|
return TrainingSample(
|
||||||
|
token_ids=[1, 250, 2],
|
||||||
|
mask=[False, True, True],
|
||||||
|
logprobs=[0.0, -0.1, -0.2],
|
||||||
|
temperatures=[1.0, 1.0, 1.0],
|
||||||
|
env_name=env_name,
|
||||||
|
advantages=[0.0, 1.0, 1.0],
|
||||||
|
mm_token_type_ids=[0, 1, 0],
|
||||||
|
mm_kwargs={
|
||||||
|
"pixel_values": _encoded_tensor([[value, value + 1]], np.float32),
|
||||||
|
"image_grid_thw": _encoded_tensor([[1, 2, 2]], np.int64),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _packer_with_two_runs(tmp_path, monkeypatch, dp_world_size, seq_len):
|
||||||
|
"""Set up a MultiPacker over two discovered runs; capture sent grids."""
|
||||||
|
reset_world()
|
||||||
|
runs._MULTI_RUN_MANAGER = None
|
||||||
|
manager = setup_multi_run_manager(output_dir=tmp_path, max_runs=2, device=torch.device("cpu"))
|
||||||
|
create_run_with_config(tmp_path, "run_a")
|
||||||
|
create_run_with_config(tmp_path, "run_b")
|
||||||
|
manager.discover_runs()
|
||||||
|
|
||||||
|
sent: list = []
|
||||||
|
|
||||||
|
class DummyReceiver:
|
||||||
|
def receive(self):
|
||||||
|
return []
|
||||||
|
|
||||||
|
def reset_run(self, idx):
|
||||||
|
pass
|
||||||
|
|
||||||
|
class DummySender:
|
||||||
|
def send(self, micro_batch_grid):
|
||||||
|
sent.append(micro_batch_grid)
|
||||||
|
|
||||||
|
monkeypatch.setattr("prime_rl.trainer.rl.packer.setup_training_batch_receiver", lambda _c: DummyReceiver())
|
||||||
|
monkeypatch.setattr("prime_rl.trainer.rl.packer.setup_micro_batch_sender", lambda *a, **k: DummySender())
|
||||||
|
packer = MultiPacker(
|
||||||
|
dp_world_size=dp_world_size,
|
||||||
|
seq_len=seq_len,
|
||||||
|
pad_to_multiple_of=1,
|
||||||
|
config=FileSystemTransportConfig(),
|
||||||
|
bin_cost=build_bin_cost(None),
|
||||||
|
start_step=0,
|
||||||
|
)
|
||||||
|
return manager, packer, sent
|
||||||
|
|
||||||
|
|
||||||
def test_packer_progress_updates_once_per_run(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
def test_packer_progress_updates_once_per_run(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
reset_world()
|
reset_world()
|
||||||
runs._MULTI_RUN_MANAGER = None
|
runs._MULTI_RUN_MANAGER = None
|
||||||
@@ -114,3 +175,67 @@ def test_packer_progress_updates_once_per_run(tmp_path: Path, monkeypatch: pytes
|
|||||||
micro_batch = sender.sent[0][0][0]
|
micro_batch = sender.sent[0][0][0]
|
||||||
assert micro_batch.run_id == "run_test123"
|
assert micro_batch.run_id == "run_test123"
|
||||||
assert micro_batch.run_step == 1
|
assert micro_batch.run_step == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_multipacker_pack_preserves_mm_kwargs_modality_and_run_tagging(tmp_path, monkeypatch):
|
||||||
|
"""MultiPacker keeps multimodal and text microbatches aligned across ranks."""
|
||||||
|
from prime_rl.trainer.batch import _is_multimodal_sample
|
||||||
|
|
||||||
|
manager, packer, sent = _packer_with_two_runs(tmp_path, monkeypatch, dp_world_size=2, seq_len=5)
|
||||||
|
malformed = _mm_sample(0.0)
|
||||||
|
malformed.mm_token_type_ids = None
|
||||||
|
valid, reason = packer._validate_sample(malformed)
|
||||||
|
assert not valid
|
||||||
|
assert reason is not None and "require mm_token_type_ids" in reason
|
||||||
|
|
||||||
|
a, b = manager.id_2_idx["run_a"], manager.id_2_idx["run_b"]
|
||||||
|
for idx, value in ((a, 1.0), (b, 10.0)):
|
||||||
|
packer.buffers[idx].append((_mm_sample(value), 0))
|
||||||
|
packer.buffers[idx].append((make_training_sample(), 0))
|
||||||
|
|
||||||
|
packer.pack()
|
||||||
|
assert sent, "pack() sent nothing"
|
||||||
|
grid = sent[-1]
|
||||||
|
assert len(grid) == 2
|
||||||
|
|
||||||
|
for step_mbs in zip(*grid):
|
||||||
|
assert len({_is_multimodal_sample(mb) for mb in step_mbs}) == 1
|
||||||
|
|
||||||
|
mm_mbs = [mb for rank in grid for mb in rank if _is_multimodal_sample(mb)]
|
||||||
|
assert mm_mbs, "no MM microbatches produced"
|
||||||
|
real_run_idxs = set()
|
||||||
|
for mb in mm_mbs:
|
||||||
|
assert mb.mm_kwargs is not None
|
||||||
|
if any(mb.loss_mask):
|
||||||
|
tagged = [i for i, n in enumerate(mb.lora_num_tokens) if n > 0]
|
||||||
|
assert len(tagged) == 1 and mb.lora_num_tokens[tagged[0]] == len(mb.input_ids)
|
||||||
|
real_run_idxs.add(tagged[0])
|
||||||
|
assert real_run_idxs == {a, b}, f"both runs' MM should be tagged; got {real_run_idxs}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_multipacker_packs_mm_kwargs_within_each_run(tmp_path, monkeypatch):
|
||||||
|
"""Compatible eager multimodal samples pack within a run but never across runs."""
|
||||||
|
from prime_rl.trainer.batch import _is_multimodal_sample
|
||||||
|
|
||||||
|
manager, packer, sent = _packer_with_two_runs(tmp_path, monkeypatch, dp_world_size=1, seq_len=12)
|
||||||
|
a, b = manager.id_2_idx["run_a"], manager.id_2_idx["run_b"]
|
||||||
|
for idx, base in ((a, 1.0), (b, 10.0)):
|
||||||
|
packer.buffers[idx].append((_mm_sample(base), 0))
|
||||||
|
packer.buffers[idx].append((_mm_sample(base + 2), 0))
|
||||||
|
|
||||||
|
packer.pack()
|
||||||
|
assert sent
|
||||||
|
grid = sent[-1]
|
||||||
|
real_mm_mbs = [mb for rank in grid for mb in rank if _is_multimodal_sample(mb) and any(mb.loss_mask)]
|
||||||
|
|
||||||
|
assert len(real_mm_mbs) == 2
|
||||||
|
for mb in real_mm_mbs:
|
||||||
|
assert len(mb.input_ids) == 6
|
||||||
|
assert mb.position_ids == [0, 1, 2, 0, 1, 2]
|
||||||
|
assert mb.seq_lens == [3, 3]
|
||||||
|
assert mb.mm_kwargs is not None
|
||||||
|
assert mb.mm_kwargs["pixel_values"].shape == [2, 2]
|
||||||
|
assert mb.mm_kwargs["image_grid_thw"].shape == [2, 3]
|
||||||
|
assert len(_decode_encoded_tensor(mb.mm_kwargs["pixel_values"])) == 2
|
||||||
|
tagged = [i for i, n in enumerate(mb.lora_num_tokens) if n > 0]
|
||||||
|
assert len(tagged) == 1
|
||||||
|
|||||||
Reference in New Issue
Block a user