Compare commits

..
Author SHA1 Message Date
35671879fb support multi-node ep (#1894)
Release / Push CUDA image to Docker (push) Canceled after 0s
* support multi-node ep

* fix

* docs(changelog): add inference data parallel config entries

Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>

---------

Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>
2026-02-27 02:43:43 +00:00
JannikStandGitHub 1ea7a8d3b5 fix: handle skipped eval intervals when ckpt_step jumps (#1903)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: handle skipped eval intervals when ckpt_step jumps + fix eval step reporting

When strict_async_level=False, ckpt_step can jump over eval interval
boundaries (e.g. 24->26 skipping 25), permanently missing scheduled evals.
Replace exact modulo check with range check that detects crossed intervals.

Also fix eval metrics being logged at progress.step instead of ckpt_step,
which caused eval results to appear at the wrong step in the metrics API.

* format ruff

* revert step=ckpt_step back to step=progress.step for eval logging

W&B requires monotonically increasing steps. Using ckpt_step (which lags
behind progress.step) causes W&B to silently drop eval metrics since
training already logged at a higher step. The ckpt_step is already
embedded in the metrics as progress/ckpt_step for platform-side lookup.

* fix stale comment about eval subprocess

* add unit tests for eval scheduling range check

* extract eval scheduling logic into compute_eval_ckpt_step function

Move range check logic from inline in orchestrator.py to a proper
function in eval_utils.py so tests import the real implementation.

* use plain functions instead of class in tests
2026-02-27 01:45:14 +01:00
halleriteandGitHub f655f71c33 simplify vlm path (#1877)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-27 01:06:26 +01:00
12 changed files with 256 additions and 271 deletions
+1
View File
@@ -85,6 +85,7 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
- **`inference.enable_return_routed_experts`**: Added flag to enable return routed experts. Passed to vLLM as `--enable-return-routed-experts` (2026-02-22)
- **`orchestrator.oversampling_factor`**: Added rollout-only over-sampling config that resolves `max_inflight_rollouts = int(batch_size * oversampling_factor)` when `max_inflight_rollouts` is unset. Cannot be used with `token_batch_size` or together with explicit `max_inflight_rollouts` (2026-02-25)
- **`model.fused_lm_head_chunk_size`**: Changed default value from 2048 to 8192 for RL training (2026-02-26)
- **`inference.data_parallel_size_local`** and **`inference.data_parallel_rpc_port`**: Added data-parallel node-local controls for vLLM, passed as `--data-parallel-size-local` and `--data-parallel-rpc-port` (defaults: `None`, `13345`) (2026-02-26)
- **`dump_config`**: Removed from `RLConfig`. Replaced by `dry_run` (see below) (2026-02-26)
- **`slurm.dry_run`**: Removed from `SlurmConfig`. Replaced by top-level `dry_run` (see below) (2026-02-26)
- **`dry_run`**: Added to `RLConfig` and `SFTConfig` (default: `False`). When set, validates the config, writes resolved subconfigs to `output_dir/configs/`, and exits without starting any processes. Works the same for both local and SLURM runs (2026-02-26)
+1 -1
View File
@@ -85,7 +85,7 @@ override-dependencies = [
[tool.uv.sources]
torch = { index = "pytorch-cu128" }
math-env = { index = "primeintellect" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "3f555af" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "b35d0c7" }
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "609e3d5" }
+23 -2
View File
@@ -181,6 +181,23 @@ class InferenceConfig(BaseSettings):
),
] = 1
data_parallel_size_local: Annotated[
int | None,
Field(
ge=1,
description="Number of data parallel replicas to run on this node. Passed to vLLM as `--data-parallel-size-local`.",
),
] = None
data_parallel_rpc_port: Annotated[
int,
Field(
ge=1,
le=65535,
description="RPC port for data parallel communication. Passed to vLLM as `--data-parallel-rpc-port`.",
),
] = 13345
seed: Annotated[
int,
Field(
@@ -245,8 +262,10 @@ class InferenceConfig(BaseSettings):
size. Unless LoRA is enabled, in which case only one API server is
supported (vLLM limitation).
"""
if self.api_server_count < self.parallel.dp:
self.api_server_count = self.parallel.dp
if "api_server_count" not in self.model_fields_set:
min_api_server_count = self.data_parallel_size_local or self.parallel.dp
if self.api_server_count < min_api_server_count:
self.api_server_count = min_api_server_count
if self.enable_lora:
self.api_server_count = 1 # LoRA requires only one API server
@@ -268,6 +287,8 @@ class InferenceConfig(BaseSettings):
"model.rope_scaling": "rope_scaling",
"parallel.tp": "tensor_parallel_size",
"parallel.dp": "data_parallel_size",
"data_parallel_size_local": "data_parallel_size_local",
"data_parallel_rpc_port": "data_parallel_rpc_port",
"enable_lora": "enable_lora",
"enable_prefix_caching": "enable_prefix_caching",
"max_loras": "max_loras",
+28
View File
@@ -612,6 +612,34 @@ class RLConfig(BaseSettings):
self.deployment.num_train_nodes // self.deployment.nodes_per_fsdp_group
)
if self.inference is not None and self.inference.enable_expert_parallel:
inference_tp = self.inference.parallel.tp
if self.deployment.gpus_per_node % inference_tp != 0:
raise ValueError(
"deployment.gpus_per_node must be divisible by inference.parallel.tp "
"when inference.enable_expert_parallel is enabled in multi-node deployment."
)
inferred_dp_local = self.deployment.gpus_per_node // inference_tp
total_infer_gpus = self.deployment.num_infer_nodes * self.deployment.gpus_per_node
expected_global_world_size = self.inference.parallel.dp * inference_tp
if expected_global_world_size != total_infer_gpus:
raise ValueError(
"For multi-node expert parallel inference, inference.parallel.dp * inference.parallel.tp "
f"must match total inference GPUs ({total_infer_gpus}), got {expected_global_world_size}."
)
if self.inference.data_parallel_size_local is None:
self.inference.data_parallel_size_local = inferred_dp_local
elif self.inference.data_parallel_size_local != inferred_dp_local:
raise ValueError(
"inference.data_parallel_size_local must equal deployment.gpus_per_node / inference.parallel.tp "
f"({inferred_dp_local}) when inference.enable_expert_parallel is enabled in multi-node deployment."
)
if not self.inference.enable_lora and self.inference.api_server_count == self.inference.parallel.dp:
self.inference.api_server_count = inferred_dp_local
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
assert self.trainer.weight_broadcast.type == "nccl"
self.trainer.weight_broadcast.host = "0.0.0.0"
+5
View File
@@ -367,6 +367,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
gpus_per_node=config.deployment.gpus_per_node,
)
else:
assert config.inference is not None
script = template.render(
config_dir=config_dir, # TODO: should prob have each subconfig path separately
job_name=config.slurm.job_name,
@@ -378,6 +380,9 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
num_infer_nodes=config.deployment.num_infer_nodes,
num_teacher_nodes=config.deployment.num_teacher_nodes,
gpus_per_node=config.deployment.gpus_per_node,
inference_tp=config.inference.parallel.tp,
inference_enable_expert_parallel=config.inference.enable_expert_parallel,
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
@@ -43,50 +43,6 @@ class _RoutedExpertsCapture:
choice.routed_experts = self.routed_experts[choice.index]
def _collapse_image_placeholders(
original_tokens: list[int],
override_tokens: list[int],
) -> list[int]:
"""
Collapse pre-expanded image placeholder tokens in override_tokens.
In multi-turn VLM conversations, tokens from previous turns already have
expanded image placeholders (e.g., 64 consecutive <|image_pad|> tokens).
If left as-is, _process_inputs re-expands each token individually, causing
compounding token inflation across turns.
Detects placeholder token IDs by comparing with the original engine tokens
(which have single placeholders from _preprocess_chat), then collapses
consecutive runs back to single tokens so _process_inputs can expand
them correctly.
"""
if not override_tokens or original_tokens == override_tokens:
return override_tokens
def get_block_tokens(tokens: list[int], min_run: int) -> set[int]:
"""Return token IDs that appear in consecutive runs >= min_run."""
result = set()
run_start = 0
for i in range(1, len(tokens) + 1):
if i == len(tokens) or tokens[i] != tokens[run_start]:
if i - run_start >= min_run:
result.add(tokens[run_start])
run_start = i
return result
# Placeholder tokens appear in blocks of 2+ in override but only as singles in original
placeholder_ids = get_block_tokens(override_tokens, 2) - get_block_tokens(original_tokens, 2)
if not placeholder_ids:
return override_tokens
result = []
for token in override_tokens:
if token in placeholder_ids and result and result[-1] == token:
continue
result.append(token)
return result
class ChatCompletionRequestWithTokens(ChatCompletionRequest):
field_names: ClassVar[Optional[set[str]]] = None
tokens: list[int] = Field(description=("Prompt tokens to use for the request."))
@@ -167,16 +123,9 @@ class OpenAIServingChatWithTokens(OpenAIServingChat):
conversation, engine_prompts = result
# For VLM models: collapse pre-expanded image placeholders before _process_inputs.
# In multi-turn token prompts, previous turns' image placeholders are already expanded
# (e.g., 64 consecutive <|image_pad|>). Without collapsing, _process_inputs re-expands
# each token, inflating counts (64 → 127 → 253 → ...) across turns.
if engine_prompts[0].get("multi_modal_data"):
override_tokens = _collapse_image_placeholders(engine_prompts[0]["prompt_token_ids"], request.tokens) # type: ignore
else:
override_tokens = request.tokens
engine_prompts[0]["prompt_token_ids"] = override_tokens # type: ignore
# VLM conversations use MITO (message-based) instead of TITO, so
# multi_modal_data is not expected here. Override prompt tokens directly.
engine_prompts[0]["prompt_token_ids"] = request.tokens # type: ignore
request_id = f"chatcmpl-{self._base_request_id(raw_request, request.request_id)}"
+26
View File
@@ -13,6 +13,32 @@ from prime_rl.utils.monitor import get_monitor
from prime_rl.utils.utils import capitalize
def compute_eval_ckpt_step(
ckpt_step: int,
prev_ckpt_step: int,
last_eval_step: int,
interval: int,
eval_base_model: bool = True,
) -> int | None:
"""Determine which checkpoint step (if any) should trigger an eval.
Handles the case where ckpt_step jumps over interval boundaries by finding
the highest interval-aligned step in (prev_ckpt_step, ckpt_step].
Returns the interval step to eval at, or None if no eval should run.
"""
if ckpt_step <= prev_ckpt_step:
return None
highest_interval_step = (ckpt_step // interval) * interval
if highest_interval_step > prev_ckpt_step and highest_interval_step > last_eval_step:
if highest_interval_step == 0:
if ckpt_step == 0 and eval_base_model:
return 0
else:
return highest_interval_step
return None
def get_eval_sampling_args(sampling_config: EvalSamplingConfig) -> dict[str, Any]:
"""Get sampling args for evaluation."""
# Initialize sampling args
+28 -10
View File
@@ -7,7 +7,7 @@ from concurrent.futures import ThreadPoolExecutor
import tomli_w
from prime_rl.orchestrator.advantage import compute_advantages
from prime_rl.orchestrator.eval_utils import get_eval_sampling_args
from prime_rl.orchestrator.eval_utils import compute_eval_ckpt_step, get_eval_sampling_args
from prime_rl.orchestrator.event_loop_lag import EventLoopLagMonitor
from prime_rl.orchestrator.patches import monkey_patch_chat_completion_logprobs, monkey_patch_oai_iterable_types
from prime_rl.orchestrator.trajectories import build_vlm_image_cache, interleave_rollout
@@ -309,6 +309,8 @@ async def orchestrate(config: OrchestratorConfig):
# Track last online eval checkpoint step for this process
last_eval_step = -1
# Track previous ckpt_step to detect when ckpt_step jumps over eval interval boundaries
prev_ckpt_step = -1
# Reset weights to base model if starting from scratch
progress = Progress()
@@ -318,8 +320,12 @@ async def orchestrate(config: OrchestratorConfig):
logger.info(f"Resuming training from checkpoint step {checkpoint_step}")
scheduler.ckpt_step = progress.step # Always resume from the latest checkpoint
if config.eval and config.eval.skip_eval_on_resume:
prev_ckpt_step = scheduler.ckpt_step
last_eval_step = scheduler.ckpt_step
logger.info(f"Skipping online eval on resume (ckpt_step={scheduler.ckpt_step})")
else:
# Allow eval at resumed step by setting prev_ckpt_step one behind
prev_ckpt_step = scheduler.ckpt_step - 1
# In NCCL mode, skip existence check - weights are broadcasted, not stored on disk
check_exists = config.weight_broadcast.type != "nccl"
@@ -376,16 +382,25 @@ async def orchestrate(config: OrchestratorConfig):
logger.info(f"Starting orchestrator step {progress.step}")
step_start_time = time.perf_counter()
# Run evals BEFORE training (blocking, in subprocess to isolate event loop)
# This ensures weights don't change during eval and eval doesn't cause event loop lag
if (
config.eval
and ckpt_step % config.eval.interval == 0
and ckpt_step > last_eval_step
and ((ckpt_step == 0 and config.eval.eval_base_model) or ckpt_step > 0)
):
# Run evals BEFORE training (blocking). Weight updates are paused via
# scheduler.checkpoint_ready during eval to ensure consistent weights.
# Use range check to handle ckpt_step jumping over interval boundaries.
eval_ckpt_step = None
if config.eval:
eval_ckpt_step = compute_eval_ckpt_step(
ckpt_step=ckpt_step,
prev_ckpt_step=prev_ckpt_step,
last_eval_step=last_eval_step,
interval=config.eval.interval,
eval_base_model=config.eval.eval_base_model,
)
if eval_ckpt_step is not None:
last_eval_step = ckpt_step
logger.info(f"Running evals for checkpoint step {ckpt_step}")
if eval_ckpt_step != ckpt_step:
logger.info(f"Running evals for interval step {eval_ckpt_step} (current ckpt_step={ckpt_step})")
else:
logger.info(f"Running evals for checkpoint step {ckpt_step}")
# Pause weight updates and re-scheduling of training rollouts during eval
# to avoid evaluating across different checkpoints and avoid congestion
@@ -417,6 +432,9 @@ async def orchestrate(config: OrchestratorConfig):
# Resume weight updates
scheduler.checkpoint_ready.set()
# Update prev_ckpt_step for next iteration
prev_ckpt_step = ckpt_step
# Schedule generating the training batch
temperature = compute_temperature(progress.step, config.sampling, config.max_steps)
sampling_args = get_sampling_args(config.sampling, temperature=temperature)
+53 -17
View File
@@ -13,6 +13,16 @@
export NUM_TRAIN_NODES={{ num_train_nodes }}
export NUM_INFER_NODES={{ num_infer_nodes }}
export GPUS_PER_NODE={{ gpus_per_node }}
export INFERENCE_TP={{ inference_tp }}
export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parallel else "0" }}
export INFERENCE_DATA_PARALLEL_RPC_PORT={{ inference_data_parallel_rpc_port }}
export INFERENCE_DP_LOCAL=$((GPUS_PER_NODE / INFERENCE_TP))
# Enable distributed EP mode only when expert parallelism spans multiple inference nodes.
export USE_DISTRIBUTED_EP=0
if [ "$INFERENCE_ENABLE_EXPERT_PARALLEL" -eq 1 ] && [ "$NUM_INFER_NODES" -gt 1 ]; then
USE_DISTRIBUTED_EP=1
fi
# Paths
export PROJECT_DIR={{ project_dir }}
@@ -34,23 +44,30 @@ export PYTHONUNBUFFERED=1
export OMP_NUM_THREADS=1
# Networking
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
export INFER_HOSTS=${HOSTNAMES[@]:0:$NUM_INFER_NODES}
export TRAIN_HOSTS=${HOSTNAMES[@]:$NUM_INFER_NODES:$SLURM_JOB_NUM_NODES}
HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
INFER_HOSTS=( ${HOSTNAMES[@]:0:$NUM_INFER_NODES} )
TRAIN_HOSTS=( ${HOSTNAMES[@]:$NUM_INFER_NODES:$SLURM_JOB_NUM_NODES} )
export INFER_HEAD_HOST="${INFER_HOSTS[0]}"
export HOSTNAMES_STR="${HOSTNAMES[*]}"
INFER_URLS=""
for host in ${INFER_HOSTS[@]}; do
if [ -z "$INFER_URLS" ]; then
INFER_URLS="http://$host:8000/v1"
else
INFER_URLS="$INFER_URLS,http://$host:8000/v1"
fi
done
if [ "$USE_DISTRIBUTED_EP" -eq 1 ]; then
INFER_URLS="http://${INFER_HEAD_HOST}:8000/v1"
else
for host in "${INFER_HOSTS[@]}"; do
if [ -z "$INFER_URLS" ]; then
INFER_URLS="http://$host:8000/v1"
else
INFER_URLS="$INFER_URLS,http://$host:8000/v1"
fi
done
fi
export INFER_URLS
echo "HOSTNAMES=${HOSTNAMES[@]}"
echo "TRAIN_HOSTS=${TRAIN_HOSTS[@]}"
echo "INFER_HOSTS=${INFER_HOSTS[@]}"
echo "HOSTNAMES=${HOSTNAMES[*]}"
echo "TRAIN_HOSTS=${TRAIN_HOSTS[*]}"
echo "INFER_HOSTS=${INFER_HOSTS[*]}"
echo "INFER_URLS=${INFER_URLS}"
echo "USE_DISTRIBUTED_EP=${USE_DISTRIBUTED_EP}"
export MASTER_ADDR="${HOSTNAMES[$NUM_INFER_NODES]}"
export MASTER_PORT=29500
@@ -84,9 +101,28 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
INFER_NODE_RANK=$SLURM_PROCID
export VLLM_WORKER_MULTIPROC_METHOD=spawn
uv run inference \
@ $CONFIG_DIR/inference.toml \
2>&1 | tee $OUTPUT_DIR/slurm/latest_infer_node_rank_${INFER_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_infer_node_rank_${INFER_NODE_RANK}.log
if [ "$USE_DISTRIBUTED_EP" -eq 1 ]; then
INFER_DP_START_RANK=$((INFER_NODE_RANK * INFERENCE_DP_LOCAL))
if [ "$INFER_NODE_RANK" -eq 0 ]; then
uv run inference \
@ $CONFIG_DIR/inference.toml \
--data-parallel-address $INFER_HEAD_HOST \
--data-parallel-rpc-port $INFERENCE_DATA_PARALLEL_RPC_PORT \
2>&1 | tee $OUTPUT_DIR/slurm/latest_infer_node_rank_${INFER_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_infer_node_rank_${INFER_NODE_RANK}.log
else
uv run inference \
@ $CONFIG_DIR/inference.toml \
--data-parallel-start-rank $INFER_DP_START_RANK \
--data-parallel-address $INFER_HEAD_HOST \
--data-parallel-rpc-port $INFERENCE_DATA_PARALLEL_RPC_PORT \
--headless \
2>&1 | tee $OUTPUT_DIR/slurm/latest_infer_node_rank_${INFER_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_infer_node_rank_${INFER_NODE_RANK}.log
fi
else
uv run inference \
@ $CONFIG_DIR/inference.toml \
2>&1 | tee $OUTPUT_DIR/slurm/latest_infer_node_rank_${INFER_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_infer_node_rank_${INFER_NODE_RANK}.log
fi
else
TRAIN_NODE_RANK=$((SLURM_PROCID - NUM_INFER_NODES))
@@ -104,7 +140,7 @@ else
# This is required for compilation to work correctly
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True"
echo $HOSTNAMES | tee $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log
echo $HOSTNAMES_STR | tee $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log
uv run torchrun \
--nnodes=$NUM_TRAIN_NODES \
@@ -1,186 +1 @@
import pytest
from prime_rl.inference.vllm.serving_chat_with_tokens import _collapse_image_placeholders
# Simulated Qwen3-VL special token IDs
VISION_START = 151652
IMAGE_PAD = 151655
VISION_END = 151653
def _make_vision_block(pad_count: int) -> list[int]:
"""Build a <|vision_start|> + N * <|image_pad|> + <|vision_end|> block."""
return [VISION_START] + [IMAGE_PAD] * pad_count + [VISION_END]
# ---- Fast-path: no collapsing needed ----
def test_identical_tokens_returns_override():
tokens = [1, 2, 3, 4, 5]
assert _collapse_image_placeholders(tokens, tokens) is tokens
def test_empty_override_returns_empty():
assert _collapse_image_placeholders([1, 2, 3], []) == []
def test_no_blocks_in_override_returns_unchanged():
original = [1, 2, 3]
override = [1, 2, 3, 4, 5]
assert _collapse_image_placeholders(original, override) == override
def test_block_in_both_original_and_override_is_not_collapsed():
"""If a token appears in blocks in BOTH sequences, it's not a placeholder."""
original = [1, 7, 7, 7, 2]
override = [1, 7, 7, 7, 7, 7, 2]
assert _collapse_image_placeholders(original, override) == override
# ---- VLM image placeholder collapsing ----
def test_single_expanded_block():
"""Turn 1: one image already expanded (64 pads), should collapse to 1."""
original = [10, VISION_START, IMAGE_PAD, VISION_END, 20]
override = [10, VISION_START] + [IMAGE_PAD] * 64 + [VISION_END, 20]
result = _collapse_image_placeholders(original, override)
assert result == original
def test_two_images_second_unexpanded():
"""Turn 1: image 1 expanded (64), image 2 unexpanded (1). Should collapse to 1 + 1."""
original = [10, *_make_vision_block(1), 20, *_make_vision_block(1), 30]
override = [10, *_make_vision_block(64), 20, *_make_vision_block(1), 30]
result = _collapse_image_placeholders(original, override)
assert result == original
def test_three_turn_compounding_inflation():
"""
Reproduces the actual bug: 3-image conversation where _process_inputs
re-expands already-expanded blocks, inflating 192 → 381 image_pad tokens.
Turn 0 (message-based): 1 image → 64 pads (correct)
Turn 1 (token-based): prev has 64 expanded + new has 1 unexpanded → 65 pads
After buggy re-expansion: 64 + 64 + 63 = 191 pads
Turn 2 (token-based): prev has 191 expanded + new has 1 unexpanded → 192 pads
After buggy re-expansion: 381 pads
The fix collapses expanded blocks before _process_inputs, so each image
has exactly 1 placeholder token for correct expansion.
"""
# Original engine tokens: 3 images, each with single placeholder
original = [
10,
*_make_vision_block(1), # image 1
20,
*_make_vision_block(1), # image 2
30,
*_make_vision_block(1), # image 3
40,
]
# Override tokens from get_prompt_ids at turn 2:
# images 1+2 have been expanded in previous response (191 pads from the bug),
# image 3 has 1 unexpanded pad from /tokenize
override = [
10,
VISION_START,
*([IMAGE_PAD] * 191),
VISION_END, # images 1+2 inflated
30,
*_make_vision_block(1), # image 3 unexpanded
40,
]
result = _collapse_image_placeholders(original, override)
# After collapsing, each block should have exactly 1 image_pad
pad_count = sum(1 for t in result if t == IMAGE_PAD)
assert pad_count == 2 # two vision blocks, one pad each
def test_realistic_turn1_token_sequence():
"""
Realistic turn 1 scenario: prev turn response had 64 expanded pads,
/tokenize returned 1 unexpanded pad for the new image.
"""
# Surrounding text tokens
system_tokens = [100, 101, 102]
user1_text = [200, 201]
assistant_response = [300, 301]
user2_text = [400, 401]
gen_prompt = [500]
# Original: _preprocess_chat tokenizes full messages with single placeholders
original = (
system_tokens
+ user1_text
+ _make_vision_block(1)
+ assistant_response
+ user2_text
+ _make_vision_block(1)
+ gen_prompt
)
# Override: get_prompt_ids concatenated prev response (expanded) + tokenized new messages (unexpanded)
override = (
system_tokens
+ user1_text
+ _make_vision_block(64) # expanded from prev response
+ assistant_response
+ user2_text
+ _make_vision_block(1) # unexpanded from /tokenize
+ gen_prompt
)
result = _collapse_image_placeholders(original, override)
# Both vision blocks should have exactly 1 pad token
pad_count = sum(1 for t in result if t == IMAGE_PAD)
assert pad_count == 2
# Non-image tokens should be preserved
non_pad = [t for t in result if t != IMAGE_PAD]
non_pad_original = [t for t in original if t != IMAGE_PAD]
assert non_pad == non_pad_original
@pytest.mark.parametrize("expanded_size", [4, 16, 64, 256])
def test_various_expansion_sizes(expanded_size):
"""Works for any expansion factor, not just 64."""
original = _make_vision_block(1)
override = _make_vision_block(expanded_size)
result = _collapse_image_placeholders(original, override)
assert result == original
def test_multiple_placeholder_types():
"""Handles models with both image_pad and video_pad tokens."""
VIDEO_PAD = 151656
original = [1, VISION_START, IMAGE_PAD, VISION_END, 2, VISION_START, VIDEO_PAD, VISION_END, 3]
override = [
1,
VISION_START,
*([IMAGE_PAD] * 64),
VISION_END,
2,
VISION_START,
*([VIDEO_PAD] * 32),
VISION_END,
3,
]
result = _collapse_image_placeholders(original, override)
assert sum(1 for t in result if t == IMAGE_PAD) == 1
assert sum(1 for t in result if t == VIDEO_PAD) == 1
def test_text_only_no_placeholders():
"""Text-only models: no image tokens, function is a no-op."""
original = [1, 2, 3, 4, 5]
override = [1, 2, 3, 4, 5, 6, 7]
assert _collapse_image_placeholders(original, override) == override
@@ -0,0 +1,86 @@
"""Unit tests for eval scheduling logic - specifically the range check
that detects when ckpt_step jumps over eval interval boundaries."""
from prime_rl.orchestrator.eval_utils import compute_eval_ckpt_step
def test_exact_hit():
result = compute_eval_ckpt_step(ckpt_step=25, prev_ckpt_step=24, last_eval_step=0, interval=25)
assert result == 25
def test_jump_over_interval():
result = compute_eval_ckpt_step(ckpt_step=26, prev_ckpt_step=24, last_eval_step=0, interval=25)
assert result == 25
def test_no_interval_crossed():
result = compute_eval_ckpt_step(ckpt_step=23, prev_ckpt_step=22, last_eval_step=0, interval=25)
assert result is None
def test_base_model_eval_at_step_0():
result = compute_eval_ckpt_step(
ckpt_step=0, prev_ckpt_step=-1, last_eval_step=-1, interval=25, eval_base_model=True
)
assert result == 0
def test_base_model_eval_disabled():
result = compute_eval_ckpt_step(
ckpt_step=0, prev_ckpt_step=-1, last_eval_step=-1, interval=25, eval_base_model=False
)
assert result is None
def test_no_double_eval():
result = compute_eval_ckpt_step(ckpt_step=25, prev_ckpt_step=24, last_eval_step=25, interval=25)
assert result is None
def test_no_change_in_ckpt_step():
result = compute_eval_ckpt_step(ckpt_step=25, prev_ckpt_step=25, last_eval_step=0, interval=25)
assert result is None
def test_multiple_intervals_crossed():
result = compute_eval_ckpt_step(ckpt_step=76, prev_ckpt_step=24, last_eval_step=0, interval=25)
assert result == 75
def test_second_interval():
result = compute_eval_ckpt_step(ckpt_step=50, prev_ckpt_step=49, last_eval_step=25, interval=25)
assert result == 50
def test_jump_across_second_interval():
result = compute_eval_ckpt_step(ckpt_step=51, prev_ckpt_step=48, last_eval_step=25, interval=25)
assert result == 50
def test_production_scenario_step25_skipped():
"""Reproduces the bug from run c14miuyha2yhxkw1z3eqgyub."""
result = compute_eval_ckpt_step(ckpt_step=26, prev_ckpt_step=24, last_eval_step=0, interval=25)
assert result == 25
def test_production_scenario_step50_exact():
result = compute_eval_ckpt_step(ckpt_step=50, prev_ckpt_step=49, last_eval_step=26, interval=25)
assert result == 50
def test_simulate_full_run():
ckpt_steps = [0, 0, 3, 5, 10, 15, 20, 24, 26, 30, 35, 40, 48, 51, 60, 70, 74, 76]
interval = 25
last_eval_step = -1
prev_ckpt_step = -1
eval_triggered_at = []
for ckpt_step in ckpt_steps:
result = compute_eval_ckpt_step(ckpt_step, prev_ckpt_step, last_eval_step, interval)
if result is not None:
eval_triggered_at.append(result)
last_eval_step = ckpt_step
prev_ckpt_step = ckpt_step
assert eval_triggered_at == [0, 25, 50, 75]
Generated
+2 -2
View File
@@ -2405,7 +2405,7 @@ requires-dist = [
{ name = "torchtitan", git = "https://github.com/pytorch/torchtitan?rev=a1fdd7e" },
{ name = "transformers", git = "https://github.com/huggingface/transformers.git?rev=609e3d5" },
{ name = "uvloop", specifier = ">=0.21.0" },
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=3f555af" },
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=b35d0c7" },
{ name = "vllm", url = "https://vllm-wheels.s3.us-west-2.amazonaws.com/7a06e5b05b170d7da31845866da0a99fc65253a1/vllm-0.16.0rc3-cp38-abi3-manylinux_2_31_x86_64.whl" },
{ name = "wandb", specifier = ">=0.24.2" },
]
@@ -3760,7 +3760,7 @@ wheels = [
[[package]]
name = "verifiers"
version = "0.1.11.dev0"
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=3f555af#3f555af3674a22ffbfec0cafade25bec51bf517f" }
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=b35d0c7#b35d0c7e464d67ea8cc8fccaaec0903cd5fd7b32" }
dependencies = [
{ name = "anthropic" },
{ name = "datasets" },