Compare commits

...
Author SHA1 Message Date
6a360c3029 feat(trainer): add runtime gate/up and qkv fusions (#3451)
## Summary

Adds runtime parameter fusions, on by default: `model.fusions` packs
parameters that are always computed together into one tensor, turning
several GEMMs into one. Fusions are runtime-only — checkpoints keep the
canonical parameter names and shapes, so a run can enable or disable one
at any point and still load its own checkpoints.

```toml
[trainer.model.fusions]
enabled = ["gate_up", "qkv"]   # default; [] disables
raise_on_fail = false          # default: a fusion no module supports logs a warning
shard_fused_on_dim1 = false    # default; experimental zero-copy checkpointing, see Notes
```

- **`gate_up`** — each gated MoE expert's `gate_proj` and `up_proj`
become one `[num_experts, 2 * intermediate_size, hidden_size]` weight.
The forward is a single grouped GEMM whose transpose and chunk are
views; there is no weight reshape.
- **`qkv`** — an attention layer's `q_proj`, `k_proj` and `v_proj` (and
their biases) become one `nn.Linear`. `FlashAttention.project_qkv` is
shared with `LagunaFlashAttention` so both support it.

## Review fixes and verification (2026-09-08)

Review found and fixed three previously unchecked checkpoint cases:

- **Exports and model-only resume:** DCP returns `{}` when no optimizers
are supplied. Both fusion optimizer-state translators now preserve that
empty dictionary instead of raising `KeyError: 'state'`.
- **AdamW resume with optimizer-state CPU offload:** packed parameters
restored their moments but lost scalar state, including AdamW's step
counter. The write-back now restores scalar tensors and non-tensor state
as well as packed moments.
- **Full CPU offload checkpoint save:** splitting packed CPU optimizer
tensors requires CPU collectives. Both training entrypoints now enable
Gloo alongside NCCL when full offload is enabled.

Verified on H200s through Slurm job **232**:

- The complete existing unit suite and Ruff checks passed.
- All **32 distributed checkpoint combinations** passed: AdamW/Muon,
fused/unfused save and load, default/dimension-1 sharding, and
optimizer-state CPU offload on/off. Canonical weights, optimizer state,
and the next update with identical gradients were bitwise exact.
- Full CPU offload completed model-only resume/save and optimizer
resume/save. All **311 model tensors** were exact after model-only
resume; **931 model/master/step tensors** were checked across optimizer
resume, with unchanged weights and correctly incremented counters.
- Expert outputs and matrix-weight gradients, and QKV projections
with/without bias, were exact. BF16 input-gradient relative differences
were about 0.29%; bias-reduction variation also occurred in repeated
unfused calculations.
- All **11 RL/SFT training, resume, and export checks** passed (6 SFT, 5
RL). BF16 and FP8 exports reload in HF, and direct DCP-to-FP8 matches
chained conversion byte-for-byte. RL completed 20 steps with final
reward **0.8362** and passed its mismatch-KL checks.

The dashboard browser checks cannot install OS dependencies on this
cluster because they require sudo. The prior A6000 benchmark CI job was
cancelled without executing any steps; its hardware-specific baseline
was not validated on H200. Blackwell-only MXFP8 was not exercised.

Verification artifacts: `/home/matej/prime-rl-verify/pr3451-20260908/`.
This review changes only the fusion helpers and RL/SFT distributed
initialization; it adds no tests or skill changes.

## Design

A fusion is a function that replaces some of a module's parameters with
one `PackedParameterSpec`, which owns the split sizes, the packing
dimension, and the canonical names it stands in for. Everything else
falls out of that description, so a new fusion adds no machinery:

- **Checkpoints** — state-dict hooks registered alongside the packing
swap the packed entry for its canonical entries on the way out and back
on the way in. The canonical entries are views of the packed storage
when the packing dimension is unsharded (`gate_up`: experts shard on dim
0, pack on dim 1); a DTensor sharded along the packing dimension (`qkv`:
FSDP shards dim 0) is unsharded by the split, so those entries are
replicated copies. Anything that loads into the state dict in place
therefore packs the loaded entries back explicitly
(`write_back_loaded_packed_parameters` after the HF weight load,
`write_back_loaded_packed_optimizer_state` /
`join_loaded_optimizer_state_for_runtime` on resume). DCP therefore
writes `gate_proj`/`up_proj` and `q_proj`/`k_proj`/`v_proj` and never
sees the packed layout. The optimizer has no equivalent hook (its
`state_dict()` hooks fire while state is still keyed by integer param
ids, before DCP maps them to FQNs), so the same translation is applied
explicitly around `get_state_dict` in `AppState`.
- **Muon** — `PackedParameterSpec.muon_matrix_partitions` yields the
split sizes when the packing is on the output dimension. Those go to
Dion's new `matrix_partitions` argument, which orthogonalizes each
logical matrix separately on the one physical parameter, with a
per-partition learning-rate adjustment. A packed parameter therefore
trains exactly as the parameters it replaces would — including
per-projection scaling for grouped-query attention — while keeping a
single momentum tensor. Uses the merged matrix-partition support in the
pinned `samsja/dion@99e5f7e` (samsja/dion#3).

Modules advertise fusions through `supported_fusions`; requesting one
that no module supports logs a warning, or fails at startup with
`raise_on_fail = true`. Fusions are skipped when LoRA is enabled, since
it targets the unfused projections.

## Performance

Qwen3-30B-A3B, 8×H200, EP=8, `seq_len=8192`, torch EP dispatch,
selective AC, compile, no offload. Mean throughput over steps 3–6:

| precision | unfused | fused | |
|---|---|---|---|
| BF16 | 37636 tok/s (MFU 13.3%) | 37352 tok/s (MFU 13.2%) | −0.8% |
| FP8 (`quantization.type=fp8` + `moe.compute.type=deepgemm_fp8`) |
30594 tok/s (MFU 10.8%) | 34062 tok/s (MFU 12.0%) | **+11.3%** |

BF16 is unchanged, as expected: the separate GEMMs already read the same
activation, so there is nothing to save. The gain is under FP8, where
each GEMM quantizes its activation independently — unfused casts the
same tensor 3× for q/k/v and 2× for gate/up, fused casts it once. Peak
memory is unchanged (101.8 → 102.0 GiB).

## Validation

Correctness, on GPU:

- Forward output and all weight gradients of the fused grouped experts
are **bitwise identical** to the unfused module; the packed q/k/v
projections are bitwise identical to the separate ones. Only the MoE
input gradient differs (max abs `1.5e-5` on a `2.4e-3` scale), by one
bf16 accumulation rounding from doing one `[T, 2I]` dgrad instead of two
`[T, I]`.
- Muon updates on a packed parameter are **bitwise identical** to
updating the parameters it replaces, over multiple steps, for both
fusions.
- All four fused/unfused optimizer checkpoint round trips are exact,
including the next optimizer update after each. For `gate_up` the
checkpoint entries alias the packed storage; for `qkv` under FSDP they
are replicated copies of the q/k/v weights and their optimizer state,
materialized transiently on every rank at load and checkpoint time (~1
GB bf16 weights + ~2 GB fp32 Muon momentum for Qwen3-30B-A3B).
`shard_fused_on_dim1 = true` (experimental, default off) shards fused
2-D parameters along dim 1 via FSDP2's `shard_placement_fn`, so the
split stays a local view: the q/k/v weight entries alias the packed
storage and `model.state_dict()` holds 0.1 MiB extra instead of 72 MiB
on the mini model (0 / 144 → 72 / 72 weight entries aliasing; biases
stay copies, having no second dimension). It is not a correctness fix on
its own — biases would still load as zero and the optimizer-offload
resume path replaces its state tensors after the template is built, so
the explicit write-back stays in place with the flag on or off.
Constraints: `hidden_size % dp_shard == 0` (FSDP2 raises otherwise) and
an extra chunk-cat per all-gather of dim-1 shards. #3486 measured the
placement alone and is closed in favour of this flag.
- DCP metadata for a fused EP=2 checkpoint contains 94 `gate_proj` and
94 `up_proj` entries and zero `gate_up_proj` entries.

End to end on SLURM (2 GPUs, EP=2, compiled, Muon, both fusions unless
noted):

| run | result |
|---|---|
| BF16 fake-data training + checkpoint save | ✅ |
| resume: fused ckpt → fused runtime | ✅ |
| resume: fused ckpt → **unfused** runtime | ✅ |
| resume: unfused ckpt → **fused** runtime | ✅ |
| optimizer-state CPU offload, save + resume | ✅ |
| DeepGEMM FP8 expert compute | ✅ |
| pretrained `mini-glm-moe` RL run with vLLM weight reload | ✅ mismatch
KL `0.0001` at both steps |

Plus `ruff format`/`ruff check`, and `pytest tests/unit/train/models
tests/unit/test_configs.py` (`215 passed, 3 skipped`), including a new
`tests/unit/train/models/test_fusions.py`.

## Notes

- `pyproject.toml` and `uv.lock` pin `samsja/dion@99e5f7e`, which
contains the merged matrix-partition support from samsja/dion#3.

## Verification on merged `main` (2026-09-04)

Branch merged with `main` (no conflicts) and re-verified on 8×H200 nodes
via SLURM. `ruff check`/`ruff format --check` clean; `pytest tests/unit
-m "not gpu"`: 536 passed, 1 skipped; `pytest tests/unit -m gpu`: 81
passed, 8 skipped.

**Numerics against an fp32 reference** (`samsja/mini-glm-moe`, single
GPU, no FSDP, 512 random tokens; reference is HF `Glm4MoeForCausalLM` in
fp32 eager). Whole-model outputs are not bitwise identical between fused
and unfused bf16 — the packed GEMMs take a different accumulation path —
but the fused model is exactly as close to fp32 as the unfused one:

| model (bf16) | logits mean abs diff vs fp32 | KL(fp32 ‖ model) | grad
rel. err vs fp32: q/k/v · experts gate/up · rest |
|---|---|---|---|
| unfused | 7.64e-3 | 3.97e-5 | 4.52e-2 · 4.96e-2 · 4.48e-2 |
| fused `qkv` | 7.64e-3 | 3.82e-5 | 4.14e-2 · 4.81e-2 · 4.12e-2 |
| fused `gate_up` | 7.22e-3 | 3.83e-5 | 4.52e-2 · 5.19e-2 · 4.51e-2 |
| fused both | 7.27e-3 | 3.88e-5 | 4.31e-2 · 4.87e-2 · 4.27e-2 |
| HF bf16 sdpa (noise floor) | 7.72e-3 | 4.48e-5 | 4.48e-2 · 5.19e-2 ·
4.46e-2 |

Fused vs unfused state dicts are bitwise identical after loading, and
each packed parameter equals the concatenation of the parameters it
replaces.

**Fake-data training matrix** (`mini-glm-moe`, 2 GPUs, EP=2, Muon,
compile + AC on, `ckpt.interval=5`, 10 steps), all runs complete without
errors:

| run | result |
|---|---|
| fused / unfused, optimizer offload on / off | ✅ losses agree to ≤ 5e-4
relative on every step |
| `shard_fused_on_dim1 = true`: load, resume (both offload paths), fused
↔ unfused resume, 10-step loss vs unfused | ✅ (verified with this code
before the flag existed; see #3486 for the measurements) |
| fused ckpt → fused resume, fused ckpt → unfused resume | ✅ post-resume
losses agree to ≤ 1e-3 relative |
| unfused ckpt → fused resume vs unfused ckpt → unfused resume | ✅ |
| the same three resumes with optimizer-state CPU offload | ✅ |
| DeepGEMM FP8 (`quantization.type=fp8`,
`moe.compute.type=deepgemm_fp8`), fused and unfused | ✅ |

(Resumed runs deliberately diverge from the un-interrupted run:
`FakeDataLoader` reseeds from a batch counter that restarts at 0, so a
resume replays the first batches. Fused and unfused resumes see
identical data and are compared against each other.)

**RL end to end** (`configs/ci/integration/reverse-text-moe/start.toml`,
custom impl, EP=2, 2 trainer GPUs + 1 vLLM GPU, 20 steps, filesystem
weight broadcast): fused `mismatch_kl/all/mean` 1.8e-4–2.2e-4 on every
step vs 1.9e-4–2.1e-4 unfused.

**Fix included in this branch.** Before `fix(trainer): load packed
parameters and their optimizer state explicitly`, the same runs showed
the `qkv` fusion training from zero attention weights: the HF weight
load wrote into the replicated q/k/v copies, every q/k/v tensor in a
fused checkpoint was exactly 0, the fused/unfused step-1 loss differed
by 20% reproducibly under both bf16 and FP8, and the RL run aborted with
no trainable rollouts. A fused resume also lost the Muon momentum of
every packed parameter (verified with lr=0: momentum after resume was
1.00× instead of 1.95× the saved value; both fusions with optimizer CPU
offload, `qkv` without). With the fix, loaded weights are bitwise
identical to the source and momentum is restored on both resume paths.
Full optimizer offload (`model.full_offload`) with fusions was not
exercised. MXFP8 expert compute needs Blackwell and could not be tested
on H200.

## Cluster verification with merged Dion (2026-09-05)

Pinned `samsja/dion@99e5f7e` (merged samsja/dion#3) and refreshed
`uv.lock`; its tree is identical to the prior fork pin. Synced with `uv
sync --all-extras --inexact`, then ran GPU verification through Slurm on
H200s:

- 10 prime-rl fusion/activation-checkpointing tests, 13 Dion single-GPU
tests, and 4 Dion distributed tests passed.
- All **16 distributed checkpoint combinations** passed: fused/unfused
save and load, default/dimension-1 sharding, and optimizer-state offload
on/off. Canonical weights, optimizer state, and the next Muon update
with identical supplied gradients were **bitwise exact**.
- **13 compiled EP=2 training/resume variants** completed on
`samsja/mini-glm-moe` (512-token fake batches): both fusion modes, all
four resume combinations, state offload, dimension-1 sharding, and
DeepGEMM FP8. Fused/unfused BF16 losses differed by at most **0.031%**
across the three initial steps.
- All **406 pretrained model tensors** were bitwise exact in the zero-LR
checkpoint and after its offloaded resume. All 13 variants saved
canonical model/optimizer projection names, with no packed `qkv_proj` or
`gate_up_proj` entries.
- The real **2-step RL run with vLLM weight reloads** completed with
mismatch KL **0.00019046 / 0.00019005**. Fake-data runs use random
inference logprobs, so their mismatch KL is not a trainer/inference
agreement metric.
- H200 module checks: gate/up outputs and matrix-weight gradients, plus
Q/K/V outputs with/without bias, were exact. BF16 MoE input-gradient
relative differences were ~0.29%. Bias reductions in an all-BF16 module
varied ~1.5%, also reproduced by repeating the unfused calculation
itself.

Slurm evidence: 147/148 (test suites), 149 (RL), 150/158 (checkpoint
equivalence), 153 (training matrix), 157 (saved checkpoint inspection).
Job 148's test suites passed before an overly strict ad-hoc BF16 bias
assertion stopped that script; the numerical diagnostic was resolved
separately. Full optimizer offload and Blackwell-only MXFP8 were not
exercised.

## CI collection fix (2026-09-05)

The `reverse_text` integration job failed before running any tests
because importing `prime_rl.utils.weights` first triggered a circular
import through the model registry and `fusions`. Import
`PreTrainedModelPrimeRL` inside `convert_state_dict_to_hf`, its only
use, so loading weight utilities no longer eagerly imports the model
registry.

Reproduced the failing import locally before the fix. After the fix,
standalone collection of `test_reverse_text.py` succeeds (6 tests), the
complete integration suite collects (38 tests), and all 6 fusion unit
tests pass. Ruff lint/format checks and `git diff --check` pass.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes core training paths (FSDP sharding, weight load, DCP optimizer
state, Muon) and defaults fusions on; incorrect packing/load logic would
corrupt weights or momentum on resume, though extensive
checkpoint/resume testing is described in the PR.
> 
> **Overview**
> Adds **runtime parameter fusions** (on by default via
`[trainer.model.fusions]`) that pack related weights into single tensors
so MoE **gate/up** and attention **q/k/v** run as one GEMM each, while
**checkpoints and exports still use canonical names** (`gate_proj`,
`q_proj`, etc.).
> 
> A new **`fusions` module** implements packing (`PackedParameterSpec`),
state-dict hooks, HF/DCP load **write-back** for packed weights, and
explicit **optimizer-state split/join** around distributed checkpoint
save/load (including CPU-offload resume). Optional
**`shard_fused_on_dim1`** wires FSDP2 **`shard_placement_fn`** for
experimental zero-copy fused weight/optimizer I/O.
> 
> **Attention and MoE layers** advertise fusions through
`supported_fusions`; forwards use **`project_qkv`** / a single grouped
**`gate_up`** GEMM when fused. Fusions are **skipped with LoRA**.
**Muon** gets **`matrix_partitions`** from packed params via an updated
**dion** pin. Docs and unit tests cover config and canonical state-dict
behavior.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
52e736c685485fdbca109c86721017ab8065f65d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 19:47:47 +02:00
samsjaandGitHub 04a61d3b75 fix: warm Muon all-to-all connections during optimizer initialization (#3490)
## Summary

Automatically establish the NCCL peer connections used by Dion's Muon
optimizer immediately after constructing Muon and before returning it to
the trainer.

The warm-up runs only for Muon. It covers the exact main optimizer
process group and, when expert parameters use expert parallelism, the
separate expert-shard process group. Single-rank and non-NCCL groups
remain no-ops; AdamW, SGD, and other optimizers are unchanged.

This is a required correctness workaround for a reproducible multi-node
GLM-4.5-Air first-step deadlock. The source now documents that optimizer
refactors must preserve the warm-up, its process groups, and its
placement between Muon construction and the first optimizer step.

## Failure signature

Pretrained GLM-4.5-Air training with Muon reproducibly stalled while
submitting the first optimizer all-to-all on two nodes. All 16 ranks
reached the collective, but only rank 0 enqueued it successfully; ranks
1–15 remained inside submission until the NCCL watchdog fired.

The clearest controlled failure was job 1182:

- Nodes `qpn01gpu009` and `qpn01gpu011`, 16 GPUs total.
- Pretrained eight-layer GLM-Air reproduction with CP4, EP8/automatic
expert mesh, BF16 compute, and optimizer-state offload.
- First Muon all-to-all was NCCL sequence 67 with 50,331,648 BF16
elements per rank.
- The watchdog fired after 182 seconds.
- Setting `NCCL_CUMEM_ENABLE=0` did not resolve it.

This was not a generic inability of the nodes to communicate: Adam
training and standalone all-reduce/all-to-all controls completed on the
same cluster. Fake-weight and reduced-model tests further isolated the
trigger to Muon's pretrained-model initialization state and first bulk
all-to-all.

## Implementation

`_warmup_muon_mesh` takes the `DeviceMesh`, resolves its single process
group, and performs a bulk BF16 list all-to-all matching Dion's
communication path, waits for completion, and synchronizes CUDA before
releasing its temporary buffers. A scalar collective is intentionally
not used because it may not initialize the same bulk-transfer peer
channels. Meshes with more than one dimension (the replicate-only world
mesh) have no single group and are skipped; Dion's Muon only accepts 1-D
meshes there anyway.

The ordering is part of the fix:

1. Construct the Dion Muon optimizer.
2. Warm Muon's main distributed NCCL group.
3. If expert parameters and EP are active, warm the independent
expert-shard NCCL group.
4. Return the optimizer only after both required warm-ups complete.

The temporary allocation is approximately 12 MiB per peer for send plus
receive buffers. No config flag is introduced because making this
optional would allow the known deadlock to recur.

Patch scope remains one optimizer source file. There are no
trainer-loop, dependency, precision, optimizer-offload, allocator, Dion,
or experiment-config changes.

## Validation

- Ruff lint/format and whitespace checks passed.
- Existing configuration tests passed: 70 passed, 67 deselected.
- Job 1183, reduced pretrained model with early connection warm-up: one
full step passed on all 16 ranks; 42.6 seconds, loss 15.4930, gradient
norm 49.0578, clean exit.
- Job 1184, full 46-layer pretrained GLM-4.5-Air with the earlier
pre-model-load placement: three fake-data steps passed with finite
losses and nonzero gradient norms.
- Job 1185, full 46-layer model with the final optimizer-construction
placement in this PR: three steps passed on all 16 ranks. Losses were
13.2325, 13.1564, and 13.3399; gradient norms were 27.9833, 27.8885, and
31.8815; clean exit.
- The research-prod Air ablations pin the backport of this
implementation. IPO-KL, IPO, DPPO, and IcePop have each subsequently
advanced beyond 400 Muon steps without recurrence of the initialization
deadlock.
- Review follow-up (`dfa07cd7e`): the warm-up now resolves the process
group from the mesh and no-ops on non-1-D meshes. Verified on 2 GPUs
with NCCL: the `dp_shard` path still completes the warm-up collectives,
and the 2-D replicate-only world mesh returns cleanly where the previous
no-arg `get_group()` call raised `RuntimeError`.

Both full-model validations used `qpn01gpu009/011`, 16 GPUs, CP4 + EP8,
optimizer-state offload, BF16 compute, and expandable CUDA allocator
segments. They used fake data with no evaluation or checkpoint overhead.

Job 1185 artifacts are retained at:

```text
/home/outputs/int4-debug/sft-air-full-muon-init-warmup-2n-009-011
```

## Confidence and limitations

Confidence is high that this initialization prevents the observed
first-all-to-all deadlock: the failure was reproducible without it, the
matching warm-up removed it in progressively more production-like tests,
and the final implementation has continued to work in four long-running
RL jobs.

The exact NCCL-native deadlock mechanism remains unproven. The warm-up
changes connection state, allocation history, and startup timing, so
this should be described as a targeted correctness workaround rather
than proof of a particular NCCL defect. Removing or moving it requires
reproducing the original multi-node pretrained GLM-Air Muon case, not
merely passing a standalone collective test.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes distributed initialization for Muon only, but incorrect group
selection or removal could reintroduce multi-node deadlocks or add
startup memory/time on every Muon run.
> 
> **Overview**
> Adds a **correctness workaround** for multi-node Muon training: NCCL
peer channels for bulk all-to-all are established **right after** Dion
`Muon` is built and **before** the first optimizer step, so
GLM-Air-style jobs avoid deadlocking on the initial Muon collective.
> 
> New helper `_warmup_muon_process_group` no-ops for single-rank or
non-NCCL groups; otherwise it runs an async **list** `all_to_all` on ~3
MiB BF16 buffers per rank (matching Dion’s bulk path), waits, and
synchronizes CUDA. Warm-up runs on the main **`dp_shard_cp`** (or world)
process group and, when expert MLP params use EP, separately on
**`dp_shard_mod_ep`**. AdamW, SGD, and other optimizers are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d0b707438f77780e4b5e0ed69237c08435ba3a41. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-07 11:20:40 -07:00
26b3131d27 fix(transports): make NCCL respect keep_in_fp32_for_weight_transfer (#3480)
The NCCL weight-broadcast transport hardcoded every tensor to
`bfloat16`, ignoring `keep_in_fp32_for_weight_transfer`. This PR makes
NCCL transport respect the fp32 overrides. This makes NCCL honor the
same declaration the other two transports already respect. Note: NIXL
does its own thing and does not use this shared helper, yet.

- Extracted `resolve_wire_dtype()` so the filesystem and NCCL paths
share one implementation.
- Lifted `NCCLBroadcaster._resolve_dtensors` to a module-level
`resolve_dtensors()`, since a method reachable only through a live
`PyNcclCommunicator` can't be unit tested.
- Added `tests/unit/utils/test_weights.py`, the flag's first test
coverage, parametrized over all six models that declare it.

Ran various experiments with small models to see if this affected KL mismatch in any way, but results were inconclusive. See commit https://github.com/PrimeIntellect-ai/prime-rl/pull/3480/changes/4b152bf3fa551ff5a1fc1752036262d14520c343 for example experiment configs.


---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 16:57:19 -04:00
samsjaandGitHub ef9dea1781 chore(inference): introduce admin plane abstraction (#3472)
## Summary

- consolidate the inference control path into a single `AdminPlane`
abstraction over its worker HTTP clients
- make the static plane own readiness, NCCL setup, weight updates, and
lifecycle management
- expose one typed `update_weights` operation; each receiver identifies
its transport explicitly
- route filesystem, NCCL, and NIXL receivers through the admin plane
instead of passing raw HTTP client lists
- remove the separate admin-plane protocol, unused factory argument, and
pass-through weight-update wrapper

`InferenceClient` remains the data-plane client for generation and
scoring, while `AdminPlane` coordinates control operations against one
or more inference workers. Alternate backends can specialize a transport
operation without adding backend flags to weight receivers.

## Validation

- `uv run ruff check src/prime_rl/orchestrator/clients.py
src/prime_rl/orchestrator/orchestrator.py src/prime_rl/evals/evals.py
src/prime_rl/transports/weights tests/unit/orchestrator/test_clients.py`
- `uv run python -m compileall -q src/prime_rl/orchestrator/clients.py
src/prime_rl/orchestrator/orchestrator.py src/prime_rl/evals/evals.py
src/prime_rl/transports/weights`
- `uv run pytest -q tests/unit/orchestrator/test_clients.py` (10 passed)

The transport test module could not be collected on this host because
its optional CUDA import chain requires `flash_attn`.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Refactors the weight-broadcast control path (pause/resume,
NCCL/NIXL/filesystem updates) used during training; behavior should be
equivalent but mistakes here can strand engines paused or desync policy
versions.
> 
> **Overview**
> Renames **`AdminClients`** to **`AdminPlane`** and makes it the single
control-plane entry point for inference workers (readiness, NCCL init,
weight updates, LoRA load, teardown).
> 
> **NCCL setup** and **weight updates** move from module-level helpers
into **`AdminPlane.initialize_nccl`** and
**`AdminPlane.update_weights`**, with callers passing an explicit
**`transport`** (`filesystem` | `nccl` | `nixl`). Orchestrator, evals,
and all **`WeightReceiver`** implementations now take an
**`AdminPlane`** instead of raw **`httpx`** client lists;
**`load_lora_adapter`** and **`init_nixl_broadcast`** follow the same
pattern.
> 
> Unit tests are updated and **`test_admin_plane_initializes_nccl`** is
added.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
65043370b7a9c857e6e3302f665b0b8c389043f1. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-03 16:36:16 -07:00
Konstantin DunasandGitHub 6c7b1ef375 feat: visualize compaction attempts and exclude rejected branches (#3478) 2026-09-03 22:09:41 +02:00
samsjaandGitHub 608c75c0af feat(dashboard): add timed terminal trace replay (#3456)
## Summary


https://github.com/user-attachments/assets/cd2caaa1-d700-40e5-8465-911812313f15

- add a terminal-style Replay view for rollout traces using recorded
model-call and tool timing
- add play/pause, seek, restart, 0.5x-32x speed controls, and an
inference-skipping tool-timing mode
- expose recorded model thinking with a toggle and T shortcut
- support Top/Live transcript navigation with Home/End shortcuts
- document replay timing semantics and extend dashboard smoke coverage

## Rebase notes

Rebased onto main (past #3444 overlays, #3465 chunked trace streams,
#3470 task/judge evidence, and #3455 semantic traces). Resolutions:

- `app.js` view state: trace viewer now has four modes — transcript,
timeline, replay, semantic; `setTraceView` keeps main's `persist` option
(replay is never persisted as a preference) and stops replay playback on
view switches; control visibility unions both sides (token-signal /
view-mode / collapse / expand hidden in graph, evidence, and replay
modes)
- `app.js` keyboard handler: replay T/Home/End shortcuts run first, then
main's step-bar arrow-key walking
- `app.js` click handler: replay control handlers first, then the
copy-button selector (including main's task/judge copy buttons)
- `index.html`: Replay button sits alongside main's Semantic button and
its episode-nav row
- `docs/training.md` / `skills/dashboard/SKILL.md`: describe all four
trace views together

## Validation

- `node --check src/prime_rl/dashboard/static/app.js` (rebased)
- `uv run --frozen ruff check tests/integration/dashboard_smoke.py`
(rebased)
- focused Playwright checks were run on the original branch (timed
playback, inference skipping, thinking toggles, keyboard shortcuts,
Top/Live navigation)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Read-only dashboard frontend and documentation; no changes to
training, inference, or data persistence.
> 
> **Overview**
> Adds a **Replay** tab to the rollout trace viewer that plays the
selected branch as a terminal session, using recorded model-call and
message timestamps for wall-clock pacing.
> 
> Playback includes play/pause, seek, restart, **0.5×–32×** speed
(default **8×**), **Skip inference** (instant model replies while
keeping tool delays), optional **Thinking** display (**T**), and **Top**
/ **Live** scroll follow (**Home** / **End**). Response text is revealed
evenly across each model-call span and labeled as inferred when
per-token timestamps are absent; prompt nodes committed at response time
are aligned to call start to avoid false idle gaps. Transcript-only
controls are hidden in Replay mode, and integration smoke tests cover
the new UI.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fddf8349c2f99ec4ac658b6bbfacb2e8f24532c9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-02 16:50:33 -07:00
Konstantin DunasandGitHub b28714289a feat(dashboard): visualize semantic agent traces (#3455) 2026-09-03 01:33:18 +02:00
Konstantin DunasandGitHub 903baaaa01 fix(dashboard): hide repeated timeline rewards (#3473) 2026-09-03 00:51:31 +02:00
Konstantin DunasandGitHub ae170acda1 feat(dashboard): surface task and judge evidence (#3470) 2026-09-03 00:45:13 +02:00
40 changed files with 3389 additions and 240 deletions
+1 -1
+19
View File
@@ -6,6 +6,7 @@ This page covers the specialized features layered on top of the core training st
- [Custom Modeling](#custom-modeling)
- [Expert Parallelism Backends](#expert-parallelism-backends)
- [Runtime Fusions](#runtime-fusions)
- [Multimodal Training](#multimodal-training)
- [Supported Families](#supported-families)
- [Enabling VLM Mode](#enabling-vlm-mode)
@@ -82,6 +83,24 @@ token_chunk_size = 4096
With DeepEP, gradient clipping is currently not supported. (`optim.max_norm` is set to `None` automatically.)
### Runtime Fusions
`model.fusions` packs parameters that are always computed together into one tensor, turning several GEMMs into one. Both fusions are on by default:
- `gate_up` — each gated MoE expert's `gate_proj` and `up_proj` become one `[num_experts, 2 * intermediate_size, hidden_size]` weight, halving the routed-expert grouped GEMMs.
- `qkv` — an attention layer's `q_proj`, `k_proj` and `v_proj` (and their biases) become one linear layer.
```toml
[trainer.model.fusions]
enabled = ["gate_up", "qkv"] # [] disables
```
Fusions are runtime-only. Checkpoints keep the canonical parameter names and shapes, so a run can turn a fusion on or off at any point and still load its own checkpoints, and exported weights are unaffected. Only modules that support a fusion are packed; a requested fusion that no module supports logs a warning, or fails at startup with `raise_on_fail = true`. Fusions are skipped when LoRA is enabled.
Muon receives the packed layout as matrix partitions and orthogonalizes each logical matrix on its own, so a packed parameter trains exactly as the parameters it replaces would — including per-projection learning-rate scaling for grouped-query attention — while keeping a single momentum tensor.
The experimental `shard_fused_on_dim1 = true` shards fused 2-D weights along dim 1 under FSDP, which makes weight loading and checkpointing zero-copy: fused weights and their optimizer state are read and written in place rather than assembled into a full copy on each rank first. It requires `hidden_size` to be divisible by the FSDP shard mesh size.
## Multimodal Training
### Supported Families
+1 -1
View File
@@ -354,7 +354,7 @@ tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
### Dashboard
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from the file monitor's `metrics.jsonl`), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from the file monitor's `metrics.jsonl`), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. The trace viewer separates the transcript, the wall-clock timeline of physical prefix branches, a wall-clock terminal replay of model and tool activity, and a top-to-bottom semantic graph of labeled model-call relationships. Replay uses recorded model-call and message timestamps; because providers do not persist per-token timestamps, it reveals response text evenly across the measured call span and labels that cadence as inferred. Agent and context labels in the semantic graph show the latest and peak prompt lengths first, with cumulative token processing available below on hover and click. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
A coding agent on the same machine can drive the open dashboard: `POST /api/view` with an on-disk address (`{"run", "tab", "step", "kind", "subset", "episode", "highlight": [...]}`) navigates every connected tab there and paints quote-anchored highlights in the trace viewer. Reports cite traces with `[^id]` markers whose JSON definitions carry the same address plus a verbatim quote; the dashboard re-checks each quote against the trace files and marks the citation verified or broken, so answers stay grounded in what is actually on disk. The `dashboard` skill documents the full contract.
@@ -85,6 +85,17 @@ class CompileConfig(BaseConfig):
"""Compile transformer blocks with ``fullgraph=True``."""
class FusionsConfig(BaseConfig):
enabled: list[Literal["gate_up", "qkv"]] = ["gate_up", "qkv"]
"""Runtime parameter fusions. ``gate_up`` runs each MoE expert's gate and up projections as one grouped GEMM; ``qkv`` runs attention's q, k and v projections as one GEMM. Only modules that support a fusion are packed, checkpoints keep the canonical parameter names and shapes, and fusions are skipped when LoRA is enabled. Set to ``[]`` to disable."""
raise_on_fail: bool = False
"""Fail at startup when no module supports a requested fusion, instead of logging a warning and continuing without it."""
shard_fused_on_dim1: bool = False
"""Experimental. Shard fused 2-D weights along dim 1 under FSDP so that weight loading and checkpointing are zero-copy: the checkpoint reads and writes the fused weights and their optimizer state in place, instead of assembling a full copy of every fused weight on each rank first. Requires the hidden size to be divisible by the FSDP shard mesh size."""
class IndexCacheConfig(BaseConfig):
topk_freq: int = Field(1, ge=1)
"""Recompute DSA top-k indices every N layers; intervening layers reuse the cached indices. ``1`` recomputes every layer (effectively no reuse). Mirrors vLLM's ``index_topk_freq`` HF override."""
@@ -240,6 +251,9 @@ class ModelConfig(BaseModelConfig):
compile: CompileConfig | None = CompileConfig()
"""Compile the model with ``torch.compile``."""
fusions: FusionsConfig = FusionsConfig()
"""Runtime parameter fusions, on by default."""
ac: ActivationCheckpointConfig | None = ActivationCheckpointConfig()
"""Activation checkpointing configuration. If None, activation checkpointing is disabled."""
+1 -1
View File
@@ -252,7 +252,7 @@ torchao = [
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
dion = { git = "https://github.com/samsja/dion.git", rev = "99e5f7e" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "0251105" }
vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
+36
View File
@@ -15,6 +15,42 @@ The Config and Logs views default to `latest (attempt <n>)`. Select an attempt
to inspect the immutable config or log files from an earlier launch. The Config
view shows a copyable launch command above the launch TOML or resolved JSON.
The trace viewer has separate **Transcript**, **Timeline**, **Replay**, and
**Semantic** views. Timeline is a wall-clock Gantt of physical prefix branches.
Replay renders the selected agent branch as a terminal session with play/pause,
seek, restart, and speed controls. It preserves recorded model-call and
tool-result delays. Since the trace schema records a complete model-call span
but no per-token timestamps, response text is paced evenly across that measured
span and labeled as inferred; events without timestamps remain ordered and are
labeled untimed. Semantic projects Verifiers `MessageNode.semantic_parents` as a
top-to-bottom causal graph of model calls, including subagent calls, returns,
compactions, and custom edge types. Calls occupy compact causal ranks within
bounded agent lanes: the root stays centered, concurrent children fan out
symmetrically, and child slots are reused after return, so graph width reflects
peak agent concurrency rather than total subagents. Compaction starts a visibly
separate context segment. For display only, a missing continuation is recovered
when the physical parent chain proves a completed tool round-trip; fragments
that still cannot be placed are shown explicitly as unlinked instead of being
presented as contexts. Hover or click an agent or context label to see its
latest and peak prompt lengths first, followed by cumulative token processing
and cost. Exact timing remains available on model-call hover and in Timeline.
Traces without semantic parents keep the other views and disable Semantic.
Replay defaults to 8× so long coding-agent model waits remain watchable; select
1× for exact wall time or up to 32× for faster review. In-flight calls display
their measured progress and recorded output-token usage even when they produce
only tool calls. Enable **Skip inference** to collapse model calls to immediate
responses while preserving the recorded command-to-tool-output delays. This is
distinct from the speed control, which scales every delay uniformly. Recorded
model thinking is shown by default. Toggle **Thinking** in the replay controls
or press **T** while Replay is open to hide or show it without changing playback
timing. Do not advertise Ctrl+T: browsers reserve it for a new tab before the
page can handle the keypress. Use **Top** or the **Home** key to scroll to the
beginning without pausing the replay. Use **Live** or **End** to resume
following newly rendered output. Prompt-context nodes that were committed at
response time are placed at the linked call's start so their serialization
timestamp does not create a false blank wait before the replay.
Every dashboard instance serves the dirs it was started with **plus** every dir
in the per-user registry (`~/.cache/prime-rl/dashboard/dirs.json`, re-read
live). Launchers (`rl`, `sft`) register their output dir on every
+20 -3
View File
@@ -3,9 +3,9 @@
`uv run dashboard [output_dir ...]` — a local web dashboard for run output
directories (metrics, resolved configs, rollout traces, cited reports,
component logs) at
http://localhost:7788. The trace viewer includes transcript and synchronized
agent timeline views; timeline activities open the corresponding transcript
call. Needs the `dashboard` extra. Every instance also serves
http://localhost:7788. The trace viewer includes transcript, synchronized
agent timeline, and terminal replay views; timeline activities open the
corresponding transcript call. Needs the `dashboard` extra. Every instance also serves
the dirs registered by launchers in `~/.cache/prime-rl/dashboard/dirs.json`
(one dashboard per host per user); `--isolated` serves only the given dirs and
skips the registry. See `skills/dashboard/SKILL.md` for discovery,
@@ -30,6 +30,23 @@ truth, and the viewer reports when IDs, the renderer model, or its tokenizer
are unavailable. Text, advantage, logprob, mask, and content signals apply to
both views; Rendered with Text uses the exact full-sequence decode.
**Replay** plays the selected trace branch as a terminal session. Model
responses, tool commands, and tool results follow their recorded wall-clock
spans, with play/pause, seeking, restart, and speed controls. Providers persist
the full model-call span rather than timestamps for individual tokens, so text
is revealed evenly across that measured span and the UI labels the token cadence
as inferred. Replay defaults to 8× for long coding-agent waits while preserving
their relative timing; 1× restores exact wall time, and speeds up to 32× are
available. In-flight calls show measured progress and recorded output usage even
when the response contains only a tool call. Events from older traces without
timing stay in order and are marked untimed. Prompt context committed at response
time appears at the linked model call's start rather than creating a false blank
delay. **Skip inference** makes every model response immediate while retaining
the recorded delays between tool commands and their outputs. Recorded model
thinking is visible by default and can be toggled from the controls or with
**T** while Replay is open. **Top** (or **Home**) stops following the newest
line and scrolls to the beginning; **Live** (or **End**) resumes following output.
This package is fully AI-generated and maintained by agents - it is not meant to be read or edited by humans. Change it by asking an agent, and verify through the browser smoke tests.
The integration suite covers it end to end (`tests/integration/dashboard_smoke.py`
runs after every integration test).
+263 -1
View File
@@ -884,6 +884,7 @@ def activity_spans(
if reasoning_tokens is None:
reasoning_tokens = (usage.get("completion_tokens_details") or {}).get("reasoning_tokens")
text = " ".join(message_text(node.get("message") or {}).split())
mask = node.get("mask")
spans.append(
{
"kind": "model_call",
@@ -901,6 +902,7 @@ def activity_spans(
"output_tokens": output_tokens,
"reasoning_tokens": reasoning_tokens,
"cost": usage.get("cost"),
"trainable": any(mask) if isinstance(mask, list) and mask else None,
}
)
return sorted(spans, key=lambda span: span["started_at"] if span["started_at"] is not None else float("inf"))
@@ -991,6 +993,7 @@ def timeline_lane(
"total_input_tokens": total_input_tokens,
"output_tokens": output_tokens,
"reasoning_tokens": reasoning_tokens,
"latest_context_tokens": context_lengths[-1] if context_lengths else None,
"max_context_tokens": max(context_lengths, default=None),
"total_tokens": total_tokens,
"cost": total("cost"),
@@ -999,8 +1002,254 @@ def timeline_lane(
}
def trace_semantic_edges(trace: dict, trace_index: int) -> list[dict]:
"""Resolve persisted ``MessageNode.semantic_parents`` into timeline edges."""
nodes = trace.get("nodes") or []
call_order = {
node_index: call_index
for call_index, call in enumerate(trace.get("calls") or [])
if isinstance((node_index := call.get("node")), int) and 0 <= node_index < len(nodes)
}
call_nodes = set(call_order)
edges = []
for target_node, node in enumerate(nodes):
if target_node not in call_nodes:
continue
for link in node.get("semantic_parents") or []:
source_node = link.get("node")
edge_type = link.get("type")
if source_node not in call_nodes or not isinstance(edge_type, str):
continue
edges.append(
{
"trace_index": trace_index,
"source_node": source_node,
"target_node": target_node,
"type": edge_type,
}
)
if not edges:
return []
incoming = {edge["target_node"] for edge in edges}
for target_node in sorted(call_nodes - incoming, key=call_order.get):
source_node = physical_continuation_source(nodes, call_nodes, target_node)
if source_node is None or call_order[source_node] >= call_order[target_node]:
continue
edges.append(
{
"trace_index": trace_index,
"source_node": source_node,
"target_node": target_node,
"type": "continuation",
"inferred": True,
}
)
return edges
def physical_continuation_source(nodes: list[dict], call_nodes: set[int], target_node: int) -> int | None:
"""Recover a missing continuation only from a completed tool round-trip."""
between = []
visited = {target_node}
cursor = nodes[target_node].get("parent")
while isinstance(cursor, int) and 0 <= cursor < len(nodes) and cursor not in visited:
if cursor in call_nodes:
source_node = cursor
break
visited.add(cursor)
between.append(cursor)
cursor = nodes[cursor].get("parent")
else:
return None
source_message = nodes[source_node].get("message") or {}
tool_call_ids = {
tool_call.get("id")
for tool_call in source_message.get("tool_calls") or []
if isinstance(tool_call, dict) and isinstance(tool_call.get("id"), str)
}
if not tool_call_ids or not between:
return None
for node_index in between:
message = nodes[node_index].get("message") or {}
if message.get("role") != "tool" or message.get("tool_call_id") not in tool_call_ids:
return None
return source_node
def semantic_context_lanes(
trace: dict,
trace_index: int,
role: str,
edges: list[dict],
) -> list[dict]:
"""Project continuation components as execution-context timeline lanes.
``continuation`` keeps calls in one context. ``subagent_call`` creates a child
agent, ``compaction_attempt`` creates a summary leaf beside its source context,
and ``compaction`` starts a new context for the same agent. Other edge labels
remain visible but do not invent session semantics.
"""
nodes = trace.get("nodes") or []
call_nodes = {
node_index
for call in trace.get("calls") or []
if isinstance((node_index := call.get("node")), int) and 0 <= node_index < len(nodes)
}
if not call_nodes or not edges:
return []
representatives = {node_index: node_index for node_index in call_nodes}
def find(node_index: int) -> int:
while representatives[node_index] != node_index:
representatives[node_index] = representatives[representatives[node_index]]
node_index = representatives[node_index]
return node_index
def union(left: int, right: int) -> None:
left_root = find(left)
right_root = find(right)
if left_root != right_root:
representatives[right_root] = left_root
for edge in edges:
if edge["type"] == "continuation":
union(edge["source_node"], edge["target_node"])
components: dict[int, set[int]] = {}
for node_index in call_nodes:
components.setdefault(find(node_index), set()).add(node_index)
component_for = {
node_index: component for component, node_indexes in components.items() for node_index in node_indexes
}
component_activities = {
component: activity_spans(trace, node_indexes) for component, node_indexes in components.items()
}
def component_start(component: int) -> float:
activities = component_activities[component]
starts = [span["started_at"] for span in activities if span["started_at"] is not None]
timestamps = [
nodes[node_index].get("timestamp")
for node_index in components[component]
if nodes[node_index].get("timestamp") is not None
]
return min(starts or timestamps, default=float("inf"))
ordered_components = sorted(components, key=lambda component: (component_start(component), component))
cross_edges = [edge for edge in edges if component_for[edge["source_node"]] != component_for[edge["target_node"]]]
created_components = {
component_for[edge["target_node"]]
for edge in cross_edges
if edge["type"] in {"subagent_call", "compaction_attempt", "compaction"}
}
root_components = [component for component in ordered_components if component not in created_components]
# component -> (agent label, depth, context index)
identities: dict[int, tuple[str, int, int]] = {}
unlinked_components = set()
if root_components:
identities[root_components[0]] = (role, 0, 0)
for index, component in enumerate(root_components[1:], start=1):
identities[component] = (f"unlinked {index}", 0, 0)
unlinked_components.add(component)
subagent_number = 0
changed = True
while changed:
changed = False
for edge in cross_edges:
source = component_for[edge["source_node"]]
target = component_for[edge["target_node"]]
if source not in identities or target in identities:
continue
agent_label, depth, context_index = identities[source]
if edge["type"] == "subagent_call":
subagent_number += 1
identities[target] = (f"subagent {subagent_number}", depth + 1, 0)
elif edge["type"] == "compaction_attempt":
identities[target] = (agent_label, depth, context_index)
elif edge["type"] == "compaction":
identities[target] = (agent_label, depth, context_index + 1)
else:
continue
changed = True
unlinked_index = len(unlinked_components)
for component in ordered_components:
if component not in identities:
unlinked_index += 1
identities[component] = (f"unlinked {unlinked_index}", 0, 0)
unlinked_components.add(component)
lanes = []
accepted_attempt_nodes = {edge["source_node"] for edge in cross_edges if edge["type"] == "compaction"}
attempt_by_component = {
component_for[edge["target_node"]]: {
"source_node": edge["source_node"],
"target_node": edge["target_node"],
"accepted": edge["target_node"] in accepted_attempt_nodes,
}
for edge in cross_edges
if edge["type"] == "compaction_attempt"
}
for component in ordered_components:
agent_label, depth, context_index = identities[component]
activities = component_activities[component]
start = component_start(component)
end = max(
[span["ended_at"] for span in activities if span.get("ended_at") is not None]
+ [
nodes[node_index].get("timestamp")
for node_index in components[component]
if nodes[node_index].get("timestamp") is not None
],
default=None,
)
completed = bool(trace.get("is_completed"))
label = f"{agent_label} · context {context_index}"
lifecycle = (
[
{
"kind": "agent",
"label": label,
"track": "lifecycle",
"started_at": start,
"ended_at": end if completed else None,
"status": "completed" if completed else "running",
}
]
if start != float("inf")
else []
)
lane = timeline_lane(
trace,
trace_index,
label=label,
depth=depth + 1,
branch=True,
lifecycle=lifecycle,
activities=activities,
)
lane["context"] = {
"agent": agent_label,
"index": context_index,
}
if component in unlinked_components:
lane["context"]["unlinked"] = True
if component in attempt_by_component:
lane["compaction_attempt"] = attempt_by_component[component]
lanes.append(lane)
return lanes
def project_episode_timeline(episode: dict) -> dict:
lane_groups = []
semantic_lane_groups = []
semantic_edges = []
for trace_index, trace in enumerate(episode.get("traces") or []):
nodes = trace.get("nodes") or []
branch_paths = branch_node_paths(nodes)
@@ -1085,9 +1334,22 @@ def project_episode_timeline(episode: dict) -> dict:
)
branches.sort(key=lambda item: (item[0] if item[0] is not None else float("inf"), item[1]))
lane_groups.append((parent, [lane for _, _, lane in branches]))
trace_edges = trace_semantic_edges(trace, trace_index)
semantic_lanes = semantic_context_lanes(trace, trace_index, role, trace_edges)
if semantic_lanes:
semantic_lane_groups.append((parent, semantic_lanes))
semantic_edges.extend(trace_edges)
lane_groups.sort(key=lambda group: group[0]["started_at"] if group[0]["started_at"] is not None else float("inf"))
lanes = [lane for parent, children in lane_groups for lane in (parent, *children)]
return {"lanes": lanes}
semantic_lane_groups.sort(
key=lambda group: group[0]["started_at"] if group[0]["started_at"] is not None else float("inf")
)
semantic_lanes = [lane for parent, children in semantic_lane_groups for lane in (parent, *children)]
return {
"lanes": lanes,
"semantic_lanes": semantic_lanes,
"semantic_edges": semantic_edges,
}
NICE_BINS = [1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600, 7200, 10800, 21600, 43200, 86400]
File diff suppressed because it is too large Load Diff
+16
View File
@@ -232,6 +232,13 @@
<div class="seg" id="tm-view">
<button data-view="transcript" class="active">Transcript</button>
<button data-view="timeline">Timeline</button>
<button data-view="replay">Replay</button>
<button data-view="semantic">Semantic</button>
</div>
<div id="tm-semantic-nav" class="tm-semantic-nav" hidden>
<button id="tm-episode-prev" class="btn tm-nav" title="previous episode">‹</button>
<span id="tm-episode-label"></span>
<button id="tm-episode-next" class="btn tm-nav" title="next episode">›</button>
</div>
<div class="spacer"></div>
<div class="seg" id="trace-view-mode">
@@ -254,9 +261,18 @@
<div class="tm-head tm-tabs-row" id="tm-tabs-row" hidden>
<div id="tm-trace-tabs" class="seg" hidden></div>
<div id="tm-branch-tabs" class="seg" hidden></div>
<div id="tm-evidence-tabs" class="seg" hidden></div>
</div>
<div id="tm-messages"></div>
<div id="tm-timeline" hidden></div>
<aside id="sg-inspector" hidden>
<div class="sg-inspector-head">
<span id="sg-inspector-title">Model call</span>
<button id="sg-inspector-close" class="btn" title="close inspector">✕</button>
</div>
<div id="sg-inspector-body"></div>
<button id="sg-open-transcript" class="btn">open in transcript</button>
</aside>
</section>
<aside id="tm-right">
<div class="tm-head"><span class="tm-title">Overview</span></div>
+415 -4
View File
@@ -680,6 +680,10 @@ mark.hit {
display: grid;
grid-template-columns: 280px minmax(0, 1fr) 320px;
}
#trace-modal.semantic-view { grid-template-columns: minmax(0, 1fr); }
#trace-modal.semantic-view #tm-left,
#trace-modal.semantic-view #tm-right { display: none; }
#trace-modal.semantic-view #tm-main { grid-column: 1; position: relative; }
.tm-head {
display: flex;
align-items: center;
@@ -694,7 +698,19 @@ mark.hit {
overflow-y: hidden;
scrollbar-width: thin;
}
#tm-evidence-tabs [data-evidence="task"].active { color: var(--chart-3); }
#tm-evidence-tabs [data-evidence="judge"].active { color: #7adfff; }
#tm-evidence-tabs { margin-left: auto; }
.tm-title { font-size: 12px; font-weight: 500; color: var(--grey-6); white-space: nowrap; }
.tm-semantic-nav { display: flex; align-items: center; gap: 7px; min-width: 0; }
#tm-episode-label {
max-width: 260px;
overflow: hidden;
color: var(--grey-5);
font-size: 10.5px;
text-overflow: ellipsis;
white-space: nowrap;
}
#tm-left { border-right: 1px solid var(--hairline); display: flex; flex-direction: column; min-height: 0; }
#tm-left .search { margin: 10px 14px 6px; }
#tm-list { flex: 1; overflow-y: auto; padding: 4px 8px 10px; }
@@ -738,11 +754,39 @@ mark.hit {
#tm-messages { display: flex; flex: 1; flex-direction: column; overflow-y: auto; padding: 14px 16px; }
#tm-messages > * { flex-shrink: 0; }
#tm-timeline { flex: 1; min-height: 0; overflow: auto; padding: 14px 16px 24px; }
#tm-timeline.semantic-canvas { padding: 0; background: var(--grey-1); }
#tm-right { border-left: 1px solid var(--hairline); overflow-y: auto; min-height: 0; }
#tm-meta { padding: 12px 14px; }
/* episode timeline: lifecycle spans above exact model-call activity */
.tl-shell { min-width: 780px; border: 1px solid var(--hairline); }
.tl-shell { position: relative; min-width: 780px; border: 1px solid var(--hairline); }
.tl-edge-legend {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 14px;
min-height: 34px;
padding: 7px 10px;
border-bottom: 1px solid var(--hairline);
color: var(--grey-4);
font-size: 9px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
}
.tl-edge-legend-title { color: var(--grey-5); }
.tl-edge-key { color: var(--grey-5); white-space: nowrap; }
.tl-edge-key i {
display: inline-block;
width: 18px;
margin-right: 6px;
vertical-align: 3px;
border-top: 2px solid var(--grey-4);
}
.tl-edge-key i.subagent-call { border-color: var(--infra); }
.tl-edge-key i.subagent-return { border-color: var(--risk); }
.tl-edge-key i.compaction-attempt { border-color: var(--chart-2); border-top-style: dotted; }
.tl-edge-key i.compaction { border-color: var(--chart-2); border-top-style: dashed; }
.tl-edge-key i.custom { border-color: var(--accent); border-top-style: dotted; }
.tl-head, .tl-lane {
display: grid;
grid-template-columns: minmax(160px, 220px) minmax(390px, 1fr) 105px 150px;
@@ -773,7 +817,7 @@ mark.hit {
.tl-label-meta { color: var(--grey-4); font-size: 9.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tl-track { position: relative; height: 42px; margin: 11px 0; border: 1px solid var(--hairline); overflow: hidden; }
.tl-gridline { position: absolute; top: 0; bottom: 0; border-left: 1px solid var(--hairline-faint); pointer-events: none; }
.tl-span { position: absolute; min-width: 3px; cursor: pointer; border: 0; padding: 0; }
.tl-span { position: absolute; z-index: 2; min-width: 3px; cursor: pointer; border: 0; padding: 0; }
.tl-span.lifecycle { top: 7px; height: 13px; opacity: 0.78; }
.tl-span.activity { top: 28px; height: 6px; background: var(--grey-4); }
.tl-span.activity.shared { opacity: 0.28; }
@@ -787,11 +831,10 @@ mark.hit {
.tl-time { color: var(--grey-5); font-size: 11px; }
.tl-time .muted { display: block; font-size: 9.5px; }
.tl-outcome { display: flex; flex-direction: column; align-items: flex-start; gap: 5px; font-size: 9.5px; }
.tl-state, .tl-reward { border: 1px solid var(--grey-3); padding: 1px 5px; white-space: nowrap; }
.tl-state { border: 1px solid var(--grey-3); padding: 1px 5px; white-space: nowrap; }
.tl-state.completed { color: var(--positive); }
.tl-state.failed { color: var(--negative); }
.tl-state.running { color: var(--infra); }
.tl-reward { color: var(--chart-3); }
.tl-tooltip {
position: fixed;
z-index: 60;
@@ -809,6 +852,221 @@ mark.hit {
.tl-tooltip dd { color: var(--grey-6); margin: 0; }
.tl-tooltip-hint { color: var(--grey-4); border-top: 1px solid var(--hairline); margin-top: 9px; padding-top: 7px; font-size: 9.5px; }
/* Semantic view: ordinal causal flow down the page. Agent identities occupy
reusable concurrency slots, so width reflects peak fan-out rather than the
total number of children created over a rollout. */
.semantic-canvas > .tl-edge-legend {
position: sticky;
top: 0;
left: 0;
z-index: 9;
width: max-content;
min-width: 100%;
box-sizing: border-box;
background: var(--grey-1);
font-size: 11px;
}
.sg-shell {
position: relative;
min-width: 100%;
overflow: clip;
background: var(--grey-1);
}
.sg-lane-band {
position: absolute;
inset-block: 0;
z-index: 0;
border-inline: 1px solid rgba(255, 255, 255, 0.035);
background: rgba(255, 255, 255, 0.009);
pointer-events: none;
}
.sg-lane-band.root {
border-inline-color: rgba(182, 255, 60, 0.07);
background: rgba(182, 255, 60, 0.012);
}
.sg-edge-layer { position: absolute; inset: 0; z-index: 1; pointer-events: none; overflow: visible; }
.sg-lifeline {
fill: none;
stroke: var(--lane-color);
stroke-width: 1.5;
vector-effect: non-scaling-stroke;
opacity: 0.38;
}
.sg-edge {
fill: none;
stroke: var(--grey-4);
stroke-width: 1.4;
stroke-linecap: round;
stroke-linejoin: round;
vector-effect: non-scaling-stroke;
opacity: 0.68;
}
.sg-edge.continuation { opacity: 0.34; }
.sg-edge.subagent-call { stroke: var(--infra); stroke-width: 2.2; opacity: 0.9; }
.sg-edge.subagent-return { stroke: var(--risk); stroke-width: 2.2; opacity: 0.9; }
.sg-edge.compaction-attempt { stroke: var(--chart-2); stroke-dasharray: 2 4; opacity: 0.66; }
.sg-edge.compaction { stroke: var(--chart-2); stroke-dasharray: 5 4; opacity: 0.9; }
.sg-edge.custom { stroke: var(--accent); stroke-dasharray: 2 4; opacity: 0.9; }
#sg-arrow-continuation path { fill: var(--grey-4); }
#sg-arrow-subagent-call path { fill: var(--infra); }
#sg-arrow-subagent-return path { fill: var(--risk); }
#sg-arrow-compaction-attempt path { fill: var(--chart-2); }
#sg-arrow-compaction path { fill: var(--chart-2); }
#sg-arrow-custom path { fill: var(--accent); }
.sg-agent-label {
position: absolute;
z-index: 6;
display: flex;
flex-direction: column;
align-items: center;
gap: 1px;
padding: 2px 6px;
background: var(--grey-1);
pointer-events: none;
white-space: nowrap;
}
.sg-agent-label.unlinked {
outline: 1px dashed var(--grey-3);
}
.sg-agent-label.unlinked .sg-agent-name,
.sg-agent-label.unlinked .sg-context-name {
color: var(--grey-5);
}
.sg-agent-name,
.sg-context-name {
padding: 0;
border: 0;
background: transparent;
cursor: pointer;
font: inherit;
white-space: nowrap;
pointer-events: auto;
}
.sg-agent-name {
display: flex;
align-items: center;
gap: 6px;
color: var(--grey-6);
font-size: 15px;
font-weight: 600;
}
.sg-agent-name i { width: 8px; height: 8px; flex: none; }
.sg-context-name { color: var(--grey-5); font-size: 10.5px; letter-spacing: var(--track-caps); text-transform: uppercase; }
.sg-agent-label.compacted .sg-context-name { color: var(--chart-2); }
.sg-agent-name:hover,
.sg-agent-name:focus-visible,
.sg-context-name:hover,
.sg-context-name:focus-visible { color: var(--accent); outline: none; }
.sg-agent-name:focus-visible,
.sg-context-name:focus-visible { text-decoration: underline; text-underline-offset: 3px; }
.sg-agent-label.side-left { align-items: flex-end; text-align: right; }
.sg-agent-label.side-right { align-items: flex-start; text-align: left; }
.sg-turn {
position: absolute;
z-index: 3;
padding: 0;
border: 0;
background: transparent;
color: var(--grey-4);
cursor: pointer;
font: inherit;
outline: none;
}
.sg-turn-mark {
position: absolute;
left: 50%;
top: 50%;
width: var(--turn-mark-width, 44px);
height: var(--turn-mark-height, 12px);
background: var(--turn-color);
transform: translate(-50%, -50%);
transition: width 100ms ease, height 100ms ease, background 100ms ease;
}
.sg-turn-index {
position: absolute;
top: 50%;
left: calc(50% + var(--turn-label-offset, 31px));
color: var(--grey-5);
font-size: 12.5px;
transform: translateY(-50%);
white-space: nowrap;
}
.sg-turn:hover,
.sg-turn:focus-visible { z-index: 4; }
.sg-turn:hover .sg-turn-mark,
.sg-turn:focus-visible .sg-turn-mark {
width: calc(var(--turn-mark-width, 44px) + 6px);
height: calc(var(--turn-mark-height, 12px) + 2px);
background: var(--accent);
}
.sg-turn:focus-visible .sg-turn-mark { outline: 1px solid var(--grey-6); outline-offset: 2px; }
.sg-turn.compaction-attempt.accepted .sg-turn-mark {
outline: 1px solid var(--chart-2);
outline-offset: 2px;
}
.sg-turn.compaction-attempt.rejected .sg-turn-mark {
border: 1px dashed var(--chart-2);
background: var(--grey-1);
opacity: 0.72;
}
.sg-turn.compaction-attempt.rejected .sg-turn-index { color: var(--grey-4); }
.sg-turn.compaction-attempt.rejected:hover .sg-turn-mark,
.sg-turn.compaction-attempt.rejected:focus-visible .sg-turn-mark {
border-color: var(--grey-6);
background: var(--grey-2);
opacity: 1;
}
.sg-turn-run {
position: absolute;
z-index: 5;
padding: 0 7px;
border: 0;
border-block: 1px solid color-mix(in srgb, var(--turn-color) 56%, var(--grey-3));
background: var(--grey-1);
color: var(--grey-5);
cursor: pointer;
font: 10.5px/1 var(--font-mono);
letter-spacing: 0.04em;
white-space: nowrap;
}
.sg-turn-run.collapsed {
box-shadow: 0 0 0 4px var(--grey-1);
}
.sg-turn-run.expanded {
border: 1px dashed color-mix(in srgb, var(--turn-color) 45%, var(--grey-3));
color: var(--grey-4);
}
.sg-turn-run:hover,
.sg-turn-run:focus-visible {
color: var(--grey-6);
outline: none;
}
.sg-turn-run.collapsed:hover,
.sg-turn-run.collapsed:focus-visible { border-block-color: var(--turn-color); }
.sg-turn-run:focus-visible { box-shadow: 0 0 0 2px var(--grey-1), 0 0 0 3px var(--turn-color); }
#sg-inspector {
position: absolute;
top: 62px;
right: 14px;
bottom: 14px;
z-index: 20;
display: flex;
flex-direction: column;
width: min(330px, calc(100% - 28px));
border: 1px solid var(--grey-4);
background: rgba(25, 25, 25, 0.98);
}
.sg-inspector-head { display: flex; align-items: center; gap: 8px; min-height: 46px; padding: 0 12px; border-bottom: 1px solid var(--hairline); color: var(--grey-6); font-size: 11px; }
.sg-inspector-head button { margin-left: auto; }
#sg-inspector-body { flex: 1; min-height: 0; overflow-y: auto; padding: 4px 13px 14px; }
.sg-inspector-section { margin: 13px 0 6px; color: var(--accent); font-size: 9px; letter-spacing: var(--track-caps); text-transform: uppercase; }
.sg-inspector-row { display: flex; gap: 12px; padding: 3px 0; font-size: 10.5px; }
.sg-inspector-row span { color: var(--grey-4); }
.sg-inspector-row strong { margin-left: auto; color: var(--grey-6); font-weight: 400; }
.sg-inspector-snippet { color: var(--grey-5); font-size: 10.5px; line-height: 1.5; white-space: pre-wrap; word-break: break-word; }
#sg-open-transcript { margin: 0 12px 12px; min-height: 30px; }
/* the banners lead the transcript, so they stand off the first entry */
.trace-errors { margin-top: auto; padding-top: 12px; margin-bottom: 14px; }
.trace-error-banner {
@@ -844,6 +1102,13 @@ mark.hit {
/* numbered collapsible message entries */
details.entry { border: 1px solid var(--hairline); margin-bottom: 8px; }
details.entry.semantic-origin {
border-color: var(--accent);
outline: 1px solid rgba(182, 255, 60, 0.55);
outline-offset: 2px;
scroll-margin-block: 80px;
}
details.entry.semantic-origin > summary { background: rgba(182, 255, 60, 0.08); }
details.entry > summary {
display: flex;
align-items: center;
@@ -915,6 +1180,80 @@ details.tool-definitions, .rendered-transcript {
margin-bottom: 12px;
background: rgba(183, 166, 250, 0.025);
}
.task-evidence {
border: 1px solid color-mix(in srgb, var(--chart-3) 42%, var(--grey-3));
margin-bottom: 12px;
background: color-mix(in srgb, var(--chart-3) 3%, transparent);
}
.task-evidence.standalone,
.judging-view .judging-divider { margin-top: 0; }
.task-evidence > summary {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
padding: 7px 12px;
background: var(--grey-2);
}
.task-evidence .context-label { color: var(--chart-3); }
.task-evidence[open] > summary { border-bottom: 1px solid var(--hairline); }
.task-evidence[open] > summary .entry-chev { transform: rotate(90deg); }
.evidence-fields { display: grid; gap: 8px; padding: 10px 12px 12px; }
.evidence-field { min-width: 0; border: 1px solid var(--hairline); background: rgba(0, 0, 0, 0.08); }
.evidence-field > header {
display: flex;
align-items: center;
padding: 5px 9px;
border-bottom: 1px solid var(--hairline);
color: var(--chart-3);
font-size: 10px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
}
.evidence-field > header .icon-btn { margin-left: auto; }
.evidence-field > pre,
.judge-result > pre {
max-height: 360px;
margin: 0;
overflow: auto;
padding: 9px 11px;
color: var(--grey-5);
font: 400 11px/1.55 var(--font-mono);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.judging-divider {
display: flex;
align-items: center;
gap: 10px;
margin: 20px 0 8px;
color: #7adfff;
font-size: 10px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
}
.judging-divider::after { content: ""; flex: 1; height: 1px; background: var(--hairline); }
.judging-divider > :last-child { order: 2; color: var(--grey-4); }
.judge-entry { border-color: color-mix(in srgb, #7adfff 38%, var(--grey-3)); }
.judge-entry .entry-role { color: #7adfff; }
.judge-call-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: 10px; padding: 10px 12px 12px; }
.judge-request,
.judge-result { min-width: 0; border: 1px solid var(--hairline); }
.judge-request > header,
.judge-result > header {
padding: 6px 10px;
border-bottom: 1px solid var(--hairline);
color: #7adfff;
font-size: 10px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
}
.judge-result.parsed > header { color: var(--chart-2); }
.judge-message { display: grid; grid-template-columns: 72px minmax(0, 1fr); border-bottom: 1px solid var(--hairline-faint); }
.judge-message:last-child { border-bottom: 0; }
.judge-message > header { display: flex; gap: 8px; padding: 9px 10px; color: var(--grey-4); font-size: 10px; }
.judge-message > header strong { color: var(--grey-5); font-weight: 500; text-transform: uppercase; }
.judge-message > div { min-width: 0; padding: 9px 11px; border-left: 1px solid var(--hairline); color: var(--grey-5); font-size: 11.5px; white-space: pre-wrap; overflow-wrap: anywhere; }
details.tool-definitions > summary, details.rendered-transcript > summary,
details.tool-definition > summary {
display: flex;
@@ -978,6 +1317,78 @@ details.meta-fold > pre { margin: 0; border: none; border-top: 1px solid var(--h
word-break: break-word;
}
/* terminal replay follows the trace's wall clock; message text is revealed
across its recorded model-call span because providers do not persist per-token timestamps */
.replay-shell {
display: flex;
flex: 1 1 auto !important;
min-height: 420px;
flex-direction: column;
overflow: hidden;
border: 1px solid var(--grey-3);
background: #080b07;
}
.replay-bar, .replay-controls {
display: flex;
align-items: center;
gap: 10px;
min-height: 40px;
padding: 7px 12px;
border-bottom: 1px solid rgba(182, 255, 60, 0.12);
background: #0d110c;
}
.replay-lights { color: var(--grey-3); letter-spacing: 3px; font-size: 8px; }
.replay-title { color: var(--grey-6); font-size: 11px; }
.replay-bar .chip { margin-left: auto; }
.replay-controls .btn { min-width: 48px; }
#replay-top, #replay-live { min-width: 52px; }
#replay-top.active, #replay-live.active { color: var(--accent); border-color: rgba(182, 255, 60, 0.35); }
#replay-restart { min-width: 30px; }
#replay-progress { flex: 1; min-width: 80px; accent-color: var(--accent); }
#replay-time { color: var(--grey-4); font: 400 10.5px var(--font-mono); white-space: nowrap; }
.replay-skip { display: flex; align-items: center; gap: 5px; color: var(--grey-5); font-size: 10.5px; white-space: nowrap; }
.replay-skip input { accent-color: var(--accent); }
.replay-skip kbd { color: var(--grey-4); font: 400 8.5px var(--font-mono); border: 1px solid var(--grey-3); padding: 1px 3px; }
.replay-control-label { color: var(--grey-4); font-size: 9px; letter-spacing: var(--track-caps); text-transform: uppercase; }
#replay-speed {
border: 1px solid var(--grey-3);
background: var(--grey-1);
color: var(--grey-5);
font: 400 10.5px var(--font-mono);
padding: 4px 6px;
}
.replay-output-pane {
flex: 1;
overflow: auto;
padding: 16px 18px 40px;
color: #c8d1c5;
font: 400 12px/1.6 var(--font-mono);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.replay-event { display: grid; grid-template-columns: 64px minmax(0, 1fr); gap: 12px; margin-bottom: 14px; }
.replay-event > div > span { display: block; }
.replay-stamp { color: #52604e; font-size: 9.5px; padding-top: 2px; }
.replay-system { color: #7c8978; }
.replay-user { color: #f1f5ef; }
.replay-assistant { color: #c8d1c5; }
.replay-command { margin-top: 7px; color: var(--accent); }
.replay-output { padding-left: 10px; border-left: 1px solid #33432d; color: #9dac98; }
.replay-wait, .replay-running { color: #70806c; }
.replay-model-wait {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 4px 16px;
margin-bottom: 8px;
color: #70806c;
font-size: 10.5px;
}
.replay-model-wait > i { grid-column: 1 / -1; height: 2px; overflow: hidden; background: #1c2719; }
.replay-model-wait > i > b { display: block; height: 100%; background: var(--accent); }
.replay-running { display: flex; align-items: center; gap: 8px; margin: 0 0 14px 76px; }
.replay-spinner { width: 7px; height: 7px; border: 1px solid #52604e; border-top-color: var(--accent); border-radius: 50%; animation: replay-spin 0.8s linear infinite; }
@keyframes replay-spin { to { transform: rotate(360deg); } }
.tok { padding: 0 1px; }
.tok:hover { outline: 1px solid var(--grey-6); }
.tok-tip {
+9 -9
View File
@@ -37,7 +37,7 @@ from prime_rl.configs.evals import EvalsConfig
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig
from prime_rl.evals.ckpt import CheckpointManager
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
from prime_rl.orchestrator.clients import AdminClients, InferenceClient
from prime_rl.orchestrator.clients import AdminPlane, InferenceClient
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs
@@ -99,7 +99,7 @@ class Evals:
# Assigned in setup(); None-initialized so stop() can tear down a
# partially completed setup with plain attribute checks.
self.clients: InferenceClient | None = None
self.admin_clients: AdminClients | None = None
self.admin_plane: AdminPlane | None = None
self.dispatcher: Dispatcher | None = None
self.inference_metrics: InferenceMetricsCollector | None = None
self.periodic_logger: PeriodicLogger | None = None
@@ -125,7 +125,7 @@ class Evals:
get_logger().info(f"Initializing inference pool (base_url={config.eval.client.base_url}, model={config.model})")
self.clients = InferenceClient(config.eval.client, model_name=config.model)
self.admin_clients = AdminClients(config.eval.client)
self.admin_plane = AdminPlane(config.eval.client)
self.spawn_env_servers()
@@ -135,7 +135,7 @@ class Evals:
get_logger().success(f"Eval environment(s) ready ({', '.join(self.eval_envs.names)})")
get_logger().info("Waiting for inference pool to be ready")
await self.admin_clients.wait_for_ready(config.model)
await self.admin_plane.wait_for_ready(config.model)
get_logger().success("Inference pool ready")
self.receiver: WeightReceiver | None = None
@@ -148,7 +148,7 @@ class Evals:
self.receiver = setup_weight_receiver(
config.online.broadcasts_dir,
weight_broadcast,
admin_clients=self.admin_clients.clients,
admin_plane=self.admin_plane,
model_name=config.model,
)
await self.receiver.initialize()
@@ -201,7 +201,7 @@ class Evals:
# The collector always polls — it feeds the concurrency controller;
# metrics fan out to every registered monitor.
self.inference_metrics = InferenceMetricsCollector(
self.admin_clients.clients,
self.admin_plane.clients,
on_load=self.concurrency.observe,
)
# Fail fast when adaptivity has no signal: external API endpoints
@@ -212,7 +212,7 @@ class Evals:
if not await self.inference_metrics.probe():
concurrency = config.eval.concurrency
if concurrency.min_inflight != concurrency.max_inflight:
urls = ", ".join(str(client.base_url) for client in self.admin_clients.clients)
urls = ", ".join(str(client.base_url) for client in self.admin_plane.clients)
raise ValueError(
f"No engine metrics at {urls} - adaptive concurrency has no load signal. "
"The endpoint does not expose vLLM /metrics (e.g. an external inference API); "
@@ -579,8 +579,8 @@ class Evals:
await self.dispatcher.stop()
if self.clients is not None:
await self.clients.aclose()
if self.admin_clients is not None:
await self.admin_clients.aclose()
if self.admin_plane is not None:
await self.admin_plane.aclose()
cleanup_processes(self.env_server_procs)
+3 -2
View File
@@ -9,8 +9,9 @@ from prime_rl.transports.batch import TrainingSample
def assign_advantages(trace: vf.Trace, values: float | list[float]) -> None:
"""Assign credit in compact sampled-token order across the trace graph."""
nodes = [node for node in trace.nodes if any(node.mask)]
"""Assign credit in compact sampled-token order across trainable graph paths."""
trainable_nodes = {id(node) for branch in trace.branches if branch.trainable for node in branch.nodes}
nodes = [node for node in trace.nodes if id(node) in trainable_nodes and any(node.mask)]
for node in nodes:
if len(node.mask) != len(node.token_ids):
raise ValueError(
+1 -1
View File
@@ -43,7 +43,7 @@ def stamp_batch(episodes: list[vf.Episode], step: int) -> list[dict[str, Any]]:
branches = {
branch.index: {"advantages": advantages}
for branch in trace.branches
if (advantages := branch.advantages) is not None
if branch.trainable and (advantages := branch.advantages) is not None
}
updates.append(make_update(trace.id, info=info, branches=branches))
return updates
+80 -96
View File
@@ -4,6 +4,7 @@ import asyncio
import os
from collections.abc import Callable
from pathlib import Path
from typing import Literal
import httpx
import verifiers.v1 as vf
@@ -73,16 +74,15 @@ class InferenceClient:
await self._scorer.aclose()
class AdminClients:
class AdminPlane:
"""Admin plane of the policy inference deployment: one httpx client per
engine process. The router serves no admin routes (pause/resume,
update_weights, init_broadcaster, load_lora_adapter live on the engines),
so these clients bypass it via ``admin_base_url``.
The client order is load-bearing: ``admin_base_url`` order must match the
GPU rank order — the ``rank_offset`` math in ``init_nccl_broadcast`` /
``init_nixl_broadcast`` and the metrics collector's role list index into
it."""
GPU rank order used by NCCL/NIXL initialization and the metrics collector's
role list index."""
def __init__(self, client_config: ClientConfig):
self.clients = setup_admin_clients(client_config)
@@ -107,6 +107,77 @@ class AdminClients:
)
await maybe_check_has_model(self.clients, model_name, skip_model_check=self._skip_model_check)
async def initialize_nccl(
self,
*,
host: str,
port: int,
timeout: int,
inference_world_size: int,
quantize_in_weight_transfer: bool = False,
) -> None:
gpus_per_server = inference_world_size // len(self.clients)
get_logger().info(
f"Initializing NCCL broadcast: {len(self.clients)} servers, "
f"inference_world_size={inference_world_size}, gpus_per_server={gpus_per_server}"
)
async def initialize_client(admin_client: AsyncClient, rank_offset: int) -> None:
try:
response = await admin_client.post(
"/init_broadcaster",
json={
"host": host,
"port": port,
"rank_offset": rank_offset,
"inference_world_size": inference_world_size,
"timeout": timeout,
"quantize_in_weight_transfer": quantize_in_weight_transfer,
},
)
response.raise_for_status()
except httpx.HTTPStatusError as error:
if error.response.status_code == 404:
get_logger().warning(
"The route /init_broadcaster does not exist. Skipping NCCL broadcast initialization."
)
await asyncio.gather(
*(
initialize_client(admin_client, client_num * gpus_per_server)
for client_num, admin_client in enumerate(self.clients)
)
)
async def update_weights(
self,
weight_dir: Path | None,
*,
transport: Literal["filesystem", "nccl", "nixl"],
step: int = 0,
on_paused: Callable[[], None] | None = None,
) -> None:
"""Update every inference engine through its configured weight transport."""
weight_dir_posix = weight_dir.as_posix() if weight_dir is not None else None
await _pause_engines(self.clients, step=step)
try:
if on_paused is not None:
on_paused()
await asyncio.gather(
*[
_admin_post(
admin_client,
"/update_weights",
json={"weight_dir": weight_dir_posix},
timeout_s=UPDATE_WEIGHTS_TIMEOUT_S,
)
for admin_client in self.clients
]
)
finally:
await _resume_engines(self.clients)
async def aclose(self) -> None:
for client in self.clients + self._router_clients:
await client.aclose()
@@ -116,7 +187,7 @@ async def check_inference_ready(client_config: ClientConfig, model_name: str) ->
"""One-shot readiness check of an inference endpoint (health + model
listing) with transient clients — for frozen endpoints that never need a
persistent admin plane."""
admin = AdminClients(client_config)
admin = AdminPlane(client_config)
try:
await admin.wait_for_ready(model_name)
finally:
@@ -300,44 +371,6 @@ async def _resume_engines(admin_clients: list[AsyncClient]) -> None:
logger.debug("All inference engines resumed")
async def update_weights(
admin_clients: list[AsyncClient],
weight_dir: Path | None,
step: int = 0,
on_paused: Callable[[], None] | None = None,
) -> None:
"""Update weights on static inference servers.
Pauses all engines first to drain in-flight requests, then performs the
weight update, then resumes. This ensures all DP workers are idle and can
participate in the collective weight transfer. ``on_paused`` runs between
the pause and the update RPC — the NCCL receiver signals the trainer there.
Note: the prefix cache is intentionally not reset on weight update. The orchestrator
salts the prefix cache per weight version (``cache_salt`` in the sampling request, see
``orchestrator/envs.py``), so KV computed under old weights is never reused.
"""
weight_dir_posix = weight_dir.as_posix() if weight_dir is not None else None
await _pause_engines(admin_clients, step=step)
try:
if on_paused is not None:
on_paused()
await asyncio.gather(
*[
_admin_post(
admin_client,
"/update_weights",
json={"weight_dir": weight_dir_posix},
timeout_s=UPDATE_WEIGHTS_TIMEOUT_S,
)
for admin_client in admin_clients
]
)
finally:
await _resume_engines(admin_clients)
def _is_retryable_lora_error(exception: BaseException) -> bool:
"""Check if an exception should trigger a retry for LoRA loading."""
if isinstance(exception, httpx.HTTPStatusError):
@@ -362,7 +395,7 @@ LORA_LOAD_READ_TIMEOUT_S = 30.0
LORA_LOAD_TOTAL_TIMEOUT_S = 120.0
async def load_lora_adapter(admin_clients: list[AsyncClient], lora_name: str, lora_path: Path) -> None:
async def load_lora_adapter(admin_plane: AdminPlane, lora_name: str, lora_path: Path) -> None:
"""Make a HTTP post request to the vLLM server to load a LoRA adapter.
Uses our wrapper around vLLM's /v1/load_lora_adapter. The prefix cache is not reset
@@ -390,61 +423,11 @@ async def load_lora_adapter(admin_clients: list[AsyncClient], lora_name: str, lo
)
response.raise_for_status()
await asyncio.gather(*[_load_lora_adapter(admin_client) for admin_client in admin_clients])
async def init_nccl_broadcast(
admin_clients: list[AsyncClient],
host: str,
port: int,
timeout: int,
inference_world_size: int,
quantize_in_weight_transfer: bool = False,
) -> None:
"""Initialize NCCL broadcast on all inference servers.
Each admin client represents one vLLM server. The function computes
per-server rank_offset and gpus_per_server so that every inference GPU
gets a unique rank in the NCCL broadcast group.
"""
logger = get_logger()
gpus_per_server = inference_world_size // len(admin_clients)
logger.info(
f"Initializing NCCL broadcast: {len(admin_clients)} servers, "
f"inference_world_size={inference_world_size}, gpus_per_server={gpus_per_server}"
)
async def _init_nccl_broadcast(admin_client: AsyncClient, rank_offset: int) -> None:
try:
response = await admin_client.post(
"/init_broadcaster",
json={
"host": host,
"port": port,
"rank_offset": rank_offset,
"inference_world_size": inference_world_size,
"timeout": timeout,
"quantize_in_weight_transfer": quantize_in_weight_transfer,
},
)
response.raise_for_status()
except httpx.HTTPStatusError as e:
if e.response.status_code == 404:
logger.warning("The route /init_broadcaster does not exist. Skipping NCCL broadcast initialization.")
return
await asyncio.gather(
*[
_init_nccl_broadcast(admin_client, client_num * gpus_per_server)
for client_num, admin_client in enumerate(admin_clients)
]
)
await asyncio.gather(*[_load_lora_adapter(client) for client in admin_plane.clients])
async def init_nixl_broadcast(
admin_clients: list[AsyncClient],
admin_plane: AdminPlane,
host: str,
port: int,
timeout: int,
@@ -452,6 +435,7 @@ async def init_nixl_broadcast(
session_id: str,
) -> None:
"""Configure every vLLM worker for NIXL + ModelExpress pulls."""
admin_clients = admin_plane.clients
workers_per_server = inference_world_size // len(admin_clients)
async def initialize(admin_client: AsyncClient, rank_offset: int) -> None:
+9 -9
View File
@@ -39,7 +39,7 @@ from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.algo.routing import is_trainable
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
from prime_rl.orchestrator.clients import AdminClients, InferenceClient
from prime_rl.orchestrator.clients import AdminPlane, InferenceClient
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
@@ -119,7 +119,7 @@ class Orchestrator:
# Always set by ``setup()``
tokenizer: PreTrainedTokenizer
clients: InferenceClient | None
admin_clients: AdminClients | None
admin_plane: AdminPlane | None
sender: BatchSender | None
packer: BatchPacker
train_envs: TrainEnvs
@@ -172,7 +172,7 @@ class Orchestrator:
# Always assigned by ``setup()``; None-initialized so teardown can run
# on a partially completed setup with plain attribute checks
self.clients = None
self.admin_clients = None
self.admin_plane = None
# Optional attributes — ``setup()`` populates them when the relevant
# config is present
@@ -208,7 +208,7 @@ class Orchestrator:
eval_client_type="openai_chat_completions",
renderer_config=config.renderer,
)
self.admin_clients = AdminClients(config.model.client)
self.admin_plane = AdminPlane(config.model.client)
await monitors.setup(
producer="orch",
@@ -290,7 +290,7 @@ class Orchestrator:
get_logger().info("Waiting for policy inference pool to be ready")
t0 = time.perf_counter()
await self.admin_clients.wait_for_ready(config.model.name)
await self.admin_plane.wait_for_ready(config.model.name)
get_logger().success(f"Policy inference pool ready after {format_time(time.perf_counter() - t0)}")
# Build + ready pools for each env's frozen generation source and the
# algorithm's frozen reference model
@@ -307,7 +307,7 @@ class Orchestrator:
self.receiver = setup_weight_receiver(
get_broadcast_dir(config.output_dir),
config.weight_broadcast,
admin_clients=self.admin_clients.clients,
admin_plane=self.admin_plane,
model_name=config.model.name,
)
await self.receiver.initialize()
@@ -360,7 +360,7 @@ class Orchestrator:
# The collector always polls — it feeds the concurrency controller;
# metrics fan out to every registered monitor when collection is on.
self.inference_metrics = InferenceMetricsCollector(
self.admin_clients.clients,
self.admin_plane.clients,
roles=config.inference_metrics_roles,
on_load=self.concurrency.observe,
log_metrics=config.collect_inference_metrics,
@@ -1056,8 +1056,8 @@ class Orchestrator:
await self.inference_metrics.stop()
if self.clients is not None:
await self.clients.aclose()
if self.admin_clients is not None:
await self.admin_clients.aclose()
if self.admin_plane is not None:
await self.admin_plane.aclose()
if self.train_envs is not None:
get_logger().debug("Stopping generation source and algorithm clients")
for env in self.train_envs:
@@ -91,6 +91,7 @@ def _encode_sampling_mask(mask: vf.SamplingMask | None, num_tokens: int) -> Samp
def iter_trainable_branches(trace: vf.Trace) -> Iterator[tuple[vf.Branch, list[bool]]]:
"""Yield each branch that yields a training sample, with its trainable-token mask.
Branches excluded by trace semantics are skipped before shared-node accounting.
The mask is `branch.sampled_mask` except that a sampled node shared by several branches
(a mid-trajectory fork) is trainable only in the first branch containing it; later
branches carry its tokens as context (mask False). Branches left with no trainable
@@ -99,6 +100,8 @@ def iter_trainable_branches(trace: vf.Trace) -> Iterator[tuple[vf.Branch, list[b
"""
trained_nodes: set[int] = set()
for branch in trace.branches:
if not branch.trainable:
continue
mask: list[bool] = []
for node in branch.nodes:
if node.sampled and any(node.mask) and id(node) in trained_nodes:
+18 -2
View File
@@ -19,6 +19,11 @@ from torchdata.stateful_dataloader import StatefulDataLoader
from prime_rl.configs.shared import ResumeConfig
from prime_rl.configs.trainer import CheckpointConfig
from prime_rl.trainer.models.fusions import (
join_loaded_optimizer_state_for_runtime,
split_packed_optimizer_state_for_checkpoint,
write_back_loaded_packed_optimizer_state,
)
from prime_rl.trainer.optim import OffloadOptimizer, OptimizerLike
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import format_time, get_logger
@@ -79,9 +84,12 @@ class AppState(Stateful):
# Automatically manages FSDP FQN's, as well as sets the default state dict type to FSDP.SHARDED_STATE_DICT
checkpoint_optimizers = self._get_checkpoint_optimizers()
model_state_dict, optimizer_state_dict = get_state_dict(self.model, checkpoint_optimizers)
# Runtime fusions own one physical state tensor per fused parameter; the checkpoint
# sees it under the canonical names. This dict is also the template dcp_load writes
# into, and load_state_dict packs the loaded entries back into the runtime state.
state_dict = {
"model": model_state_dict,
"optimizers": optimizer_state_dict,
"optimizers": split_packed_optimizer_state_for_checkpoint(self.model, optimizer_state_dict),
}
if self.scheduler is not None:
scheduler_state_dict = self.scheduler.state_dict()
@@ -118,15 +126,23 @@ class AppState(Stateful):
# apply the model side here and flip the wrappers to initialized so
# subsequent steps take the steady-state path.
set_model_state_dict(self.model, model_state_dict=state_dict["model"])
# The template only aliases a packed parameter's state where the packing
# dimension is unsharded, so the loaded logical entries are packed back in.
write_back_loaded_packed_optimizer_state(self.model, checkpoint_optimizers, state_dict["optimizers"])
for optimizer in self.optimizers:
if isinstance(optimizer, OffloadOptimizer):
optimizer.finish_checkpoint_load()
else:
# The runtime state dict read back here keys the fused parameters' state by their
# physical names; the loaded logical entries are packed into it.
_, runtime_optimizer_state_dict = get_state_dict(self.model, checkpoint_optimizers)
set_state_dict(
self.model,
checkpoint_optimizers,
model_state_dict=state_dict["model"],
optim_state_dict=state_dict["optimizers"],
optim_state_dict=join_loaded_optimizer_state_for_runtime(
self.model, state_dict["optimizers"], runtime_optimizer_state_dict
),
)
if self.scheduler is not None:
+17
View File
@@ -42,6 +42,11 @@ from prime_rl.trainer.models import (
get_custom_vlm_cls,
supports_custom_impl,
)
from prime_rl.trainer.models.fusions import (
apply_model_fusions,
get_fsdp_shard_placement_fn,
write_back_loaded_packed_parameters,
)
from prime_rl.trainer.models.glm_moe_dsa.sparse_mla_attention import Indexer
from prime_rl.trainer.models.layers.fp8_linear import replace_linear_with_fp8_blockwise_linear
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
@@ -774,10 +779,12 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
mp_policy = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=DTYPE_MAP[config.reduce_dtype])
offload_policy: OffloadPolicy = CPUOffloadPolicy(pin_memory=True) if config.fsdp_cpu_offload else OffloadPolicy()
shard_placement_fn = get_fsdp_shard_placement_fn(model) if config.fusions.shard_fused_on_dim1 else None
fsdp_config = {
"mp_policy": mp_policy,
"offload_policy": offload_policy,
"reshard_after_forward": config.reshard_after_forward,
"shard_placement_fn": shard_placement_fn,
}
hsdp_mesh = parallel_dims.get_mesh("hsdp")
@@ -819,6 +826,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
mp_policy=MixedPrecisionPolicy(param_dtype=torch.float32, reduce_dtype=torch.float32),
offload_policy=offload_policy,
reshard_after_forward=config.reshard_after_forward,
shard_placement_fn=shard_placement_fn,
)
fully_shard(
@@ -844,6 +852,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
mp_policy=mp_policy,
offload_policy=offload_policy,
reshard_after_forward=False,
shard_placement_fn=shard_placement_fn,
)
else:
get_logger().warning("Model uses tied word embeddings, so skipping the last-layer no-reshard optimization.")
@@ -854,6 +863,7 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
mp_policy=mp_policy,
offload_policy=offload_policy,
reshard_after_forward=config.reshard_after_forward,
shard_placement_fn=shard_placement_fn,
)
if not parallel_dims.ep_enabled:
@@ -1006,6 +1016,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
state_dict,
storage_reader=HuggingFaceStorageReader(path=snapshot_path.as_posix()),
)
write_back_loaded_packed_parameters(model, state_dict)
# Restore weight tying broken by to_empty() for HF models
if not isinstance(model, PreTrainedModelPrimeRL) and model.config.tie_word_embeddings:
model.tie_weights()
@@ -1257,6 +1268,12 @@ def setup_model(
logger.warning("Cannot load model to meta device only, loading to CPU instead.")
model = get_model(config, device=torch.device("cpu"), dtype=DTYPE_MAP[config.optimization_dtype])
if config.fusions.enabled and config.lora is not None:
logger.warning("Skipping runtime model fusions because LoRA targets the unfused projections")
elif config.fusions.enabled:
applied = apply_model_fusions(model, config.fusions.enabled, raise_on_fail=config.fusions.raise_on_fail)
logger.info(f"Applied runtime model fusions: {applied}")
lm_head_chunk_size: int | None = None
if isinstance(config.fused_lm_head_token_chunk_size, int):
lm_head_chunk_size = config.fused_lm_head_token_chunk_size
@@ -23,7 +23,7 @@ Design constraints:
``expert_offset`` so a rank can unstack just its *local* experts into
globally-numbered per-expert keys — no all-gather. Any op that genuinely
needs a full tensor is the caller's responsibility to gather first (via the
trainer's ``_resolve_dtensors``); none of the ops here gather on their own.
trainer's ``resolve_dtensors``); none of the ops here gather on their own.
* **Every op is present-guarded** — it no-ops when its inputs are absent — so
the same per-layer op list can be emitted for every layer and simply skips
dense / non-matching layers, exactly as the imperative loops did.
+312
View File
@@ -0,0 +1,312 @@
from collections.abc import Callable, Iterator, Sequence
from typing import Any, NamedTuple
import torch
from torch import nn
from torch.distributed.tensor import Shard
from prime_rl.utils.logger import get_logger
from prime_rl.utils.weights import resolve_fqn
# Replaces some of a module's parameters with a packed one. Advertised by modules
# through their ``supported_fusions``.
RuntimeFusion = Callable[[nn.Module], None]
class PackedParameterSpec:
"""One physical parameter packing several logical parameters along a dimension.
Training allocates, computes on, and optimizes the packed parameter. The logical
parameters keep their canonical names in checkpoints. They alias the packed storage
unless the parameter is a DTensor sharded along the packing dimension, where a split
has to redistribute and yields copies instead.
``name`` and ``logical_names`` are relative to the module the packing is registered
on, and may name parameters of its children. ``dim`` is a non-negative dimension
index into the packed parameter.
"""
def __init__(self, name: str, logical_names: Sequence[str], sizes: Sequence[int], dim: int):
self.name = name
self.logical_names = tuple(logical_names)
self.sizes = tuple(sizes)
self.dim = dim
def split_into_logical_views(self, tensor: torch.Tensor) -> tuple[torch.Tensor, ...]:
"""The logical parameters, in ``logical_names`` order, as views of ``tensor``."""
return tensor.split(self.sizes, dim=self.dim)
def pack_logical_tensors(self, tensors: Sequence[torch.Tensor]) -> torch.Tensor:
return torch.cat(list(tensors), dim=self.dim)
def muon_matrix_partitions(self, parameter: torch.Tensor) -> tuple[int, ...] | None:
"""Muon's partition sizes, or None when the packing is not on the output dimension."""
return self.sizes if self.dim == parameter.ndim - 2 else None
def register_packed_parameter_state_dict_hooks(module: nn.Module, spec: PackedParameterSpec) -> None:
"""Record a packed parameter and keep the module's state dict in canonical form.
The hooks below trade the packed entry for its canonical ones on the way out and
back again on the way in, so checkpoints never see the packed layout. Torch stamps
an attribute onto every hook it registers, so these have to be plain functions.
"""
def split_packed_entry_into_logical_entries(module, state_dict, prefix, local_metadata) -> None:
views = spec.split_into_logical_views(state_dict.pop(f"{prefix}{spec.name}"))
for logical_name, view in zip(spec.logical_names, views):
state_dict[f"{prefix}{logical_name}"] = view
def join_logical_entries_into_packed_entry(module, state_dict, prefix, *load_state_dict_args) -> None:
state_dict[f"{prefix}{spec.name}"] = spec.pack_logical_tensors(
[state_dict.pop(f"{prefix}{logical_name}") for logical_name in spec.logical_names]
)
module.packed_parameter_specs = (*getattr(module, "packed_parameter_specs", ()), spec)
module.register_state_dict_post_hook(split_packed_entry_into_logical_entries)
module.register_load_state_dict_pre_hook(join_logical_entries_into_packed_entry)
def fuse_gate_up_projections(module: nn.Module) -> None:
"""Pack a gated expert's gate and up projections into one grouped-GEMM weight.
The packed weight is ``[num_experts, 2 * hidden_dim, dim]``, so the forward path is a
single grouped GEMM whose transpose and chunk are views.
"""
spec = PackedParameterSpec("gate_up_proj", ("gate_proj", "up_proj"), (module.hidden_dim, module.hidden_dim), dim=1)
module.gate_up_proj = nn.Parameter(
spec.pack_logical_tensors([module.gate_proj, module.up_proj]),
requires_grad=module.gate_proj.requires_grad,
)
module.gate_proj = None
module.up_proj = None
register_packed_parameter_state_dict_hooks(module, spec)
def fuse_qkv_projections(module: nn.Module) -> None:
"""Pack an attention module's query, key and value projections into one linear layer.
The packed weight is ``[q_size + k_size + v_size, hidden_size]``, so the projections
become a single GEMM whose output is split along the last dimension.
"""
projections = {"q_proj": module.q_proj, "k_proj": module.k_proj, "v_proj": module.v_proj}
sizes = tuple(projection.out_features for projection in projections.values())
has_bias = module.q_proj.bias is not None
# Built on meta so the packed parameters assigned below are the only allocation
qkv_proj = nn.Linear(module.q_proj.in_features, sum(sizes), bias=has_bias, device="meta")
for parameter_name in ("weight", "bias") if has_bias else ("weight",):
spec = PackedParameterSpec(
f"qkv_proj.{parameter_name}",
[f"{name}.{parameter_name}" for name in projections],
sizes,
dim=0,
)
tensors = [getattr(projection, parameter_name) for projection in projections.values()]
setattr(
qkv_proj,
parameter_name,
nn.Parameter(spec.pack_logical_tensors(tensors), requires_grad=tensors[0].requires_grad),
)
register_packed_parameter_state_dict_hooks(module, spec)
module.qkv_proj = qkv_proj
# The projections stay in place, emptied. DCP resolves every checkpoint key by
# attribute traversal, so the canonical q/k/v names still need a module to land on.
for projection in projections.values():
projection.weight = None
projection.bias = None
def apply_model_fusions(
model: nn.Module, requested_fusions: Sequence[str], raise_on_fail: bool = True
) -> dict[str, int]:
"""Apply each requested fusion to every module that supports it; returns the module count per fusion."""
fused_module_counts: dict[str, int] = {}
for fusion_name in requested_fusions:
num_fused_modules = 0
for module in model.modules():
fusion: RuntimeFusion | None = getattr(module, "supported_fusions", {}).get(fusion_name)
if fusion is None:
continue
fusion(module)
num_fused_modules += 1
if num_fused_modules == 0:
message = f"The model does not support the {fusion_name!r} runtime fusion"
if raise_on_fail:
raise ValueError(message)
get_logger().warning(f"{message}; continuing without it")
continue
fused_module_counts[fusion_name] = num_fused_modules
return fused_module_counts
def join_module_path(module_path: str, name: str) -> str:
"""Join a module path and a name, tolerating the empty path of the root module."""
return f"{module_path}.{name}" if module_path else name
class PackedParameterInfo(NamedTuple):
fqn: str
"""Fully qualified name of the packed parameter."""
logical_fqns: tuple[str, ...]
"""Fully qualified canonical names of the parameters it packs, in packing order."""
parameter: nn.Parameter
spec: PackedParameterSpec
def get_model_packed_parameters(model: nn.Module) -> Iterator[PackedParameterInfo]:
"""Yield every packed parameter in the model with the canonical names it stands in for."""
for module_path, module in model.named_modules():
for spec in getattr(module, "packed_parameter_specs", ()):
fqn = resolve_fqn(model, join_module_path(module_path, spec.name))
prefix = fqn.removesuffix(spec.name)
yield PackedParameterInfo(
fqn=fqn,
logical_fqns=tuple(f"{prefix}{logical_name}" for logical_name in spec.logical_names),
parameter=module.get_parameter(spec.name),
spec=spec,
)
def get_fsdp_shard_placement_fn(model: nn.Module) -> Callable[[nn.Parameter], Shard | None]:
"""FSDP placement that keeps every packed parameter's packing dimension unsharded.
Splitting a DTensor along an unsharded dimension is a local view, so the canonical
state-dict entries alias the packed storage instead of being replicated copies. FSDP's
default ``Shard(0)`` is kept for everything else, including parameters packed along
dim 0 that have no other dimension to shard.
"""
packing_dim_by_param_id = {
id(packed_info.parameter): packed_info.spec.dim for packed_info in get_model_packed_parameters(model)
}
def shard_placement_fn(parameter: nn.Parameter) -> Shard | None:
if packing_dim_by_param_id.get(id(parameter)) == 0 and parameter.ndim > 1:
return Shard(1)
return None
return shard_placement_fn
def write_back_loaded_packed_parameters(model: nn.Module, state_dict: dict[str, torch.Tensor]) -> None:
"""Write the logical entries of a state dict loaded in place back into the packed parameters.
Loading into ``model.state_dict()`` in place only reaches a packed parameter through
entries that alias it, so the entries that are copies are packed and written back here.
"""
with torch.no_grad():
for packed_info in get_model_packed_parameters(model):
packed_info.parameter.copy_(
packed_info.spec.pack_logical_tensors([state_dict[fqn] for fqn in packed_info.logical_fqns])
)
def split_packed_optimizer_state_for_checkpoint(model: nn.Module, state_dict: dict[str, Any]) -> dict[str, Any]:
"""Expose packed optimizer tensors under their logical names for DCP."""
# DCP returns {} when no optimizers are supplied, including model-only loads.
if not state_dict:
return state_dict
packed_infos = list(get_model_packed_parameters(model))
if not packed_infos:
return state_dict
checkpoint_state_dict = dict(state_dict)
checkpoint_state_dict["state"] = dict(state_dict["state"])
checkpoint_state_dict["param_groups"] = [
{**group, "params": list(group["params"])} for group in state_dict["param_groups"]
]
for packed_info in packed_infos:
if packed_info.fqn in checkpoint_state_dict["state"]:
packed_param_state = checkpoint_state_dict["state"].pop(packed_info.fqn)
logical_param_states: dict[str, dict[str, Any]] = {fqn: {} for fqn in packed_info.logical_fqns}
for state_key, value in packed_param_state.items():
if isinstance(value, torch.Tensor) and value.shape == packed_info.parameter.shape:
for fqn, logical_view in zip(
packed_info.logical_fqns, packed_info.spec.split_into_logical_views(value)
):
logical_param_states[fqn][state_key] = logical_view
else:
for logical_param_state in logical_param_states.values():
logical_param_state[state_key] = value
checkpoint_state_dict["state"].update(logical_param_states)
for group in checkpoint_state_dict["param_groups"]:
param_fqns = []
for param_fqn in group["params"]:
param_fqns.extend(packed_info.logical_fqns if param_fqn == packed_info.fqn else [param_fqn])
group["params"] = param_fqns
return checkpoint_state_dict
def write_back_loaded_packed_optimizer_state(
model: nn.Module, optimizers: Sequence[torch.optim.Optimizer], checkpoint_state_dict: dict[str, Any]
) -> None:
"""Pack the logical optimizer state DCP loaded in place into the optimizers' live state."""
packed_infos = {id(packed_info.parameter): packed_info for packed_info in get_model_packed_parameters(model)}
with torch.no_grad():
for optimizer in optimizers:
for parameter, state in optimizer.state.items():
packed_info = packed_infos.get(id(parameter))
if packed_info is None:
continue
logical_param_states = [checkpoint_state_dict["state"][fqn] for fqn in packed_info.logical_fqns]
for state_key, value in state.items():
loaded_value = logical_param_states[0][state_key]
if isinstance(value, torch.Tensor) and value.shape == packed_info.parameter.shape:
loaded_value = packed_info.spec.pack_logical_tensors(
[logical_param_state[state_key] for logical_param_state in logical_param_states]
)
if isinstance(value, torch.Tensor):
value.copy_(loaded_value)
else:
state[state_key] = loaded_value
def join_loaded_optimizer_state_for_runtime(
model: nn.Module,
checkpoint_state_dict: dict[str, Any],
runtime_state_dict: dict[str, Any],
) -> dict[str, Any]:
"""Pack the logical optimizer state DCP loaded back into the runtime optimizer state."""
if not checkpoint_state_dict:
return checkpoint_state_dict
packed_infos = list(get_model_packed_parameters(model))
if not packed_infos:
return checkpoint_state_dict
restored_state_dict = dict(runtime_state_dict)
restored_state_dict["state"] = dict(runtime_state_dict["state"])
restored_state_dict["param_groups"] = [
{**group, "params": list(group["params"])} for group in checkpoint_state_dict["param_groups"]
]
for packed_info in packed_infos:
if packed_info.fqn in restored_state_dict["state"]:
packed_param_state = restored_state_dict["state"][packed_info.fqn]
logical_param_states = [checkpoint_state_dict["state"][fqn] for fqn in packed_info.logical_fqns]
first_logical_view = packed_info.spec.split_into_logical_views(packed_info.parameter)[0]
for state_key, value in logical_param_states[0].items():
if isinstance(value, torch.Tensor) and value.shape == first_logical_view.shape:
with torch.no_grad():
packed_param_state[state_key].copy_(
packed_info.spec.pack_logical_tensors(
[logical_param_state[state_key] for logical_param_state in logical_param_states]
)
)
else:
packed_param_state[state_key] = value
for group in restored_state_dict["param_groups"]:
param_fqns = group["params"]
if packed_info.logical_fqns[0] not in param_fqns:
continue
first_logical_index = min(param_fqns.index(fqn) for fqn in packed_info.logical_fqns)
group["params"] = [fqn for fqn in param_fqns if fqn not in packed_info.logical_fqns]
group["params"].insert(first_logical_index, packed_info.fqn)
return restored_state_dict
@@ -130,9 +130,7 @@ class LagunaFlashAttention(FlashAttention):
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states)
key_states = self.k_proj(hidden_states)
value_states = self.v_proj(hidden_states)
query_states, key_states, value_states = self.project_qkv(hidden_states)
if self.use_qk_norm and self.qk_norm_type == "per_layer":
query_states = self.q_norm(query_states)
+19 -11
View File
@@ -5,6 +5,8 @@ from typing import Literal
import torch
from torch import nn
from prime_rl.trainer.models.fusions import fuse_qkv_projections
from .norms import RMSNorm, RMSNormConfig
from .rotary_emb import apply_rotary_pos_emb
@@ -48,6 +50,8 @@ class AttentionConfig:
class FlashAttention(nn.Module):
"""Flash Attention"""
supported_fusions = {"qkv": fuse_qkv_projections}
_funcs = {
2: flash_attn_varlen_func,
3: flash_attn_3_varlen_func,
@@ -61,15 +65,15 @@ class FlashAttention(nn.Module):
self.scaling = self.head_dim**-0.5
self.is_causal = config.is_causal
self.q_proj = nn.Linear(
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
)
self.k_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.v_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
self.qkv_sizes = (
config.num_attention_heads * self.head_dim,
config.num_key_value_heads * self.head_dim,
config.num_key_value_heads * self.head_dim,
)
self.q_proj = nn.Linear(config.hidden_size, self.qkv_sizes[0], bias=config.attention_bias)
self.k_proj = nn.Linear(config.hidden_size, self.qkv_sizes[1], bias=config.attention_bias)
self.v_proj = nn.Linear(config.hidden_size, self.qkv_sizes[2], bias=config.attention_bias)
self.register_module("qkv_proj", None)
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.output_bias)
self.use_qk_norm = config.use_qk_norm
self.qk_norm_type = config.qk_norm_type
@@ -91,6 +95,12 @@ class FlashAttention(nn.Module):
if self._flash_attn_version == 4:
self._flash_attn_call = torch._dynamo.disable(self.func)
def project_qkv(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Query, key and value projections, from one packed GEMM when qkv is fused."""
if self.qkv_proj is None:
return self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states)
return self.qkv_proj(hidden_states).split(self.qkv_sizes, dim=-1)
def _compute_attention(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, cu_seqlens, max_seqlen):
"""Run the flash attention kernel. q/k/v are [total_tokens, heads, dim]."""
kwargs: dict = {"causal": True}
@@ -119,9 +129,7 @@ class FlashAttention(nn.Module):
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states)
key_states = self.k_proj(hidden_states)
value_states = self.v_proj(hidden_states)
query_states, key_states, value_states = self.project_qkv(hidden_states)
if self.use_qk_norm and self.qk_norm_type == "per_layer":
query_states = self.q_norm(query_states)
+30 -12
View File
@@ -13,6 +13,7 @@ from torch import nn
from torch.distributed.tensor import DTensor
from prime_rl.trainer.distributed.token_dispatcher import LocalTokenDispatcher, TokenDispatcher
from prime_rl.trainer.models.fusions import fuse_gate_up_projections
from prime_rl.trainer.models.layers.activations import ActivationDispatch, ActivationType
from prime_rl.trainer.models.layers.grouped_gemm import BF16GroupedGemm, GroupedGemm
from prime_rl.trainer.models.layers.mlp import ExpertType, FeedForward
@@ -82,6 +83,8 @@ def broadcast_expert_bias(
class GroupedExperts(nn.Module):
supported_fusions = {"gate_up": fuse_gate_up_projections}
def __init__(
self,
dim: int,
@@ -98,6 +101,7 @@ class GroupedExperts(nn.Module):
self.hidden_dim = hidden_dim
self.gate_proj = nn.Parameter(torch.empty(num_experts, hidden_dim, dim)) if expert_type == "gated" else None
self.up_proj = nn.Parameter(torch.empty(num_experts, hidden_dim, dim))
self.register_parameter("gate_up_proj", None)
self.down_proj = nn.Parameter(torch.empty(num_experts, dim, hidden_dim))
self.gate_proj_bias = (
nn.Parameter(torch.empty(num_experts, hidden_dim)) if bias and self.gate_proj is not None else None
@@ -107,6 +111,8 @@ class GroupedExperts(nn.Module):
self.grouped_gemm = grouped_gemm or BF16GroupedGemm()
self.activation = ActivationDispatch[activation]
if expert_type == "non_gated":
self.supported_fusions = {}
@property
def token_group_alignment(self) -> int:
@@ -128,19 +134,26 @@ class GroupedExperts(nn.Module):
offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32)
x_bf16 = x.bfloat16()
up_proj = to_local(self.up_proj).transpose(-2, -1)
up = self.grouped_gemm(x_bf16, up_proj.bfloat16(), offs=offsets)
if self.gate_up_proj is None:
up_proj = to_local(self.up_proj).transpose(-2, -1)
up = self.grouped_gemm(x_bf16, up_proj.bfloat16(), offs=offsets)
gate = None
if self.gate_proj is not None:
gate_proj = to_local(self.gate_proj).transpose(-2, -1)
gate = self.grouped_gemm(x_bf16, gate_proj.bfloat16(), offs=offsets)
else:
gate_up_proj = to_local(self.gate_up_proj).transpose(-2, -1)
gate_up = self.grouped_gemm(x_bf16, gate_up_proj.bfloat16(), offs=offsets)
gate, up = gate_up.chunk(2, dim=-1)
if self.up_proj_bias is not None:
up_proj_bias = to_local(self.up_proj_bias)
up = up + broadcast_expert_bias(up_proj_bias, num_tokens_per_expert, up.shape[0]).bfloat16()
gate = None
if self.gate_proj is not None:
gate_proj = to_local(self.gate_proj).transpose(-2, -1)
gate = self.grouped_gemm(x_bf16, gate_proj.bfloat16(), offs=offsets)
if self.gate_proj_bias is not None:
gate_proj_bias = to_local(self.gate_proj_bias)
gate = gate + broadcast_expert_bias(gate_proj_bias, num_tokens_per_expert, gate.shape[0]).bfloat16()
if gate is not None and self.gate_proj_bias is not None:
gate_proj_bias = to_local(self.gate_proj_bias)
gate = gate + broadcast_expert_bias(gate_proj_bias, num_tokens_per_expert, gate.shape[0]).bfloat16()
hidden = self.activation.apply(gate, up)
down_proj = to_local(self.down_proj).transpose(-2, -1)
@@ -151,9 +164,14 @@ class GroupedExperts(nn.Module):
return output.type_as(x)
def init_weights(self, init_std: float):
first_projection = self.gate_proj if self.gate_proj is not None else self.up_proj
nn.init.trunc_normal_(first_projection, mean=0.0, std=0.02)
remaining = (self.up_proj, self.down_proj) if self.gate_proj is not None else (self.down_proj,)
if self.gate_up_proj is None:
first_projection = self.gate_proj if self.gate_proj is not None else self.up_proj
nn.init.trunc_normal_(first_projection, mean=0.0, std=0.02)
remaining = (self.up_proj, self.down_proj) if self.gate_proj is not None else (self.down_proj,)
else:
gate_proj, up_proj = self.gate_up_proj.chunk(2, dim=1)
nn.init.trunc_normal_(gate_proj, mean=0.0, std=0.02)
remaining = (up_proj, self.down_proj)
for weight in remaining:
nn.init.trunc_normal_(weight, mean=0.0, std=init_std)
for bias in (self.gate_proj_bias, self.up_proj_bias, self.down_proj_bias):
+51 -1
View File
@@ -1,9 +1,12 @@
import torch
import torch.distributed as dist
from dion import Muon
from torch import nn
from torch.distributed.device_mesh import DeviceMesh
from torch.optim import SGD, AdamW, Optimizer
from prime_rl.configs.trainer import OptimizerConfig, OptimizerInBackwardOffloadConfig
from prime_rl.trainer.models.fusions import get_model_packed_parameters
from prime_rl.trainer.optim.base import OffloadOptimizer as OffloadOptimizer
from prime_rl.trainer.optim.base import OptimizerLike
from prime_rl.trainer.optim.offload import (
@@ -17,6 +20,33 @@ from prime_rl.trainer.sign_sgd import SignSGD
from prime_rl.utils.logger import get_logger
def _warmup_muon_mesh(mesh: DeviceMesh) -> None:
"""Establish NCCL peer connections before Muon's first optimizer step.
This is a correctness workaround, not an optional performance warm-up:
multi-node GLM-Air training can deadlock on Muon's first bulk all-to-all
without it. Optimizer refactors must preserve this initialization.
"""
# get_group() without a mesh dim is only valid for 1-D meshes; the
# replicate-only world mesh is 2-D and has no single group to warm.
if mesh.ndim != 1:
return
group = mesh.get_group()
size = dist.get_world_size(group)
if size <= 1 or dist.get_backend(group) != "nccl":
return
get_logger().info(f"Warming Muon all-to-all connections on group {group.group_name} ({size} ranks)")
device = torch.device("cuda", torch.cuda.current_device())
# Use a bulk list all-to-all, matching Dion's path rather than a scalar
# collective that may leave bulk-transfer peer channels uninitialized.
inputs = [torch.zeros(3 * 1024 * 1024, dtype=torch.bfloat16, device=device) for _ in range(size)]
outputs = [torch.empty_like(tensor) for tensor in inputs]
dist.all_to_all(outputs, inputs, group=group, async_op=True).wait()
torch.cuda.synchronize()
get_logger().info(f"Finished warming Muon all-to-all connections on group {group.group_name}")
def setup_optimizer(
config: OptimizerConfig,
named_params: list[tuple[str, nn.Parameter]],
@@ -54,6 +84,7 @@ def setup_optimizer(
optimizer_named_params,
parallel_dims,
fused_adamw=config.type == "adamw" and not cpu_offload,
model=model,
)
if full_offload_config is not None:
@@ -80,6 +111,7 @@ def _create_optimizer(
parallel_dims: ParallelDims,
lr: float | None = None,
fused_adamw: bool = False,
model: nn.Module | None = None,
) -> Optimizer:
"""Create optimizer. If lr is None, uses config.lr."""
if lr is None:
@@ -107,7 +139,7 @@ def _create_optimizer(
fused=fused_adamw,
)
case "muon":
return _create_muon_optimizer(config, named_params, parallel_dims, lr)
return _create_muon_optimizer(config, named_params, parallel_dims, model, lr)
case "sign_sgd":
return SignSGD(
params=trainable_params,
@@ -120,6 +152,7 @@ def _create_muon_optimizer(
config: OptimizerConfig,
named_params: list[tuple[str, nn.Parameter]],
parallel_dims: ParallelDims,
model: nn.Module | None,
lr: float | None = None,
) -> Optimizer:
def muon_enabled(n, p):
@@ -185,8 +218,20 @@ def _create_muon_optimizer(
else:
distributed_mesh = parallel_dims.world_mesh
# Runtime fusions pack several logical matrices into one physical parameter. Muon
# orthogonalizes each of them separately, so a packed parameter trains exactly as the
# matrices it replaces would. Packed biases and frozen parameters are not Muon's.
matrix_partitions = {}
if model is not None:
muon_params = {p for group in param_groups if group["algorithm"] == "muon" for p in group["params"]}
for packed_info in get_model_packed_parameters(model):
partitions = packed_info.spec.muon_matrix_partitions(packed_info.parameter)
if partitions is not None and packed_info.parameter in muon_params:
matrix_partitions[packed_info.parameter] = partitions
optimizer = Muon(
params=param_groups,
matrix_partitions=matrix_partitions,
lr=lr,
mu=config.mu,
betas=(config.betas1, config.betas2),
@@ -196,4 +241,9 @@ def _create_muon_optimizer(
world_mesh=parallel_dims.world_mesh,
fsdp_mesh_dim=1 if parallel_dims.dp_replicate_enabled else 0,
)
# Keep both warm-ups after Muon construction and before its first step. The
# main and expert groups establish independent NCCL peer connections.
_warmup_muon_mesh(distributed_mesh)
if expert_params and parallel_dims.ep_enabled:
_warmup_muon_mesh(parallel_dims.get_mesh("dp_shard_mod_ep"))
return optimizer
+2 -1
View File
@@ -114,7 +114,8 @@ def train(config: TrainerConfig):
# Set precision
setup_torch_distributed(
timeout=timedelta(seconds=config.dist_timeout_seconds), enable_gloo=config.model.fsdp_cpu_offload
timeout=timedelta(seconds=config.dist_timeout_seconds),
enable_gloo=config.model.fsdp_cpu_offload or config.model.full_offload is not None,
)
if config.model.full_offload is not None:
setup_full_cpu_optimizer_offload(config.model.full_offload)
+2 -1
View File
@@ -100,7 +100,8 @@ def train(config: SFTConfig):
# Set precision
setup_torch_distributed(
timeout=timedelta(seconds=config.dist_timeout_seconds), enable_gloo=config.model.fsdp_cpu_offload
timeout=timedelta(seconds=config.dist_timeout_seconds),
enable_gloo=config.model.fsdp_cpu_offload or config.model.full_offload is not None,
)
if config.model.full_offload is not None:
setup_full_cpu_optimizer_offload(config.model.full_offload)
+5 -5
View File
@@ -1,9 +1,9 @@
from pathlib import Path
import torch
from httpx import AsyncClient
from prime_rl.configs.trainer import LoRAConfig, WeightBroadcastConfig
from prime_rl.orchestrator.clients import AdminPlane
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.transports.weights.base import WeightReceiver, WeightSender, prune_broadcasts_beyond
from prime_rl.transports.weights.filesystem import FileSystemWeightReceiver, FileSystemWeightSender
@@ -38,14 +38,14 @@ def setup_weight_sender(
def setup_weight_receiver(
broadcast_dir: Path,
config: WeightBroadcastConfig,
admin_clients: list[AsyncClient],
admin_plane: AdminPlane,
model_name: str,
) -> WeightReceiver:
if config.type == "nccl":
return NCCLWeightReceiver(broadcast_dir, config, admin_clients, model_name)
return NCCLWeightReceiver(broadcast_dir, config, admin_plane, model_name)
elif config.type == "filesystem":
return FileSystemWeightReceiver(broadcast_dir, config, admin_clients, model_name)
return FileSystemWeightReceiver(broadcast_dir, config, admin_plane, model_name)
elif config.type == "nixl":
return NIXLWeightReceiver(broadcast_dir, config, admin_clients, model_name)
return NIXLWeightReceiver(broadcast_dir, config, admin_plane, model_name)
else:
raise ValueError(f"Invalid weight broadcast type: {config.type}")
+4 -4
View File
@@ -7,9 +7,9 @@ from pathlib import Path
from typing import final
import torch.nn as nn
from httpx import AsyncClient
from prime_rl.configs.trainer import WeightBroadcastConfig
from prime_rl.orchestrator.clients import AdminPlane
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.pathing import get_all_ckpt_steps, get_broadcast_dir, get_step_path
@@ -115,19 +115,19 @@ class WeightReceiver(ABC):
watcher, the orchestrator's startup rendezvous, and the evals process all
drive the same object instead of hand-rolling transport branches. The
engines' in-process receive hooks are its data plane, reached through the
admin clients."""
admin plane."""
def __init__(
self,
broadcast_dir: Path,
config: WeightBroadcastConfig,
admin_clients: list[AsyncClient],
admin_plane: AdminPlane,
model_name: str,
) -> None:
self.logger = get_logger()
self.broadcast_dir = broadcast_dir
self.config = config
self.admin_clients = admin_clients
self.admin_plane = admin_plane
self.model_name = model_name
async def initialize(self) -> None:
@@ -5,7 +5,7 @@ import torch.nn as nn
from torch.distributed.tensor import DTensor
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig, LoRAConfig
from prime_rl.orchestrator.clients import load_lora_adapter, update_weights
from prime_rl.orchestrator.clients import load_lora_adapter
from prime_rl.trainer.lora import get_lora_state, save_lora_config
from prime_rl.transports.weights.base import FINISHED_MARKER, WeightReceiver, WeightSender
from prime_rl.utils.pathing import wait_for_path
@@ -70,6 +70,6 @@ class FileSystemWeightReceiver(WeightReceiver):
self._ack(step)
await wait_for_path(weights_dir / FINISHED_MARKER)
if (weights_dir / "adapter_config.json").exists():
await load_lora_adapter(self.admin_clients, self.model_name, weights_dir)
await load_lora_adapter(self.admin_plane, self.model_name, weights_dir)
else:
await update_weights(self.admin_clients, weights_dir, step=step)
await self.admin_plane.update_weights(weights_dir, transport="filesystem", step=step)
+29 -16
View File
@@ -1,6 +1,6 @@
import pickle
from pathlib import Path
from typing import Callable, Generator, cast
from typing import Callable, Generator
import torch
import torch.distributed as dist
@@ -11,7 +11,6 @@ from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
from vllm.distributed.utils import StatelessProcessGroup
from prime_rl.configs.trainer import NCCLWeightBroadcastConfig
from prime_rl.orchestrator.clients import init_nccl_broadcast, update_weights
from prime_rl.trainer.conversion_utils import get_max_layer_num
from prime_rl.trainer.models import PreTrainedModelPrimeRL
from prime_rl.trainer.utils import get_world
@@ -19,6 +18,7 @@ from prime_rl.transports.weights.base import WeightReceiver, WeightSender
from prime_rl.utils.logger import get_logger
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable
from prime_rl.utils.vlm import get_layer_prefix
from prime_rl.utils.weights import resolve_wire_dtype
def broadcast_integer(integer: int, communicator: PyNcclCommunicator) -> None:
@@ -81,6 +81,25 @@ def filter_state_dict_by_layers(
)
def resolve_dtensors(
state_dict: dict[str, Tensor],
keep_in_fp32: Callable[[str], bool] | None,
default_dtype: torch.dtype,
) -> dict[str, Tensor]:
"""Replace every sharded tensor with its full tensor, at the dtype it goes on the wire in.
Only DTensors are touched, since only they need gathering. A buffer is never sharded, so it
goes on the wire in whatever dtype it already holds and its fp32 declaration, if it has one,
is never consulted. TODO: NIXL transport does not use this function; unify logic.
"""
for key, value in list(state_dict.items()):
if isinstance(value, DTensor):
# only gather after the downcast as it will be faster
target_dtype = resolve_wire_dtype(keep_in_fp32, key, default_dtype)
state_dict[key] = value.to(target_dtype).full_tensor()
return state_dict
def preprocess_layer_checkpoint(
model: nn.Module,
layer_state_dict: dict[str, Tensor],
@@ -150,18 +169,13 @@ class NCCLBroadcaster:
else:
preprocess_fn = preprocess_layer_checkpoint
keep_in_fp32 = getattr(model, "keep_in_fp32_for_weight_transfer", None)
for layer_id, layer_state_dict in filter_state_dict_by_layers(state_dict, num_layers, layer_prefix):
layer_state_dict = self._resolve_dtensors(layer_state_dict)
layer_state_dict = resolve_dtensors(layer_state_dict, keep_in_fp32, self.dtype)
layer_state_dict = preprocess_fn(model, layer_state_dict, layer_id)
if self.world.is_master:
broadcast_state_dict(layer_state_dict, self.communicator)
def _resolve_dtensors(self, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
for key, value in list(state_dict.items()):
if isinstance(value, DTensor):
state_dict[key] = cast(DTensor, value.to(self.dtype)).full_tensor()
return state_dict
class NCCLWeightSender(WeightSender):
"""Broadcast weights into the inference engine using NCCL."""
@@ -202,19 +216,18 @@ class NCCLWeightReceiver(WeightReceiver):
marker."""
async def initialize(self) -> None:
await init_nccl_broadcast(
self.admin_clients,
self.config.host,
self.config.port,
self.config.timeout,
await self.admin_plane.initialize_nccl(
host=self.config.host,
port=self.config.port,
timeout=self.config.timeout,
inference_world_size=self.config.inference_world_size,
quantize_in_weight_transfer=self.config.quantize_in_weight_transfer,
)
async def receive(self, step: int) -> None:
await update_weights(
self.admin_clients,
await self.admin_plane.update_weights(
self.step_dir(step),
transport="nccl",
step=step,
on_paused=lambda: self._ack(step),
)
+3 -3
View File
@@ -20,7 +20,7 @@ from torch.distributed.tensor import DTensor
from torch.distributed.tensor._utils import compute_local_shape_and_global_offset
from prime_rl.configs.trainer import NIXLWeightBroadcastConfig
from prime_rl.orchestrator.clients import init_nixl_broadcast, update_weights
from prime_rl.orchestrator.clients import init_nixl_broadcast
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.transports.weights.base import WeightReceiver, WeightSender
@@ -465,7 +465,7 @@ class NIXLWeightReceiver(WeightReceiver):
async def initialize(self) -> None:
await init_nixl_broadcast(
self.admin_clients,
self.admin_plane,
self.config.host,
self.config.port,
self.config.timeout,
@@ -495,7 +495,7 @@ class NIXLWeightReceiver(WeightReceiver):
policy_notification(step, "ready"),
timeout=self.config.timeout,
)
await update_weights(self.admin_clients, None, step=step)
await self.admin_plane.update_weights(None, transport="nixl", step=step)
self.nixl_agent.send_notification(
trainer_peer,
policy_notification(step, "complete"),
+12 -3
View File
@@ -2,7 +2,7 @@ import json
import re
import warnings
from pathlib import Path
from typing import cast
from typing import Callable, cast
import torch
import torch.distributed as dist
@@ -18,7 +18,6 @@ from transformers.utils import (
SAFE_WEIGHTS_NAME,
)
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
@@ -98,6 +97,8 @@ def convert_state_dict_to_hf(model: nn.Module, state_dict: dict[str, Tensor]) ->
Format detection uses the model's full key set, so a partial dict (one rank's
slice) converts the same way as the full state dict would.
"""
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
full_keys = dict.fromkeys(resolve_fqn(model, key) for key in model.state_dict().keys())
if isinstance(model, PreTrainedModelPrimeRL) and model.is_prime_state_dict(full_keys):
# PrimeRL custom model holding weights in prime format: apply the model's
@@ -150,6 +151,14 @@ def partition_weights(state_dict: dict[str, Tensor], world_size: int, dtype: tor
return {key: unit_owner[unit] for key, unit in key_to_unit.items()}
def resolve_wire_dtype(keep_in_fp32: Callable[[str], bool] | None, key: str, default: torch.dtype) -> torch.dtype:
"""The dtype a tensor must travel to the inference engine in.
TODO: NIXL keeps its own inline copy of this rule; unify the handling.
"""
return torch.float32 if keep_in_fp32 is not None and keep_in_fp32(key) else default
def gather_weights_parallel(model: nn.Module, dtype: torch.dtype = torch.bfloat16) -> dict[str, Tensor]:
"""Gather distributed weights cooperatively, each rank keeping a slice on CPU.
@@ -177,7 +186,7 @@ def gather_weights_parallel(model: nn.Module, dtype: torch.dtype = torch.bfloat1
for key, value in model.state_dict().items():
if isinstance(value, DTensor):
# only gather after the downcast to dtype as it will be faster
target_dtype = torch.float32 if keep_in_fp32 is not None and keep_in_fp32(key) else dtype
target_dtype = resolve_wire_dtype(keep_in_fp32, key, dtype)
value = cast(DTensor, value.to(target_dtype)).full_tensor()
if owners[key] != world.rank:
continue
+14
View File
@@ -127,6 +127,20 @@ def check_dashboard_smoke(output_dir: Path, run_name: str) -> None:
assert entries > 0, "episode viewer rendered no messages"
reward = page.locator(".tm-reward-big").first.inner_text()
assert reward not in ("", "n/a"), f"episode reward did not render: {reward!r}"
page.click("#tm-view [data-view=replay]")
page.wait_for_timeout(250)
assert page.locator(".replay-shell").count() == 1, "terminal replay did not render"
assert page.locator("#replay-output .replay-event").count() > 0, "terminal replay showed no events"
assert page.locator("#replay-speed").input_value() == "8"
page.check("#replay-skip-inference")
assert "inference skipped" in page.locator("#replay-timing-badge").inner_text()
assert page.locator("#replay-show-thinking").is_checked()
page.keyboard.press("t")
assert not page.locator("#replay-show-thinking").is_checked()
page.keyboard.press("Home")
assert page.locator("#replay-top").get_attribute("class").find("active") >= 0
page.keyboard.press("End")
assert page.locator("#replay-live").get_attribute("class").find("active") >= 0
page.keyboard.press("Escape")
# logs: the merged pane shows lines
@@ -213,6 +213,93 @@ def test_assign_advantages_full_length_stream():
assert trace_to_samples(trace)[0].advantages == [0.0, 0.0, 0.5, -0.5, 0.0, 1.0]
def test_compaction_retries_train_only_causally_used_generations():
nodes = [
MessageNode(
parent=None,
message=UserMessage(content="work"),
sampled=False,
token_ids=[1],
mask=[False],
),
MessageNode(
parent=0,
message=AssistantMessage(content="evidence"),
sampled=True,
token_ids=[2],
mask=[True],
logprobs=[-0.1],
),
MessageNode(
parent=1,
message=UserMessage(content="summarize"),
sampled=False,
token_ids=[3],
mask=[False],
),
MessageNode(
parent=2,
semantic_parents=[vf.ParentLink(node=1, type="compaction_attempt")],
message=AssistantMessage(content="rejected tool call"),
sampled=True,
token_ids=[4],
mask=[True],
logprobs=[-0.2],
),
MessageNode(
parent=2,
semantic_parents=[vf.ParentLink(node=1, type="compaction_attempt")],
message=AssistantMessage(content="accepted summary"),
sampled=True,
token_ids=[5],
mask=[True],
logprobs=[-0.3],
),
MessageNode(
parent=None,
message=UserMessage(content="compacted context"),
sampled=False,
token_ids=[6],
mask=[False],
),
MessageNode(
parent=5,
semantic_parents=[vf.ParentLink(node=4, type="compaction")],
message=AssistantMessage(content="answer"),
sampled=True,
token_ids=[7],
mask=[True],
logprobs=[-0.4],
),
]
trace = vf.Trace(
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=0, prompt=None)),
agent=vf.AgentInfo(config=vf.AgentConfig()),
nodes=nodes,
rewards={},
ok=True,
)
branches = {branch.nodes[-1].message.content: branch for branch in trace.branches}
assert branches["rejected tool call"].trainable is False
assert branches["accepted summary"].trainable is True
assert branches["answer"].trainable is True
assign_advantages(trace, 1.0)
assert trace.nodes[1].advantages == [1.0]
assert trace.nodes[3].advantages is None
assert trace.nodes[4].advantages == [1.0]
assert trace.nodes[6].advantages == [1.0]
trainable_ids = [
token_id
for sample in trace_to_samples(trace)
for token_id, trainable in zip(sample.token_ids, sample.mask, strict=True)
if trainable
]
assert sorted(trainable_ids) == [2, 5, 7]
def test_assign_advantages_slices_across_nodes():
trace = _make_episode().traces[0]
assign_advantages(trace, [1.0, 2.0, 3.0])
+40 -2
View File
@@ -6,7 +6,13 @@ import httpx
from verifiers.v1.configs.client import EvalClientConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.orchestrator.clients import _is_retryable_lora_error, check_health, load_lora_adapter, setup_client
from prime_rl.orchestrator.clients import (
AdminPlane,
_is_retryable_lora_error,
check_health,
load_lora_adapter,
setup_client,
)
def test_is_retryable_lora_error_returns_true_for_404():
@@ -36,11 +42,12 @@ def test_is_retryable_lora_error_returns_false_for_non_http_error():
def test_load_lora_adapter_succeeds_on_first_attempt():
mock_client = AsyncMock()
admin_plane = MagicMock(clients=[mock_client])
mock_response = MagicMock()
mock_response.raise_for_status = MagicMock()
mock_client.post.return_value = mock_response
asyncio.run(load_lora_adapter([mock_client], "test-lora", Path("/test/path")))
asyncio.run(load_lora_adapter(admin_plane, "test-lora", Path("/test/path")))
mock_client.post.assert_called_once_with(
"/load_lora_adapter",
@@ -49,6 +56,37 @@ def test_load_lora_adapter_succeeds_on_first_attempt():
)
def test_admin_plane_initializes_nccl():
admin_plane = AdminPlane(ClientConfig())
client = AsyncMock()
response = MagicMock()
response.raise_for_status.return_value = None
client.post.return_value = response
admin_plane.clients = [client]
asyncio.run(
admin_plane.initialize_nccl(
host="trainer",
port=29501,
timeout=1200,
inference_world_size=1,
)
)
client.post.assert_awaited_once_with(
"/init_broadcaster",
json={
"host": "trainer",
"port": 29501,
"rank_offset": 0,
"inference_world_size": 1,
"timeout": 1200,
"quantize_in_weight_transfer": False,
},
)
asyncio.run(admin_plane.aclose())
def test_setup_client_creates_renderer_client():
from renderers import Qwen3VLRendererConfig
+276
View File
@@ -0,0 +1,276 @@
from prime_rl.dashboard.server import project_episode_timeline
def _node(
parent: int | None,
timestamp: float,
semantic_parents: list[dict] | None = None,
message: dict | None = None,
) -> dict:
return {
"parent": parent,
"semantic_parents": semantic_parents or [],
"timestamp": timestamp,
"message": message or {"role": "assistant", "content": f"node {timestamp}"},
}
def _call(
node: int,
start: float,
end: float,
*,
prompt_tokens: int = 100,
cached_tokens: int = 20,
) -> dict:
return {
"node": node,
"time": {"start": start, "end": end},
"usage": {
"prompt_tokens": prompt_tokens,
"cached_input_tokens": cached_tokens,
"completion_tokens": 10,
},
}
def _episode(nodes: list[dict], calls: list[dict]) -> dict:
return {
"traces": [
{
"nodes": nodes,
"calls": calls,
"is_completed": True,
"agent": {"name": "root", "config": {"model": "test-model"}},
"timing": {"agent": {"start": 0.0, "end": 10.0}},
}
]
}
def test_semantic_timeline_projects_concurrent_fork_join() -> None:
nodes = [
_node(None, 0.0),
_node(0, 2.0),
_node(0, 4.0, [{"node": 1, "type": "subagent_call"}]),
_node(0, 4.1, [{"node": 1, "type": "subagent_call"}]),
_node(
1,
7.0,
[
{"node": 1, "type": "continuation"},
{"node": 2, "type": "subagent_return"},
{"node": 3, "type": "subagent_return"},
{"node": 2, "type": "vendor:review"},
],
),
]
calls = [
_call(1, 1.0, 2.0),
_call(2, 3.0, 4.0),
_call(3, 3.1, 4.1),
_call(4, 6.0, 7.0),
]
timeline = project_episode_timeline(_episode(nodes, calls))
assert [lane["label"] for lane in timeline["semantic_lanes"]] == [
"root",
"root · context 0",
"subagent 1 · context 0",
"subagent 2 · context 0",
]
assert [lane["usage"]["model_calls"] for lane in timeline["semantic_lanes"][1:]] == [
2,
1,
1,
]
assert [lane["usage"]["total_tokens"] for lane in timeline["semantic_lanes"][1:]] == [
260,
130,
130,
]
assert [lane["usage"]["latest_context_tokens"] for lane in timeline["semantic_lanes"][1:]] == [
120,
120,
120,
]
assert [lane["context"] for lane in timeline["semantic_lanes"][1:]] == [
{"agent": "root", "index": 0},
{"agent": "subagent 1", "index": 0},
{"agent": "subagent 2", "index": 0},
]
assert [edge["type"] for edge in timeline["semantic_edges"]] == [
"subagent_call",
"subagent_call",
"continuation",
"subagent_return",
"subagent_return",
"vendor:review",
]
def test_semantic_timeline_starts_new_context_after_compaction() -> None:
nodes = [
_node(None, 0.0),
_node(0, 2.0),
_node(1, 4.0, [{"node": 1, "type": "continuation"}]),
_node(2, 6.0, [{"node": 2, "type": "compaction"}]),
]
calls = [
_call(1, 1.0, 2.0, prompt_tokens=150),
_call(2, 3.0, 4.0),
_call(3, 5.0, 6.0, prompt_tokens=50, cached_tokens=10),
]
timeline = project_episode_timeline(_episode(nodes, calls))
assert [lane["label"] for lane in timeline["semantic_lanes"]] == [
"root",
"root · context 0",
"root · context 1",
]
assert [lane["usage"]["model_calls"] for lane in timeline["semantic_lanes"][1:]] == [
2,
1,
]
assert [lane["usage"]["total_tokens"] for lane in timeline["semantic_lanes"][1:]] == [
310,
70,
]
assert [lane["usage"]["latest_context_tokens"] for lane in timeline["semantic_lanes"][1:]] == [
120,
60,
]
assert [lane["usage"]["max_context_tokens"] for lane in timeline["semantic_lanes"][1:]] == [
170,
60,
]
assert [lane["context"] for lane in timeline["semantic_lanes"][1:]] == [
{"agent": "root", "index": 0},
{"agent": "root", "index": 1},
]
assert [edge["type"] for edge in timeline["semantic_edges"]] == [
"continuation",
"compaction",
]
def test_semantic_timeline_keeps_rejected_and_accepted_compaction_attempts() -> None:
nodes = [
_node(None, 0.0),
_node(0, 2.0),
_node(1, 4.0, [{"node": 1, "type": "compaction_attempt"}]),
_node(1, 5.0, [{"node": 1, "type": "compaction_attempt"}]),
_node(0, 7.0, [{"node": 3, "type": "compaction"}]),
]
nodes[2]["mask"] = [True]
nodes[3]["mask"] = [True]
calls = [
_call(1, 1.0, 2.0),
_call(2, 3.0, 4.0),
_call(3, 4.0, 5.0),
_call(4, 6.0, 7.0),
]
timeline = project_episode_timeline(_episode(nodes, calls))
attempts = [lane for lane in timeline["semantic_lanes"] if lane.get("compaction_attempt")]
assert [attempt["compaction_attempt"]["accepted"] for attempt in attempts] == [
False,
True,
]
assert [attempt["spans"][1]["trainable"] for attempt in attempts] == [
True,
True,
]
assert [attempt["context"] for attempt in attempts] == [
{"agent": "root", "index": 0},
{"agent": "root", "index": 0},
]
assert timeline["semantic_lanes"][-1]["context"] == {
"agent": "root",
"index": 1,
}
def test_semantic_timeline_falls_back_to_physical_only() -> None:
nodes = [_node(None, 0.0), _node(0, 2.0)]
timeline = project_episode_timeline(_episode(nodes, [_call(1, 1.0, 2.0)]))
assert timeline["lanes"]
assert timeline["semantic_lanes"] == []
assert timeline["semantic_edges"] == []
def test_semantic_timeline_recovers_interrupted_tool_continuation() -> None:
nodes = [
_node(None, 0.0),
_node(0, 2.0),
_node(
0,
4.0,
[{"node": 1, "type": "subagent_call"}],
{"role": "assistant", "tool_calls": [{"id": "first-tool"}]},
),
_node(
2,
5.0,
message={"role": "tool", "tool_call_id": "first-tool", "content": "result"},
),
_node(
3,
6.0,
[{"node": 2, "type": "continuation"}],
{"role": "assistant", "tool_calls": [{"id": "interrupted-tool"}]},
),
_node(
4,
7.0,
message={"role": "tool", "tool_call_id": "interrupted-tool", "content": "result"},
),
_node(5, 8.0),
]
calls = [
_call(1, 1.0, 2.0),
_call(2, 3.0, 4.0),
_call(4, 5.0, 6.0),
_call(6, 7.0, 8.0),
]
timeline = project_episode_timeline(_episode(nodes, calls))
assert [lane["label"] for lane in timeline["semantic_lanes"]] == [
"root",
"root · context 0",
"subagent 1 · context 0",
]
assert timeline["semantic_lanes"][2]["usage"]["model_calls"] == 3
assert timeline["semantic_edges"][-1] == {
"trace_index": 0,
"source_node": 4,
"target_node": 6,
"type": "continuation",
"inferred": True,
}
def test_semantic_timeline_labels_unrecoverable_components_as_unlinked() -> None:
nodes = [
_node(None, 0.0),
_node(0, 2.0),
_node(1, 4.0, [{"node": 1, "type": "continuation"}]),
_node(0, 6.0),
]
timeline = project_episode_timeline(_episode(nodes, [_call(1, 1.0, 2.0), _call(2, 3.0, 4.0), _call(3, 5.0, 6.0)]))
assert [lane["label"] for lane in timeline["semantic_lanes"]] == [
"root",
"root · context 0",
"unlinked 1 · context 0",
]
assert timeline["semantic_lanes"][2]["context"] == {
"agent": "unlinked 1",
"index": 0,
"unlinked": True,
}
+109
View File
@@ -0,0 +1,109 @@
import copy
import pytest
import torch
from torch import nn
from prime_rl.trainer.models.fusions import apply_model_fusions, get_model_packed_parameters
from prime_rl.trainer.models.layers.attn import AttentionConfig, FlashAttention
from prime_rl.trainer.models.layers.moe import GroupedExperts
NUM_EXPERTS, DIM, HIDDEN = 4, 16, 24
NUM_HEADS, NUM_KV_HEADS, HEAD_DIM = 4, 2, 8
def build_experts(expert_type="gated"):
experts = GroupedExperts(dim=DIM, hidden_dim=HIDDEN, num_experts=NUM_EXPERTS, expert_type=expert_type)
for parameter in experts.parameters():
nn.init.normal_(parameter)
return experts
def build_attention(attention_bias=True):
config = AttentionConfig(
hidden_size=DIM,
head_dim=HEAD_DIM,
num_attention_heads=NUM_HEADS,
num_key_value_heads=NUM_KV_HEADS,
is_causal=True,
attention_bias=attention_bias,
use_qk_norm=False,
rms_norm_eps=1e-6,
)
attention = FlashAttention(config)
for parameter in attention.parameters():
nn.init.normal_(parameter)
return attention
def assert_state_dict_stays_canonical(unfused, fusion):
"""Packing a module must not change what its state dict contains, or how it loads."""
fused = copy.deepcopy(unfused)
apply_model_fusions(fused, [fusion])
expected = unfused.state_dict()
assert set(fused.state_dict()) == set(expected)
for name, tensor in expected.items():
assert torch.equal(fused.state_dict()[name], tensor), name
reloaded = copy.deepcopy(unfused)
apply_model_fusions(reloaded, [fusion])
reloaded.load_state_dict(expected)
for packed_info, reloaded_info in zip(get_model_packed_parameters(fused), get_model_packed_parameters(reloaded)):
assert torch.equal(reloaded_info.parameter, packed_info.parameter), packed_info.fqn
return fused
def test_gate_up_packs_the_output_dimension():
fused = assert_state_dict_stays_canonical(build_experts(), "gate_up")
(packed_info,) = get_model_packed_parameters(fused)
assert packed_info.fqn == "gate_up_proj"
assert packed_info.logical_fqns == ("gate_proj", "up_proj")
assert packed_info.parameter.shape == (NUM_EXPERTS, 2 * HIDDEN, DIM)
assert packed_info.spec.muon_matrix_partitions(packed_info.parameter) == (HIDDEN, HIDDEN)
assert fused.gate_proj is None and fused.up_proj is None
def test_qkv_packs_weights_and_biases():
fused = assert_state_dict_stays_canonical(build_attention(), "qkv")
weight, bias = get_model_packed_parameters(fused)
query_size, key_size = NUM_HEADS * HEAD_DIM, NUM_KV_HEADS * HEAD_DIM
assert weight.fqn == "qkv_proj.weight"
assert weight.logical_fqns == ("q_proj.weight", "k_proj.weight", "v_proj.weight")
assert weight.parameter.shape == (query_size + 2 * key_size, DIM)
assert weight.spec.muon_matrix_partitions(weight.parameter) == (query_size, key_size, key_size)
assert bias.fqn == "qkv_proj.bias"
assert bias.logical_fqns == ("q_proj.bias", "k_proj.bias", "v_proj.bias")
# A one-dimensional parameter has no output dimension to partition
assert bias.spec.muon_matrix_partitions(bias.parameter) is None
def test_qkv_without_bias_packs_only_weights():
fused = assert_state_dict_stays_canonical(build_attention(attention_bias=False), "qkv")
assert [packed_info.fqn for packed_info in get_model_packed_parameters(fused)] == ["qkv_proj.weight"]
def test_qkv_projections_match_the_unpacked_ones():
unfused = build_attention()
fused = copy.deepcopy(unfused)
apply_model_fusions(fused, ["qkv"])
hidden_states = torch.randn(1, 8, DIM)
for fused_projection, unfused_projection in zip(
fused.project_qkv(hidden_states), unfused.project_qkv(hidden_states)
):
assert torch.equal(fused_projection, unfused_projection)
def test_unsupported_fusion_fails_loudly():
with pytest.raises(ValueError, match="does not support"):
apply_model_fusions(build_experts(), ["qkv"])
assert apply_model_fusions(build_experts(), ["qkv"], raise_on_fail=False) == {}
def test_non_gated_experts_have_nothing_to_pack():
with pytest.raises(ValueError, match="does not support"):
apply_model_fusions(build_experts(expert_type="non_gated"), ["gate_up"])
+44
View File
@@ -0,0 +1,44 @@
import pytest
import torch
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4ForCausalLM
from prime_rl.trainer.models.glm4_moe import Glm4MoeForCausalLM
from prime_rl.trainer.models.glm_moe_dsa import GlmMoeDsaForCausalLM
from prime_rl.trainer.models.nemotron_h import NemotronHForCausalLM
from prime_rl.trainer.models.qwen3_5 import Qwen3_5ForCausalLM
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeForCausalLM
from prime_rl.utils.weights import resolve_wire_dtype
def test_resolve_wire_dtype():
def keep_in_fp32(key: str) -> bool:
return key.endswith("A_log")
assert resolve_wire_dtype(keep_in_fp32, "layers.0.linear_attn.A_log", torch.bfloat16) is torch.float32
assert resolve_wire_dtype(keep_in_fp32, "layers.0.self_attn.q_proj.weight", torch.bfloat16) is torch.bfloat16
# The default is whatever the transport asked for, not hardcoded bf16.
assert resolve_wire_dtype(keep_in_fp32, "layers.0.self_attn.q_proj.weight", torch.float8_e4m3fn) is (
torch.float8_e4m3fn
)
# A plain transformers model declares nothing, so every key takes the default.
assert resolve_wire_dtype(None, "layers.0.linear_attn.A_log", torch.bfloat16) is torch.bfloat16
@pytest.mark.parametrize(
("model_cls", "fp32_key", "ordinary_key"),
[
(NemotronHForCausalLM, "model.layers.0.mamba.A_log", "model.layers.0.mamba.in_proj.weight"),
(Qwen3_5ForCausalLM, "model.layers.0.linear_attn.A_log", "model.layers.0.self_attn.q_proj.weight"),
(Qwen3_5MoeForCausalLM, "model.layers.0.linear_attn.norm.weight", "model.layers.0.mlp.experts.gate_proj"),
(Glm4MoeForCausalLM, "model.layers.0.mlp.router.selection_bias", "model.layers.0.self_attn.q_proj.weight"),
(GlmMoeDsaForCausalLM, "model.layers.0.mlp.router.selection_bias", "model.layers.0.self_attn.q_proj.weight"),
(DeepseekV4ForCausalLM, "model.layers.0.attn_hc.fn", "model.layers.0.self_attn.q_b_proj.weight"),
],
)
def test_declared_keys_travel_in_fp32(model_cls, fp32_key, ordinary_key):
keep_in_fp32 = model_cls.keep_in_fp32_for_weight_transfer
assert resolve_wire_dtype(keep_in_fp32, fp32_key, torch.bfloat16) is torch.float32
assert resolve_wire_dtype(keep_in_fp32, ordinary_key, torch.bfloat16) is torch.bfloat16
Generated
+11 -5
View File
@@ -1433,7 +1433,7 @@ wheels = [
[[package]]
name = "dion"
version = "0.1.0"
source = { git = "https://github.com/samsja/dion.git?rev=d891eeb#d891eebbd950a6ff11d9b5f806282e33df83df9d" }
source = { git = "https://github.com/samsja/dion.git?rev=99e5f7e#99e5f7e5f0a7dbe418ce6dfc84196dba052e67c8" }
dependencies = [
{ name = "numpy" },
{ name = "torch", version = "2.13.0+cu130", source = { registry = "https://download.pytorch.org/whl/cu130" } },
@@ -5092,7 +5092,7 @@ requires-dist = [
{ name = "deep-gemm", marker = "platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl" },
{ name = "deep-gemm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and sys_platform == 'linux' and extra == 'disagg'" },
{ name = "deep-gemm", marker = "platform_machine == 'x86_64' and sys_platform == 'linux' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" },
{ name = "dion", marker = "sys_platform == 'linux' and extra == 'gpu'", git = "https://github.com/samsja/dion.git?rev=d891eeb" },
{ name = "dion", marker = "sys_platform == 'linux' and extra == 'gpu'", git = "https://github.com/samsja/dion.git?rev=99e5f7e" },
{ name = "fastapi", marker = "extra == 'dashboard'", specifier = ">=0.115" },
{ name = "flash-attn", marker = "platform_machine == 'aarch64' and extra == 'flash-attn'", url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.48/flash_attn-2.8.3+cu130torch2.13-cp312-cp312-linux_aarch64.whl" },
{ name = "flash-attn", marker = "platform_machine == 'x86_64' and extra == 'flash-attn'", url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.47/flash_attn-2.8.3+cu130torch2.13-cp312-cp312-linux_x86_64.whl" },
@@ -7648,16 +7648,16 @@ requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
[[package]]
name = "uvicorn"
version = "0.48.0"
version = "0.52.4"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "click", version = "8.4.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
{ name = "click", version = "8.4.2", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
{ name = "h11" },
]
sdist = { url = "https://files.pythonhosted.org/packages/e6/bf/f6544ba992ddb9a6077343a576f9844f7f8f06ab819aefd00206e9255f18/uvicorn-0.48.0.tar.gz", hash = "sha256:a5504207195d08c2511bf9125ede5ac4a4b71725d519e758d01dcf0bc2d31c37", size = 91074, upload-time = "2026-05-24T12:08:41.925Z" }
sdist = { url = "https://files.pythonhosted.org/packages/f2/0f/3f86e61397dd33bf2ccf28188c40db6a740658aeebbbf6e7dbc101a1f487/uvicorn-0.52.4.tar.gz", hash = "sha256:73acfee47a0b133c5de13d219492d62d8a31e935f4fe6e41a232451a15379f86", size = 100627, upload-time = "2026-08-19T06:27:41.821Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/01/be/72532be3da7acc5fdfbccdb95215cd04f995a0886532a5b423f929cda4cc/uvicorn-0.48.0-py3-none-any.whl", hash = "sha256:48097851328b87ec36117d3d575234519eb58c2b22d79666e9bbc6c49a761dad", size = 71410, upload-time = "2026-05-24T12:08:40.258Z" },
{ url = "https://files.pythonhosted.org/packages/f1/79/4a20b54ab0491485ccd8c077db2d39187c7f12b3e15485d38a7be37c81b4/uvicorn-0.52.4-py3-none-any.whl", hash = "sha256:f86e41a149d7d05a9969337e3946a9c171c06a5d42680896daaba624aeac8da1", size = 79871, upload-time = "2026-08-19T06:27:40.36Z" },
]
[package.optional-dependencies]
@@ -7705,7 +7705,9 @@ dependencies = [
{ name = "aiohttp" },
{ name = "anthropic" },
{ name = "gepa" },
{ name = "h11" },
{ name = "httpx" },
{ name = "httpx2" },
{ name = "loguru" },
{ name = "math-verify" },
{ name = "mcp" },
@@ -7722,6 +7724,7 @@ dependencies = [
{ name = "tenacity" },
{ name = "tomli-w" },
{ name = "typing-extensions" },
{ name = "uvicorn" },
]
[package.optional-dependencies]
@@ -7739,8 +7742,10 @@ requires-dist = [
{ name = "anthropic", specifier = ">=1.0.0" },
{ name = "datasets", marker = "extra == 'lean'", specifier = ">=3.3.0,<6.0.0" },
{ name = "gepa", specifier = ">=0.0.6" },
{ name = "h11", specifier = ">=0.16.0" },
{ name = "harbor", marker = "python_full_version >= '3.12' and extra == 'harbor'", specifier = "==0.21.0" },
{ name = "httpx", specifier = ">=0.27.0" },
{ name = "httpx2", specifier = ">=2.12.0" },
{ name = "loguru", specifier = ">=0.7.0" },
{ name = "math-verify", specifier = ">=0.8.0" },
{ name = "mcp", specifier = "==2.0.0" },
@@ -7761,6 +7766,7 @@ requires-dist = [
{ name = "textarena", marker = "extra == 'ta'", specifier = "==0.7.4" },
{ name = "tomli-w", specifier = ">=1.0.0" },
{ name = "typing-extensions", specifier = ">=4.12.2" },
{ name = "uvicorn", specifier = ">=0.52.0" },
]
provides-extras = ["harbor", "lean", "modal", "openenv", "ta"]