Compare commits

...
Author SHA1 Message Date
16f5c7222b feat: make step numbers 1-indexed (policy versions stay 0-indexed) (#2896)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: 1-index step counters (policy versions stay 0-indexed)

The first trainer/orchestrator step is now step 1 (was step 0). Policy
versions remain 0-indexed, with v0 the base model. Training step x consumes
batch x and produces policy version x; orchestrator step x samples that batch
from policy v(x-1).

Checkpoints/broadcasts now follow a completed-step convention: the trainer
writes the broadcast + checkpoint at the END of each step's iteration (model
= the version just produced), the loop breaks on step == max_steps, and a
checkpoint step_S means "step S finished". Resuming from step_S continues at
step S+1 (orchestrator, trainer, and per-run progress all advance one step on
load). broadcasts/step_S holds policy vS, so the watcher derives the policy
version directly from the directory label; the broadcast label is
mm.progress[idx].step - 1 because pack() has already advanced progress.

This is a pure relabeling: the number of steps, LR schedule, data, and
off-policy/async-barrier behavior are unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: drop CHANGELOG entry for 1-indexed steps (not a config-field change)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix: align multi-run checkpoint step label with 1-indexed convention

MultiCheckpointManager.save derived its step from mm.progress[idx].step, but
pack() has already advanced that to the next step by the end-of-loop save
point — the same off-by-one the broadcast paths needed. It mislabeled the ckpt
dir step_{S+1} (vs the orchestrator's step_S), looked for the nonexistent
broadcasts/step_{S+1} when copying weights into the ckpt, and gated _should_save
on the wrong interval boundary. Subtract 1 to use the step just finished.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: fix misleading checkpoint comment in RL trainer loop

The "skip it here / written after the loop" note applied only to the single-run
branch; move it onto that branch and clarify the multi-run branch has no
after-loop final save.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs: trim redundant async-pipeline sentence in algorithms.md

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix: keep orchestrator resume step coordinated under ckpt.skip_progress

The resume increment ran on whatever progress.step held after load, but with
ckpt.skip_progress the orchestrator's CheckpointManager doesn't restore the
counter, so `+= 1` bumped the default (→ 2) while policy.version came from
resume_step — desyncing rollouts/checkpoints/dispatch-gate from the trainer and
mm.progress (both at resume_step + 1). Derive the step from resume_step so
skip_progress only resets the totals and the step stays coordinated.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 10:06:58 -07:00
5c0a6dbdba chore(ci): drop uv extras that aren't required from CPU unit tests to fix disk exhaustion (#2940)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore(ci): drop --all-extras from CPU unit tests to fix disk exhaustion

The CPU unit-test job ran `uv sync --all-extras --locked`, pulling the
entire dependency universe (envs, flash-attn-3, disagg, quack, gpt-oss,
modelexpress) just to run `pytest tests/unit -m "not gpu"`. That ~2-3GB
of GPU kernels and env deps (spacy, rdkit, chromadb, opencv, onnxruntime,
...) overflows the runner's root disk — the last run died extracting
triton with "No space left on device (os error 28)".

No `tests/unit` test imports any of those extras: they only use base deps
(torch, transformers, vllm, verifiers.v1) plus dev (pytest). The one test
touching flash_attn skips gracefully when it's absent. Install base + dev
only.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* clean up comment

* fix(ci): install flash-attn extra for CPU unit tests

Dropping --all-extras entirely broke test collection: `ring_flash_attn`
(a base dep) hard-imports `flash_attn` at module load, and `flash_attn`
is provided only by the flash-attn extra. 12 model/train tests failed to
collect with `ModuleNotFoundError: No module named 'flash_attn'`.

Add back just the flash-attn extra (a prebuilt wheel on x86_64, no build).
The disk fix holds — we still skip envs/flash-attn-3/disagg/quack/etc.,
the ~2-3GB no unit test imports.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(ci): add envs extra for CPU unit tests config loading

test_load_configs loads every config TOML; configs referencing a v1
taskset make verifiers.v1.loaders import the taskset package by name at
runtime (scaleswe_v1, math500_v1, aime24_v1, ...), which ships via the
envs extra. Static import analysis missed this, so the prior commit's
base+flash-attn install failed 15 config-loading tests.

The run proved the disk fix and the extras audit: 454 tests passed with
only flash-attn installed, and the sole failures were envs tasksets. So
install flash-attn + envs and skip the GPU-only extras (flash-attn-3,
disagg, quack, gpt-oss, modelexpress, flash-attn-cute) no unit test uses.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* clean up comment

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 23:25:39 -07:00
dbe95b799a feat: optional per-node uv sync for multi-node RL (#2926)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: optional per-node uv sync for multi-node RL

Add a SlurmConfig.per_node_venv_sync flag (default False). When enabled,
the multi-node RL sbatch runs uv sync on every node via srun (one task per
node, blocking) instead of only the batch node.

This is needed when the venv is node-local (e.g. UV_PROJECT_ENVIRONMENT on
/tmp): a single batch-node sync would leave the other nodes without a venv.
The srun task re-sources .env so uv sees the node-local UV_PROJECT_ENVIRONMENT
/ UV_CACHE_DIR even if SLURM env propagation is disabled. With set -e, a failed
sync on any node aborts the job. Default keeps the original head-only behavior
for shared (NFS) venvs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat: rename per_node_venv_sync to shared_fs, fix .env sourcing, extend to all multi-node templates

- Rename SlurmConfig.per_node_venv_sync (default False) to SlurmConfig.shared_fs
  (default True) with inverted logic, as suggested in PR review
- Fix .env sourcing in srun command to not fail when .env is absent
  (|| true guard), matching the rest of the script
- Fix comment: re-sourcing .env is needed because unexported vars don't cross
  srun even with normal SLURM env propagation, not because propagation is disabled
- Extend shared_fs to multi_node_sft.sbatch.j2 and inference.sbatch.j2
  since the flag lives in shared.py config

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 18:30:46 -07:00
16 changed files with 191 additions and 145 deletions
+1 -1
View File
@@ -25,7 +25,7 @@ jobs:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --locked
run: uv sync --extra flash-attn --extra envs --locked
- name: Run tests
env:
USERNAME_CI: CI_RUNNER
+1 -1
View File
@@ -157,7 +157,7 @@ At step $n = 1, 2, 3, \dots$:
- **Trainer** produces policy $\pi_n$ with weights $\theta_n$ from rollouts $(x_n, y_n)$.
- **Inference** produces rollouts $(x_n, y_n)$ from policy $\pi_{\max(0,\,n-1)}$.
Step indices are 0-indexed so the gap holds at startup — inference is exactly one step behind the trainer.
Step indices are 1-indexed; policy versions are 0-indexed, with $\pi_0$ the base model. At step 1 inference samples from $\pi_0$.
## Loss
+1 -1
View File
@@ -226,7 +226,7 @@ uv run rl @ rl.toml --ckpt.interval 25 --ckpt.keep-interval 100 # …plus perma
Re-run the same launch command and pass `--ckpt.resume-step <N>` (or `-1` for "latest"). Make sure `--max-steps` is at least the target final step, not the remaining delta:
```bash
# First run: steps 0–10
# First run: steps 1–10
uv run rl @ rl.toml --max-steps 10 --ckpt
# Resume: continue to step 20
@@ -58,6 +58,9 @@ class SlurmConfig(BaseConfig):
cleanup_grace_period: int = Field(3600, ge=0)
"""Seconds to wait before tearing down a multi-node RL job that hit a non-zero exit, letting in-flight checkpoints flush. Set to 0 to tear down immediately."""
shared_fs: bool = True
"""Whether the project filesystem (including the venv) is shared across nodes (e.g. NFS). When True, a single ``uv sync`` on the batch node suffices. Set to False when the venv is node-local (e.g. ``UV_PROJECT_ENVIRONMENT`` on ``/tmp``) so ``uv sync`` runs on every node via srun."""
@property
def template_vars(self) -> dict:
"""Common template variables for all SLURM templates."""
@@ -71,6 +74,7 @@ class SlurmConfig(BaseConfig):
"time": self.time,
"pre_run_command": self.pre_run_command,
"cleanup_grace_period": self.cleanup_grace_period,
"shared_fs": self.shared_fs,
}
@model_validator(mode="after")
+27 -23
View File
@@ -309,17 +309,21 @@ class Orchestrator:
if self.resume_step is not None and self.ckpt_manager is not None:
self.ckpt_manager.load(self.progress, step=self.resume_step)
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
# trainer even when ``ckpt.skip_progress`` left the counter unrestored.
self.progress.step = self.resume_step + 1
get_logger().info(f"Resuming orchestrator from checkpoint step {self.resume_step}")
check_exists = config.weight_broadcast.type != "nccl"
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else None
weights_path = get_weight_dir(
config.output_dir, self.progress.step, check_exists=check_exists, wait_timeout=wait_timeout
config.output_dir, self.resume_step, check_exists=check_exists, wait_timeout=wait_timeout
)
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=self.progress.step)
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=self.resume_step)
if self.lora_name is not None:
self.policy_inference.update_model_name(self.lora_name)
self.policy.model_name = self.lora_name
self.policy.version = self.progress.step
self.policy.version = self.resume_step
else:
get_logger().info("Training from scratch")
@@ -365,7 +369,7 @@ class Orchestrator:
inference=self.policy_inference,
observers=[self.dispatcher, self],
lora_name=self.lora_name,
ckpt_step=self.progress.step,
ckpt_step=self.policy.version,
)
# Single periodic logger for the whole pipeline. It's the only
# consumer of ``dispatcher.metrics.drained()`` (which clears on read)
@@ -411,11 +415,11 @@ class Orchestrator:
asyncio.create_task(self.watcher.start(), name="watcher"),
]
# Default step-0 base-model eval — fires before any train rollouts
# unless ``eval.skip_first_step=True`` (or this is a resume)
# Base-model eval (policy v0) — fires before any train rollouts, logged at the first
# step, unless ``eval.skip_first_step=True`` (or this is a resume)
self.maybe_trigger_eval(self.progress.step)
# Anchor step-time clock so step 0 measures startup → first batch
# Anchor step-time clock so the first step measures startup → first batch
self.last_batch_at = time.perf_counter()
# ``clean_exit`` stays False if ``main_loop`` raises (signal-driven
@@ -432,7 +436,11 @@ class Orchestrator:
else:
get_logger().warning(f"Orchestrator interrupted after {elapsed} — forcing cleanup (not a clean exit)")
self.monitor.save_final_summary()
if self.ckpt_manager is not None:
# ``progress.step`` points at the next (unshipped) step; the last finished step is
# ``progress.step - 1``. Checkpoint it as ``step_{progress.step - 1}`` (no-op before the
# first ship).
if self.ckpt_manager is not None and self.progress.step > 1:
self.progress.step -= 1
get_logger().info("Writing final checkpoint")
self.ckpt_manager.save(self.progress, step=self.progress.step)
await self.stop()
@@ -485,9 +493,7 @@ class Orchestrator:
step_time = (now - self.last_batch_at) if self.last_batch_at is not None else 0.0
self.last_batch_at = now
save_ckpt_time = await self.maybe_save_ckpt(step)
if config.max_steps is not None and step >= config.max_steps:
if config.max_steps is not None and step > config.max_steps:
self.draining = True
self.dispatcher.disable_train_scheduling()
n_cancelled = await self.dispatcher.cancel_inflight_train_rollouts()
@@ -528,6 +534,8 @@ class Orchestrator:
await self.sender.send(TrainingBatch(examples=batch.samples, step=step))
self.progress.step += 1
self.update_dispatch_gate()
# Checkpoint the step we just shipped (resume point: continue at step + 1).
save_ckpt_time = await self.maybe_save_ckpt(step)
trim_process_memory()
# Rollout metrics over the {agg,<env>} × {all,effective} matrix. ``batch.rollouts`` is the
@@ -770,19 +778,13 @@ class Orchestrator:
)
async def maybe_save_ckpt(self, step: int) -> float:
"""Save the checkpoint if we're at an interval boundary. Returns
"""Checkpoint the step just shipped if it's an interval boundary. Returns
elapsed time (0.0 when no save happened)."""
if self.ckpt_manager is None or self.config.ckpt is None or not self.config.ckpt.interval:
return 0.0
if step <= 0:
return 0.0
# Skip only the drain-entry step (step == max_steps, which never ships):
# it would double-save with the final checkpoint in ``start()`` (also at
# progress.step == max_steps). The last *shipped* step (max_steps - 1) is
# NOT skipped — the trainer saves there (its is_last_step is max_steps),
# so the orchestrator must too or resume from that interval ckpt breaks.
near_end = self.config.max_steps is not None and step >= self.config.max_steps
if near_end:
# The final step's checkpoint is written once in ``start()``'s teardown; skip it here so
# we don't double-save. This mirrors the trainer (its is_last_step skips the in-loop save).
if self.config.max_steps is not None and step >= self.config.max_steps:
return 0.0
if step % self.config.ckpt.interval != 0:
return 0.0
@@ -795,8 +797,10 @@ class Orchestrator:
"""Pause/resume the dispatcher based on how far the in-flight batch runs
ahead of ``policy.version``. ``progress.step`` is always the batch being
collected — advanced right after shipping — so both call sites (ship time
here, policy update in ``on_new_version``) share one lead formula."""
lead = self.progress.step - self.policy.version
here, policy update in ``on_new_version``) share one lead formula. Steps
are 1-indexed while policy versions stay 0-indexed, so the shipped-batch
count is ``progress.step - 1``."""
lead = (self.progress.step - 1) - self.policy.version
gate = self.dispatcher.dispatch_allowed
was_set = gate.is_set()
if lead > TARGET_LAG:
+2 -2
View File
@@ -27,9 +27,9 @@ class Policy:
@dataclass
class Progress:
"""Persistent counters; ``step`` is the trainer-aligned step."""
"""Persistent counters; ``step`` is the trainer-aligned step (1-indexed)."""
step: int = 0
step: int = 1
total_tokens: int = 0
total_samples: int = 0
total_problems: int = 0
@@ -61,7 +61,17 @@ ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
{% if not shared_fs %}
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
# build the batch node, so srun runs it on every node (one task each) and blocks until
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
# inside the task because unexported vars in .env don't cross srun even with normal
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras'
{% else %}
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
uv sync --all-extras
{% endif %}
# Print inference URLs
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
@@ -144,7 +144,17 @@ echo "MASTER_PORT=${MASTER_PORT}"
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
{% if not shared_fs %}
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
# build the batch node, so srun runs it on every node (one task each) and blocks until
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
# inside the task because unexported vars in .env don't cross srun even with normal
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras'
{% else %}
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
uv sync --all-extras
{% endif %}
{% if pre_run_command %}
# Pre-run command
@@ -48,9 +48,17 @@ echo "MASTER_PORT=${MASTER_PORT}"
# Install environment
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
source $PROJECT_DIR/.venv/bin/activate
# Install environment as local package
{% if not shared_fs %}
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
# build the batch node, so srun runs it on every node (one task each) and blocks until
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
# inside the task because unexported vars in .env don't cross srun even with normal
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras'
{% else %}
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
cd $PROJECT_DIR && uv sync --all-extras
{% endif %}
{% if pre_run_command %}
+3 -1
View File
@@ -116,7 +116,9 @@ class MultiCheckpointManager:
scheduler: "MultiLoRAScheduler",
) -> None:
for idx in self.multi_run_manager.used_idxs:
step = self.multi_run_manager.progress[idx].step
# pack() already advanced progress to the next step, so the step just finished
# (and its broadcasts/step_{step} weights) is progress - 1.
step = self.multi_run_manager.progress[idx].step - 1
if not self._should_save(idx, step):
continue
@@ -68,9 +68,11 @@ class FileSystemWeightBroadcast(WeightBroadcast):
# TODO: Broadcast ready to update in sync, then we dont need to gather on not ready
if self.world.is_master:
try:
# pack() already advanced progress to the next step, so the model we just
# trained — policy v(step-1) — broadcasts to broadcasts/step_{step-1}.
save_dir = get_step_path(
get_broadcast_dir(self.multi_run_manager.get_run_dir(idx)),
self.multi_run_manager.progress[idx].step,
self.multi_run_manager.progress[idx].step - 1,
)
save_dir.mkdir(parents=True, exist_ok=True)
@@ -112,6 +114,6 @@ class FileSystemWeightBroadcast(WeightBroadcast):
for idx in self.multi_run_manager.used_idxs:
maybe_clean(
get_broadcast_dir(self.multi_run_manager.get_run_dir(idx)),
self.multi_run_manager.progress[idx].step,
self.multi_run_manager.progress[idx].step - 1,
interval_to_keep,
)
+3 -1
View File
@@ -224,9 +224,11 @@ class NCCLWeightBroadcast(WeightBroadcast):
if not self.multi_run_manager.ready_to_update[idx]:
continue
try:
# pack() already advanced progress to the next step, so the model we just
# trained — policy v(step-1) — broadcasts to broadcasts/step_{step-1}.
save_dir = get_step_path(
get_broadcast_dir(self.multi_run_manager.get_run_dir(idx)),
self.multi_run_manager.progress[idx].step,
self.multi_run_manager.progress[idx].step - 1,
)
notified_runs.append((idx, save_dir))
except FileNotFoundError:
+69 -71
View File
@@ -222,6 +222,8 @@ def train(config: TrainerConfig):
progress = Progress()
if checkpoint_step is not None:
ckpt_manager.load(checkpoint_step, model, [optimizer], scheduler, progress)
# The checkpoint finished step ``checkpoint_step``; resume training at the next step.
progress.step += 1
logger.info(f"Resuming training from checkpoint step {checkpoint_step}")
logger.info(
@@ -248,7 +250,6 @@ def train(config: TrainerConfig):
gc_handler = GarbageCollection(config.gc.interval) if config.gc else None
logger.info(f"Starting training loop (max_steps={config.max_steps or 'infinite'})")
is_first_step = True
maybe_record_function = nullcontext
if config.trace_path:
logger.info(f"Tracing to {config.trace_path}")
@@ -261,73 +262,6 @@ def train(config: TrainerConfig):
gc_handler.run(progress.step)
is_last_step = config.max_steps is not None and progress.step == config.max_steps
# Broadcast weights every step except:
# - step 0: nothing has changed yet, the orchestrator has the base model.
# - the final NCCL broadcast: with a 1-step async barrier the orchestrator's last step
# uses the trainer's penultimate ckpt, so the trainer's last broadcast has no receiver
# (the inference NCCL group has been torn down). Filesystem broadcast still writes the
# final step so we can resume from the broadcast directory.
if weight_broadcast is None:
broadcast_weights_time = 0
else:
nccl_broadcast_unused = (
config.weight_broadcast.type == "nccl"
and config.max_steps is not None
and progress.step >= config.max_steps - 1
)
if progress.step > 0 and not nccl_broadcast_unused:
broadcast_weights_start_time = time.perf_counter()
weight_broadcast.broadcast_weights(model, step=progress.step)
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
# Clean up old broadcast directories (unless at ckpt interval if using filesystem weight broadcast)
if config.weight_broadcast.type == "filesystem":
interval_to_keep = config.ckpt and config.ckpt.interval
weight_broadcast.maybe_clean(interval_to_keep)
else:
broadcast_weights_time = 0
# Usually the broadcast will set this. If broadcast is skipped, we need to reset this here.
for idx in multi_run_manager.used_idxs:
multi_run_manager.ready_to_update[idx] = False
if config.max_concurrent_runs > 1:
# Multi-run: Save per-run checkpoints using each run's orchestrator config.
# Trainer-level ckpt config can be set by the combined rl entrypoint,
# but MultiCheckpointManager has a different save signature.
save_ckpt_start_time = time.perf_counter()
ckpt_manager.save(optimizer, scheduler)
save_ckpt_time = time.perf_counter() - save_ckpt_start_time
ckpt_manager.maybe_clean()
elif (
ckpt_manager is not None
and (config.ckpt and config.ckpt.interval)
and not (is_first_step or is_last_step)
and progress.step % config.ckpt.interval == 0
):
save_ckpt_time = 0
if not config.ckpt.weights_only:
# Single-run: Save full checkpoint
logger.info(f"Saving checkpoint at step {progress.step}")
save_ckpt_start_time = time.perf_counter()
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
ckpt_manager.maybe_clean()
# Save weight checkpoint
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)
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
weight_ckpt_manager.maybe_clean()
else:
save_ckpt_time = 0
# Break if we have reached the maximum number of steps
if config.max_steps is not None and progress.step >= config.max_steps:
break
logger.debug(f"Starting training step {progress.step}")
step_start_time = time.perf_counter()
@@ -620,6 +554,69 @@ def train(config: TrainerConfig):
current_lr = optimizer.get_current_lr()
forward_backward_time = time.perf_counter() - forward_backward_start_time
# Broadcast the model just produced (policy v{progress.step}) so the orchestrator can
# sample its next step from it. Skip the final NCCL broadcasts: with a 1-step async barrier
# the orchestrator's last step uses the trainer's penultimate ckpt, so they have no receiver
# (the inference NCCL group is torn down). Filesystem broadcast still writes them so we can
# resume from the broadcast directory.
if weight_broadcast is None:
broadcast_weights_time = 0
else:
nccl_broadcast_unused = (
config.weight_broadcast.type == "nccl"
and config.max_steps is not None
and progress.step >= config.max_steps - 1
)
if not nccl_broadcast_unused:
broadcast_weights_start_time = time.perf_counter()
weight_broadcast.broadcast_weights(model, step=progress.step)
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
# Clean up old broadcast directories (unless at ckpt interval if using filesystem weight broadcast)
if config.weight_broadcast.type == "filesystem":
interval_to_keep = config.ckpt and config.ckpt.interval
weight_broadcast.maybe_clean(interval_to_keep)
else:
broadcast_weights_time = 0
# Usually the broadcast will set this. If broadcast is skipped, we need to reset this here.
for idx in multi_run_manager.used_idxs:
multi_run_manager.ready_to_update[idx] = False
# Checkpoint the step we just finished (model = policy v{progress.step}).
if config.max_concurrent_runs > 1:
# Multi-run: save per-run checkpoints every step (interval-gated inside
# MultiCheckpointManager); there is no after-loop final save for multi-run.
save_ckpt_start_time = time.perf_counter()
ckpt_manager.save(optimizer, scheduler)
save_ckpt_time = time.perf_counter() - save_ckpt_start_time
ckpt_manager.maybe_clean()
elif (
ckpt_manager is not None
and (config.ckpt and config.ckpt.interval)
# the last step is written once after the loop (final ckpt), so skip it here
and not is_last_step
and progress.step % config.ckpt.interval == 0
):
save_ckpt_time = 0
if not config.ckpt.weights_only:
# Single-run: Save full checkpoint
logger.info(f"Saving checkpoint at step {progress.step}")
save_ckpt_start_time = time.perf_counter()
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
ckpt_manager.maybe_clean()
# Save weight checkpoint
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)
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
weight_ckpt_manager.maybe_clean()
else:
save_ckpt_time = 0
# Optionally, dump memory snapshot
if memory_profiler is not None:
memory_profiler.step()
@@ -737,13 +734,14 @@ def train(config: TrainerConfig):
run_stats=run_stats,
)
progress.step += 1
is_first_step = False
# Send heartbeat if configured
if heart is not None:
heart.beat()
if is_last_step:
break
progress.step += 1
if config.trace_path:
prof.__exit__(None, None, None)
config.trace_path.mkdir(parents=True, exist_ok=True)
+5 -4
View File
@@ -20,7 +20,7 @@ if TYPE_CHECKING:
@dataclass
class Progress:
step: int = 0
step: int = 1
total_tokens: int = 0
total_samples: int = 0
@@ -278,16 +278,17 @@ class MultiRunManager:
# Set progress based on resume_step config (match orchestrator behavior)
self.progress[new_id] = Progress()
# ``step_S`` means step S finished; resume continues at S+1.
if config.ckpt is None or config.ckpt.resume_step is None:
self.progress[new_id].step = 0
self.progress[new_id].step = 1
elif config.ckpt.resume_step == -1:
ckpt_dir = self.get_run_dir(new_id) / "checkpoints"
# In multi-run, the trainer writes STABLE after saving LoRA weights to the run's checkpoint dir.
# In single-run, only the orchestrator writes checkpoints here (trainer has its own dir), so no STABLE exists.
steps = get_stable_ckpt_steps(ckpt_dir) if self.max_runs > 1 else get_all_ckpt_steps(ckpt_dir)
self.progress[new_id].step = max(steps) if steps else 0
self.progress[new_id].step = max(steps) + 1 if steps else 1
else:
self.progress[new_id].step = config.ckpt.resume_step
self.progress[new_id].step = config.ckpt.resume_step + 1
# Store the parsed config
self.config[new_id] = config
+36 -32
View File
@@ -215,6 +215,9 @@ def train(config: SFTConfig):
dataloader=dataloader if not config.ckpt.skip_dataloader else None,
)
logger.info(f"Resuming training from checkpoint step {checkpoint_step}")
# The checkpoint finished step ``checkpoint_step``; resume training at the next step.
if not config.ckpt.skip_progress:
progress.step += 1
# This redundant setup is necessary because loading the optimizer's state has side effects on the scheduler state dict
if config.ckpt.skip_scheduler:
scheduler = setup_scheduler(optimizer, config.scheduler, scheduler_steps, config.optim.lr)
@@ -347,37 +350,6 @@ def train(config: SFTConfig):
gc_handler.run(progress.step)
is_last_step = config.max_steps is not None and progress.step == config.max_steps
if (
ckpt_manager is not None
and (config.ckpt and config.ckpt.interval)
and not (is_first_step or is_last_step)
and progress.step % config.ckpt.interval == 0
):
save_ckpt_time = 0
if not config.ckpt.weights_only:
# Save full checkpoint
logger.info(f"Saving checkpoint at step {progress.step}")
save_ckpt_start_time = time.perf_counter()
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
ckpt_manager.maybe_clean()
# Save weight checkpoint
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)
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
weight_ckpt_manager.maybe_clean()
else:
save_ckpt_time = 0
# Break if we have reached the maximum number of steps
if config.max_steps is not None and progress.step >= config.max_steps:
break
memory_profiler = (
MemoryProfiler(progress.step, config.memory_profiler_path) if config.memory_profiler_path else None
)
@@ -482,6 +454,35 @@ def train(config: SFTConfig):
current_lr = optimizer.param_groups[0]["lr"]
scheduler.step()
# Checkpoint the step we just finished. The last step's checkpoint is written once after
# the loop, so skip it here to avoid a double-save.
if (
ckpt_manager is not None
and (config.ckpt and config.ckpt.interval)
and not is_last_step
and progress.step % config.ckpt.interval == 0
):
save_ckpt_time = 0
if not config.ckpt.weights_only:
# Save full checkpoint
logger.info(f"Saving checkpoint at step {progress.step}")
save_ckpt_start_time = time.perf_counter()
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
ckpt_manager.maybe_clean()
# Save weight checkpoint
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)
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
weight_ckpt_manager.maybe_clean()
else:
save_ckpt_time = 0
# Optionally, dump memory snapshot
if memory_profiler is not None:
memory_profiler.step()
@@ -585,12 +586,15 @@ def train(config: SFTConfig):
monitor.log({**moe_log_metrics, "step": progress.step}, step=progress.step)
is_first_step = False
progress.step += 1
# Send heartbeat if configured
if heart is not None:
heart.beat()
if is_last_step:
break
progress.step += 1
if config.trace_path:
prof.__exit__(None, None, None)
config.trace_path.mkdir(parents=True, exist_ok=True)
+5 -4
View File
@@ -97,19 +97,20 @@ def test_packer_progress_updates_once_per_run(tmp_path: Path, monkeypatch: pytes
start_step=0,
)
packer.buffers[run_idx].append((make_training_sample(), 0))
packer.buffers[run_idx].append((make_training_sample(), 0))
# Steps are 1-indexed: a fresh run starts at step 1, so the first batch's samples carry step 1.
packer.buffers[run_idx].append((make_training_sample(), 1))
packer.buffers[run_idx].append((make_training_sample(), 1))
packer.pack()
progress = manager.progress[run_idx]
assert progress.total_samples == 2
assert progress.total_tokens == 4
assert progress.step == 1
assert progress.step == 2
sender = sender_holder["sender"]
assert len(sender.sent) == 1
assert len(sender.sent[0][0]) == 1
micro_batch = sender.sent[0][0][0]
assert micro_batch.run_id == "run_test123"
assert micro_batch.run_step == 0
assert micro_batch.run_step == 1