Compare commits

...
Author SHA1 Message Date
Mika SenghaasandGitHub 2d6dc64efd fix: log periodic gauges through the monitors (#3565)
## Summary
- The `PeriodicLogger` printed its pipeline view to the console and
called `wandb.log` directly, so the `dispatcher/*`, `concurrency/*`,
`watcher/*`, and `event_loop_lag/*` gauges only ever reached W&B. The
file monitor (and with it the local dashboard's `metrics.jsonl`) and the
Prime monitor never saw them; with W&B disabled the gauges existed only
as console log text.
- The periodic payload now fans out through `monitors.log(payload,
step=None)` like the inference-metrics collector, so every registered
monitor receives it as a time-keyed row and stamps its own time axis.
All W&B-specific logic is gone from the orchestrator and the eval runner
(`eval/runner.py`, which replaced the old evals process in #3471): the
W&B monitor already defines the `_timestamp` axis lazily per key prefix,
so the eager `wandb.define_metric` pre-registration and its
`metric_keys`/`wandb_enabled` plumbing are removed (the now-unused
`DispatcherMetrics.drain_keys` helper goes with it).
- Clean-exit teardown now stops the `PeriodicLogger` before
`monitors.finalize()`, next to the inference collector — both write
through the monitors, and a tick after finalize would land on a finished
W&B / Prime run. The eval runner already drained its loggers first
(`drain()` before `finalize()`); the orchestrator now matches.
- Overview panels, mirrored in the W&B saved view
(`monitors/wandb/overview.py`) and the local dashboard
(`dashboard/static/app.js`), which the overview code keeps in sync: the
inflight panel gains `concurrency/max_inflight` so in-flight episodes
read against the adaptive cap, and the token-rate panels drop their
per-engine tail series (`generation_tokens_total:rate/min`,
`prompt_tokens_total:rate/max`).

## Verification
1-step reverse-text runs (`uv run rl @
configs/ci/integration/reverse-text/start.toml --max-steps 1`, W&B off,
file monitor on), before on `main` vs. after on this branch:

- **before**: `monitors/file/metrics.jsonl` has 13 rows and zero
`concurrency/*` / `dispatcher/*` keys — only
train/eval/inference/loss/perf keys.
- **after**: periodic time-keyed rows (`"step": null`, `"producer":
"orch"`) carrying all `concurrency/*` gauges (`max_inflight`,
`turnover`, `capacity`, `signal`, `growth_multiplier`), 12
`dispatcher/*` keys, 4 `watcher/*` keys, and 7 `event_loop_lag/*` keys.
- **local dashboard overview** (headless browser check against both run
dirs): after, the `dispatcher/inflight/{train,eval}` +
`concurrency/max_inflight` panel renders with data (all charts mounted,
no console errors); before, the panel is absent (no keys, no panel).
- **teardown ordering** (after the finalize-order fix): the last
`metrics.jsonl` write lands strictly before `monitors.finalize()`
(03:54:38.66 vs. the `Finalized metrics` log line at 03:54:39), zero
rows written at or after finalize, clean exit, no `Failed to log`
warnings.
- Re-verified after rebasing onto `main` (picked up the eval-CLI
consolidation and the concurrency-taper commit) and again after the
teardown-order fix — all green.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes observability plumbing and shutdown ordering for background
loggers; behavior is well-scoped but affects all runs’ metrics export
and clean-exit teardown.
> 
> **Overview**
> **Periodic pipeline metrics** (dispatcher, concurrency, watcher, event
loop lag) no longer go only to W&B via direct `wandb.log`.
`PeriodicLogger` now emits each tick through `monitors.log(payload,
step=None)`, so file monitor, dashboard `metrics.jsonl`, Prime, and W&B
all get the same time-keyed rows.
> 
> The orchestrator and eval runner drop `metric_keys`, `wandb_enabled`,
and eager `wandb.define_metric` pre-registration; unused
`DispatcherMetrics.drain_keys` is removed. On clean exit, the
orchestrator **stops `PeriodicLogger` before `monitors.finalize()`**,
matching inference metrics teardown so nothing writes after the run is
closed.
> 
> **Overview charts** (W&B overview + local dashboard) add
`concurrency/max_inflight` to the inflight panel and simplify token-rate
panels to fleet sum only (no per-engine min/max tails).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
be479ea13c728ab82bacdd9f0773fc70dc0a3b41. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-17 10:02:47 -07:00
07ebe34570 fix(rl): launch env servers in multi-node RL runs (#3568)
Multi-node RL runs currently launch no environment servers. The
orchestrator waits 600 seconds
for an address file that nobody writes, then times out, and the trainer
sits in the weight
broadcast until its own timeout.

The flat-to-nested refactor in #3471 replaced `format_log_message`'s two
flat `train_env_names` /
`eval_env_names` parameters with a single `env_names: dict[str,
list[str]]` and updated all four
call sites in `rl.py`. Two of them really are `format_log_message` calls
and were correct. The
other two are `template.render(...)` calls feeding

[`multi_node_rl.sbatch.j2:542-559`](https://github.com/PrimeIntellect-ai/prime-rl/blob/d5ed9fb7e4233c6f4914af2652c3bda69bddb0c7/src/prime_rl/templates/multi_node_rl.sbatch.j2#L542-L559),
which still reads the flat names:

```diff
# src/prime_rl/entrypoints/rl.py:534,574 in c394c2e1b, write_slurm_script
-            train_env_names=train_env_names,
-            eval_env_names=eval_env_names,
+            env_names={"train": train_env_names, "eval": eval_env_names},
```

```jinja
{# multi_node_rl.sbatch.j2:542,550, unchanged by this PR #}
{%- if train_env_names or eval_env_names %}
{%- for name in train_env_names %}
```

Under Jinja's default `Undefined`, a name that was never passed is
indistinguishable from an
empty list: `{% if train_env_names or eval_env_names %}` is false either
way and nothing raises.
The generated script was therefore identical to one for a run that
legitimately has no env
servers. This reverts the two render calls to flat kwargs and leaves the
three
`format_log_message` calls on the nested dict.

- The failure is silent: the generated sbatch and the per-source env
JSON both look correct, and
the first symptom is `TimeoutError: env server never published its
address ... within 600.0s`.
- Single-node and SFT are unaffected. Single-node goes through
`rl_local`, which spawns env
servers as subprocesses; `sft.py` already spreads its env names as
`**eval_vars`, the flat form
  `multi_node_sft.sbatch.j2` wants.

## Verification

**Render level.** The pre-fix script is 13 lines shorter, and those 13
lines are the entire
env-server block:

```sh
uv run rl @ examples/basic/reverse-text/rl.toml --deployment.type multi_node --deployment.num-train-nodes 1 --deployment.num-infer-nodes 1 --slurm.partition all --max-steps 2 --run.name envserver-check --no-dashboard --dry-run
grep -c "uv run env-server" $PRL_OUTPUT_DIR/envserver-check/launcher/rl.sbatch
```

Before: `0`. After: `2`, one for the train source and one for the eval
source. Diffing the two
generated scripts shows nothing else moved (comment block elided):

```diff
@@ -331,0 +332,13 @@
+    mkdir -p $LOG_DIR/envs/train
+    uv run env-server @ $CONFIG_DIR/envs/train/reverse-text.json \
+        > $LOG_DIR/envs/train/reverse-text.log 2>&1 &
+    mkdir -p $LOG_DIR/envs/eval
+    uv run env-server @ $CONFIG_DIR/envs/eval/reverse-text-eval.json \
+        > $LOG_DIR/envs/eval/reverse-text-eval.log 2>&1 &
```

**Runtime.** Before, from one of the failing multi-node runs, the
orchestrator polls for a file
no process will write and gives up after 600s:

```
TimeoutError: env server never published its address to
<run>/configs/attempt_1/resolved/envs/train/reverse-text.address within 600.0s
```

After, a 2-node reverse-text run on Qwen3-0.6B spawns the server, which
publishes its address
46s later, and training completes:

```
14:48:47  <run>/logs/attempt_1/envs/train/reverse-text.log created
14:49:33  EnvServerPool up: address=tcp://127.0.0.1:42101 workers=1/inf multiplex=128
15:01:56  SUCCESS Step 2 | 1.2s | Loss 0.0038 | Entropy 0.6078 | Grad. Norm 0.7942
```

That log file is the cleanest discriminator: the shell redirect on the
`uv run env-server` line
creates it, so before the fix it never exists at all.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 13:02:37 -04:00
c1ac451e39 fix(trainer): declare contiguous outputs in the fp8 and ring attention fakes (#3567)
Three custom-op fake kernels declared output strides copied from their
inputs, while the real kernels return freshly allocated contiguous
buffers. `torch.compile` trusts the fake, bakes its strides into an
`assert_size_stride` guard, and the guard fires at runtime. This showed
up first in the fp8 MoE backward with activation checkpointing off,
where `ac=full` had been hiding the expert backward inside a recompute
region:

```
assert_size_stride(buf2, (32, 1408, 4096), (5767168, 1, 1408), 'torch.ops.prime_rl.grouped_fp8_gemm_backward.default')
AssertionError: expected size 1408==1408, stride 4096==1 at dim=1; expected size 4096==4096, stride 1==1408 at dim=2
```

All three fakes now declare metadata that is a pure function of their
inputs' shapes and dtypes, independent of the inputs' strides, of the
`needs_grad_*` flags, and of an unstated bf16 contract.

- `grouped_fp8_gemm_backward`, active: MoE passes a transposed weight;
real `(524288, 1024, 1)` vs fake `(524288, 1, 512)`.
- `ring_attn::attention`, active: rope leaves `q` non-contiguous, so
real `(1024, 128, 1)` vs fake `(128, 32768, 1)`, on every CP ring step.
- `fp8_blockwise_mm_backward` and the grouped GEMM's `grad_x`, latent:
masked only because production inputs are contiguous.
- The fp8 kernels' unobservable placeholder allocations are contiguous
too, which is what drops the flag-conditional stride.
- `ring_attn.py` needed no real-kernel change, since `torch.cat` is
already unconditionally contiguous.
- `_compute_grad_weight` downcasts to `weight.dtype`, not a hardcoded
bf16; a no-op today, as call sites pre-cast.
- Verified already correct, left alone: both fp8 forward fakes,
`attention_backward`, and the forward's `softmax_lse`.
- `compile=on, ac=off, fp8 MoE` now completes a full forward and
backward on the GLM-4.5-MoE path.

Noticed while auditing, not addressed: `gpt_oss` has its own ring
implementation that bypasses this op.

## Verification

An `opcheck` test for the four fp8 ops was added in `02f3f684b` and
removed again in `49ce67cff`: it needs an SM90+ GPU and `deep_gemm`, so
it would only ever skip on CI's `vm` runner. To re-run it on a Hopper or
Blackwell node:

```
git show 02f3f684b:tests/unit/train/models/test_fp8_fake_kernels.py > tests/unit/train/models/test_fp8_fake_kernels.py
DG_JIT_CACHE_DIR=<warm deepgemm cache> uv run pytest tests/unit/train/models/test_fp8_fake_kernels.py -v
```

`torch.library.opcheck` with `test_utils=["test_schema",
"test_faketensor"]` compares the real op's output shape, stride, and
dtype against the fake's. On 8x H200 that is 26 passed post-fix; against
the pre-fix sources it fails exactly the 9 cases where a grad is
requested and its corresponding input is non-contiguous and passes the
other 17, so it discriminates rather than failing everywhere. The
ring-attention fake was verified the same way under a two-rank
`torchrun` harness, not committed since a distributed GPU test would
also only skip on CI. `uv run pytest tests/unit/train/models` is green
on the same node: 177 passed, 5 skipped.

Verified end to end with a harness built from production code only
(`Glm4MoeForCausalLM`, `configure_moe_runtime` with
`DeepGemmFP8MoEComputeConfig`, `apply_compile`, `setup_fsdp`):
`compile=on, ac=off` completes forward and backward at `ep` 1, 2, and 4,
up to real GLM-4.5-Air dimensions on 8 H200s. Restoring the pre-fix fake
reproduces the original `assert_size_stride` traceback at the same
shapes, so the check is not inert.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 12:59:53 -04:00
rasdaniandGitHub d5ed9fb7e4 chore: ask before changing repository skills (#3564)
Require agents to suggest specific repository skill changes, explain the
benefit, and wait for user approval before editing. Existing explicit
requests or approvals remain sufficient; ordinary code, workflow,
documentation, and PR requests do not authorize skill changes. Reading
and following skills remains allowed.

Changes only `AGENTS.md`, replacing its automatic skill-maintenance
requirement with the same approval guidance as
https://github.com/PrimeIntellect-ai/prime-envs/pull/814.

Validation: `git diff --check` passed; file-scoped pre-commit hooks
completed (Python-only hooks skipped this Markdown-only change).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Markdown-only policy change in `AGENTS.md` with no runtime or security
impact.
> 
> **Overview**
> Updates **agent policy in `AGENTS.md`** so repository skills under
`skills/` are no longer auto-maintained when code or workflows change.
> 
> The Skills section drops the requirement to check and update skills
after codebase edits, and replaces the “you must update skills when you
fix workflows” rule with **explicit user approval**: propose a concrete
skill change, explain why, and wait before creating, editing, renaming,
deleting skills or their symlinks. Prior explicit approval still counts;
ordinary code, workflow, docs, or PR work does **not** grant permission
to touch skills. Agents may still read and follow skills unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6e13660903da49dda03394923b97dee985fe779b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-16 19:50:35 -07:00
b4a41d3f2c perf(deepseek-v4): fuse the mHC chain and route unweighted RMS norms through quack (#3558)
DeepSeek V4's manifold-constrained hyper-connection (mHC) chain ran
eager and cost far more than
its arithmetic warrants: a python Sinkhorn loop of roughly 119 tiny
launches over stream mixing
matrices, an fp32 copy of the flattened streams materialized purely as
an intermediate, a
multi-kernel write-back over the full (batch, sequence, stream, hidden)
tensor, and a `q_b_norm`
whose input was non-contiguous. This fuses or reroutes all four.

- The unweighted RMS norms (the mHC input norms and attention's
`q_b_norm`) dispatch to quack
through the same gate the shared `RMSNorm` uses, with an optional
`out_dtype`. `q_b_norm` moves
ahead of the head transpose so quack's flatten is a view rather than a
copy; RMS over the channel
  axis commutes with the transpose exactly.
- The input norms take the bf16 streams directly and emit fp32, so the
fp32 copy is never
  materialized. The gate math downstream of the norm stays fp32.
- The Sinkhorn loop and the write-back become two Triton ops vendored
from NVIDIA/Megatron-LM at
`bb5dfd08f` (BSD-3, full license text reproduced in the file header).
They require a power-of-two
`hc_mult` and a CUDA input, both of which Triton itself enforces, and
the eager implementations
move to `eager_reference.py`, where the tests measure the kernels
against them.
- The rank-4 mHC residual is named `mhc_states` throughout, so
`hidden_states` always means the
rank-3 collapsed sequence, and the write-back moves onto
`DeepseekV4HyperConnection` as
  `update_states`.
- Both fused paths are covered on GPU, measured against the eager
references rather than a
  runtime fallback branch.

Forward/backward ms per call on an H200 at batch 1, sequence 16384,
`hc_mult` 4, hidden dimension
4096 (the Sinkhorn row is measured on the stream mixing tensor):

| Op | Before | After |
| --- | --- | --- |
| mHC front half | 2.89 / 8.10 | 1.05 / 2.54 |
| Sinkhorn | 1.05 / 3.14 | 0.10 / 0.81 |
| Stream write-back | 5.96 / 7.89 | 0.40 / 0.94 |
| `q_b_norm` | 0.99 / 2.85 | 0.30 / 0.96 |

A 4-node full-depth A/B goes from 15.97 to 13.11 s/step at 4.2 GiB lower
peak. That was measured on
the SFT-optim stack, not this branch: on `main` step time is
optimizer-offload dominated, so the
same A/B there would hide the change inside the offload's shadow.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-16 20:35:30 -04:00
Mika SenghaasandGitHub d7339fcf25 fix(orchestrator): taper concurrency growth by KV usage (#3556)
## Summary

The adaptive controller currently grows the admission cap by 25% per
pipeline turnover until GPU-KV usage crosses 60%, then stops growing
until the 80% soft-cap. That discontinuity can carry the cap into a
corrective trim too quickly.

This changes growth to taper linearly from 1.20× per turnover at 0%
GPU-KV usage to 1.00× at the 80% soft-cap. Above the soft-cap, the
existing soft-trim behavior remains unchanged. The controller also
exposes the active growth multiplier as a gauge.

## Verification

Validation run from #3542. Qwen3-30B-A3B on Terminal Lego on 2 nodes.
Can observe oscillating heavy growth and hard cut prior to this PR and
sigmoidish growth and no episode preemptions.

<img width="582" height="245" alt="Screenshot 2026-09-15 at 9 26 47 PM"
src="https://github.com/user-attachments/assets/dedf2bbe-0c8e-4434-93fb-de79b829ff44"
/>

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes orchestrator admission AIMD tuning, which can affect
throughput and preemption/cut behavior under load, though trims and cuts
above the soft-cap are unchanged.
> 
> **Overview**
> Replaces the **fixed 1.25× cap growth per pipeline turnover** (while
KV stayed below 60%) with a **usage-dependent multiplier** that scales
from **1.20× at 0% GPU-KV** down to **1.0× at the 80% soft-cap**, so
growth eases before trims instead of stopping abruptly at 60%.
> 
> **Signal handling** no longer treats “KV above grow threshold” as
overload for gating; **soft pressure** is tied to crossing
**`KV_USAGE_SOFT_CAP`**, while **persistent queue overload** still
drives **hard** signals. **`record_episode`** applies
**`growth_multiplier**` instead of a constant factor, and
**`concurrency/growth_multiplier`** is exported as a gauge for
observability.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
bc42bf362df09c89e5a3c47bbb2f11bf21d5923d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-16 11:58:36 -07:00
20 changed files with 838 additions and 137 deletions
+2 -2
View File
@@ -43,9 +43,9 @@ Namespaces are one honking great idea -- let's do more of those!
## Skills
Skills live in `skills/` and are symlinked to `.claude/skills/`. They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs). When you make changes to the codebase, check if any skills need to be updated to stay accurate.
Skills live in `skills/` and are symlinked to `.claude/skills/`. They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs).
You are responsible for maintaining the skills folder. When a workflow fails and you fix it – whether with help from the user or through trial and error – you must update the skills to make implicit knowledge explicit. You are also responsible for keeping the skills up to date whenever you or anyone else modifies the code.
If a repository skill could benefit from an update, suggest the specific change, explain why it would help, and ask the user for approval before making it. Wait for approval before creating, modifying, renaming, or deleting skills, including their supporting files and symlinks. If the user has already explicitly requested or approved the skill change, proceed without asking again. Requests to change code, fix workflows, update documentation, or open a PR do not implicitly authorize skill changes. You may read and follow skills without changing them.
## Testing
+3 -2
View File
@@ -406,8 +406,9 @@ const INFERENCE_PANELS = [
["inference/agg/num_requests_running/mean", "inference/agg/num_requests_running/min", "inference/agg/num_requests_running/max"],
["inference/agg/num_requests_waiting/mean", "inference/agg/num_requests_waiting/min", "inference/agg/num_requests_waiting/max"],
["inference/agg/prefix_cache_hit_rate/pooled", "inference/agg/prefix_cache_hit_rate/min"],
["inference/agg/generation_tokens_total:rate/sum", "inference/agg/generation_tokens_total:rate/min"],
["inference/agg/prompt_tokens_total:rate/sum", "inference/agg/prompt_tokens_total:rate/max"],
["inference/agg/generation_tokens_total:rate/sum"],
["inference/agg/prompt_tokens_total:rate/sum"],
["dispatcher/inflight/train", "dispatcher/inflight/eval", "concurrency/max_inflight"],
];
const TRAINER_KEY_RE = /^(perf|optim|loss|entropy|system|mismatch_kl|kl_ent_ratio|is_masked|masked_|unmasked_|max_vio|routing_|ref_kl|val)[/_]?/;
+4 -2
View File
@@ -531,7 +531,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
use_zmq_transport=config.rollout_transport is not None and config.rollout_transport.type == "zmq",
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
env_names={"train": train_env_names, "eval": eval_env_names},
train_env_names=train_env_names,
eval_env_names=eval_env_names,
**modelexpress_vars,
)
else:
@@ -571,7 +572,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script
trainer_env_vars=trainer_env_vars,
orchestrator_env_vars=orchestrator_env_vars,
inference_env_vars=inference_env_vars,
env_names={"train": train_env_names, "eval": eval_env_names},
train_env_names=train_env_names,
eval_env_names=eval_env_names,
**modelexpress_vars,
)
+1 -8
View File
@@ -28,7 +28,7 @@ from prime_rl.orchestrator import live
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
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.dispatcher import Dispatcher, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
@@ -79,7 +79,6 @@ class EvalRunner:
# The launcher-set $PRL_RUN_ID is the run identity; standalone runs mint a local one.
self.run_id = os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex
self.run_name = os.environ.get("PRL_RUN_NAME")
wandb_enabled = monitors.get(monitors.WandbMonitor) is not None
get_logger().info(f"Initializing inference pool (base_url={config.client.base_url}, model={config.model})")
self.clients = InferenceClient(config.client, model_name=config.model)
@@ -153,13 +152,7 @@ class EvalRunner:
self.periodic_logger = PeriodicLogger(
name="Eval",
collect=self.collect_pipeline_view,
metric_keys=[
*list(self.dispatcher.gauges().keys()),
*list(self.concurrency.gauges().keys()),
*DispatcherMetrics.drain_keys(train_envs=set(), eval_envs={env.name for env in self.eval_envs}),
],
interval=config.log.interval,
wandb_enabled=wandb_enabled,
)
async def start(self) -> None:
+3 -3
View File
@@ -73,9 +73,9 @@ INFERENCE_PANELS = [
"inference/agg/num_requests_waiting/max",
],
["inference/agg/prefix_cache_hit_rate/pooled", "inference/agg/prefix_cache_hit_rate/min"],
["inference/agg/generation_tokens_total:rate/sum", "inference/agg/generation_tokens_total:rate/min"],
["inference/agg/prompt_tokens_total:rate/sum", "inference/agg/prompt_tokens_total:rate/max"],
["dispatcher/inflight/train", "dispatcher/inflight/eval"],
["inference/agg/generation_tokens_total:rate/sum"],
["inference/agg/prompt_tokens_total:rate/sum"],
["dispatcher/inflight/train", "dispatcher/inflight/eval", "concurrency/max_inflight"],
]
# SFT flavor: no rollout-based train sections — the training signal is the loss curve.
+13 -9
View File
@@ -5,8 +5,9 @@ treats it as a black box. There is no cost model: the controller measures KV
pressure off the engines and reacts at the pipeline's own pace (AIMD):
- **Grow** the cap multiplicatively per pipeline turnover (each completion
advances the turnover by ``1/inflight``) while the engines are clear, KV
usage is below ``KV_USAGE_GROW``, and the cap binds admission.
advances the turnover by ``1/inflight``) while the engines are clear and
the cap binds admission. The multiplier tapers linearly with GPU-KV usage
until the soft-cap boundary.
- **Trim** above ``KV_USAGE_SOFT_CAP``: lower the cap to what the engines
hold at ``KV_USAGE_TARGET`` and let completions drain the pool (soft). If
usage still climbs past ``KV_USAGE_HARD_CAP`` — units maturing in place
@@ -38,14 +39,12 @@ from prime_rl.configs.orchestrator import ConcurrencyConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.utils import format_num
TURNOVER_GROWTH = 1.25
"""Cap growth per pipeline turnover while the engines are clear and the cap binds."""
TURNOVER_GROWTH_MAX = 1.2
"""Cap growth per pipeline turnover at zero GPU-KV utilization."""
BINDING_FRACTION = 0.9
"""The cap counts as binding when inflight reaches this fraction of it."""
KV_USAGE_GROW = 0.6
"""Grow only while every decode engine's KV usage is below this."""
KV_USAGE_SOFT_CAP = 0.8
"""Above this usage, soft-trim: lower the cap and let completions drain the
@@ -129,6 +128,7 @@ class ConcurrencyController:
self.turnover = 0.0
self.signal: Signal = "clear"
self.growth_multiplier = 1.0
# Growth gate from the last poll, consumed by per-completion growth
self.can_grow = False
self.can_grow_until = 0.0
@@ -183,7 +183,7 @@ class ConcurrencyController:
and time.monotonic() < self.can_grow_until
and inflight >= BINDING_FRACTION * self.max_inflight
):
self.cap = self.clamp(self.cap * TURNOVER_GROWTH**fraction)
self.cap = self.clamp(self.cap * self.growth_multiplier**fraction)
self.apply_limit(int(self.cap), reason=None)
def observe(self, samples: list[EngineLoadSample]) -> None:
@@ -223,8 +223,10 @@ class ConcurrencyController:
else:
self.queue_overload_polls = 0
queue_overload = self.queue_overload_polls >= QUEUE_PERSISTENCE_POLLS
if queue_overload or max_usage > KV_USAGE_GROW:
worst = max(worst, "hard" if queue_overload else "soft", key=SEVERITY.__getitem__)
if queue_overload:
worst = max(worst, "hard", key=SEVERITY.__getitem__)
elif max_usage > KV_USAGE_SOFT_CAP:
worst = max(worst, "soft", key=SEVERITY.__getitem__)
self.signal = worst
inflight = self.get_inflight() if self.get_inflight is not None else 0
@@ -247,6 +249,7 @@ class ConcurrencyController:
self.escalated = False
self.trim_cooldown = max(0, self.trim_cooldown - 1)
self.can_grow = worst == "clear" and total_queued == 0 and not self.draining
self.growth_multiplier = 1.0 + (TURNOVER_GROWTH_MAX - 1.0) * max(0.0, 1.0 - max_usage / KV_USAGE_SOFT_CAP)
self.can_grow_until = time.monotonic() + GROWTH_GATE_TTL_S
# First capacity observation without a user-set start: derive the
@@ -331,4 +334,5 @@ class ConcurrencyController:
"concurrency/turnover": self.turnover,
"concurrency/capacity": float(self.capacity or 0),
"concurrency/signal": float(SEVERITY[self.signal]),
"concurrency/growth_multiplier": self.growth_multiplier,
}
+2 -17
View File
@@ -92,8 +92,8 @@ class DispatcherMetrics:
def drained(self, *, train_envs: set[str], eval_envs: set[str]) -> dict[str, float]:
"""Return per-tick counters and clear them. Emits the full pre-
registered key set every tick (zero when no activity) so the wandb
time axis stays dense and ``define_metric`` lines up."""
registered key set every tick (zero when no activity) so the
time-keyed series stay dense on every monitor."""
out: dict[str, float] = {}
for kind in ("train", "eval"):
envs = train_envs if kind == "train" else eval_envs
@@ -112,21 +112,6 @@ class DispatcherMetrics:
self.errored_by_kind_env.clear()
return out
@staticmethod
def drain_keys(*, train_envs: set[str], eval_envs: set[str]) -> list[str]:
"""Full set of keys ``drained`` may emit; used by the periodic
logger for ``wandb.define_metric``."""
keys = [
"dispatcher/cancelled/train",
"dispatcher/cancelled/eval",
"dispatcher/errored/train",
"dispatcher/errored/eval",
]
for env in train_envs | eval_envs:
keys.append(f"dispatcher/cancelled/{env}")
keys.append(f"dispatcher/errored/{env}")
return keys
def _validate_episode_task(episode: vf.WireEpisode, task: vf.Task) -> None:
expected = (task.key, task.hash)
+7 -23
View File
@@ -11,7 +11,7 @@ and drives the pipeline. Components are single-purpose:
- ``TrainEpisodes`` / ``EvalEpisodes`` preserve episode boundaries and build per-step metrics.
- ``WeightWatcher`` advances ``Policy`` and notifies observers.
- ``PeriodicLogger`` polls the components on a shared interval for the
``_timestamp``-axis pipeline log.
pipeline log, a time-keyed row through the monitors.
Components don't reference the orchestrator. The orchestrator wires them
in ``setup()`` and drives them from ``main_loop()``.
@@ -41,7 +41,7 @@ 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 AdminPlane, InferenceClient, setup_admin_plane
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
@@ -336,7 +336,6 @@ class Orchestrator:
)
log_interval = config.log.interval
wandb_enabled = monitors.get(monitors.WandbMonitor) is not None
self.concurrency = ConcurrencyController(config.concurrency, fallback_cost=config.seq_len)
self.dispatcher = Dispatcher(
@@ -398,24 +397,7 @@ class Orchestrator:
self.periodic_logger = PeriodicLogger(
name="Pipeline",
collect=self.collect_pipeline_view,
metric_keys=[
*list(self.dispatcher.gauges().keys()),
*list(self.concurrency.gauges().keys()),
*DispatcherMetrics.drain_keys(
train_envs={e.name for e in self.train_envs},
eval_envs={e.name for e in self.eval_envs} if self.eval_envs is not None else set(),
),
*list(self.watcher.gauges().keys()),
"event_loop_lag/min",
"event_loop_lag/mean",
"event_loop_lag/median",
"event_loop_lag/p90",
"event_loop_lag/p99",
"event_loop_lag/max",
"event_loop_lag/n",
],
interval=log_interval,
wandb_enabled=wandb_enabled,
)
get_logger().info(f"Syncing inference to the trainer's startup broadcast (v{sync_version})")
@@ -457,10 +439,12 @@ class Orchestrator:
elapsed = format_time(time.perf_counter() - start_time)
if clean_exit:
get_logger().success(f"Orchestrator step loop done in {elapsed}")
# The collector logs to the W&B run, so it must stop before
# finalize marks the run finished
# The background loggers write through the monitors, so they must
# stop before finalize marks the run finished
if self.inference_metrics is not None:
await self.inference_metrics.stop()
if self.periodic_logger is not None:
await self.periodic_logger.stop()
# Finalize only on a clean exit — a crashed run must not be marked
# completed; the platform run's atexit hook marks it failed instead.
await monitors.finalize()
@@ -830,7 +814,7 @@ class Orchestrator:
def collect_pipeline_view(self) -> tuple[str, dict[str, float]]:
"""Pipeline view for the orchestrator's ``PeriodicLogger``. Returns
``(console_body, wandb_payload)``. Per-env ``(env=N, …)``
``(console_body, payload)``. Per-env ``(env=N, …)``
breakdowns inline only when there's more than one train / eval env;
the eval halves drop entirely when nothing is accumulating."""
disp_gauges = self.dispatcher.gauges()
+10 -18
View File
@@ -1,16 +1,14 @@
"""PeriodicLogger: orchestrator's pipeline view, fires every ``interval``
seconds. ``collect()`` returns ``(console_body, wandb_payload)`` in one
call so drain-on-read counters fire exactly once per tick. Wandb writes
land on the ``_timestamp`` axis."""
seconds. ``collect()`` returns ``(console_body, payload)`` in one call so
drain-on-read counters fire exactly once per tick. The payload goes to every
registered monitor as a time-keyed row (``step=None``)."""
from __future__ import annotations
import asyncio
import time
from typing import Callable
import wandb
from prime_rl import monitors
from prime_rl.utils.async_utils import safe_cancel
from prime_rl.utils.logger import get_logger
@@ -21,21 +19,14 @@ class PeriodicLogger:
*,
name: str,
collect: Callable[[], tuple[str, dict[str, float]]],
metric_keys: list[str],
interval: float,
wandb_enabled: bool,
) -> None:
self.name = name
self.collect = collect
self.interval = interval
self.wandb_enabled = wandb_enabled
self.task: asyncio.Task | None = None
self.stopped = asyncio.Event()
if self.wandb_enabled:
for key in metric_keys:
wandb.define_metric(key, step_metric="_timestamp")
async def start(self) -> None:
self.task = asyncio.create_task(self.run(), name=f"{self.name}_periodic_logger")
@@ -46,16 +37,17 @@ class PeriodicLogger:
await asyncio.wait_for(self.stopped.wait(), timeout=self.interval)
except asyncio.TimeoutError:
pass
self.emit()
await self.emit()
except asyncio.CancelledError:
return
def emit(self) -> None:
async def emit(self) -> None:
body, payload = self.collect()
get_logger().info(body)
if self.wandb_enabled and payload:
payload["_timestamp"] = time.time()
wandb.log(payload)
if payload:
# Time-keyed row: the pipeline view is sampled on wall time, not
# the training step. Each monitor stamps its own time axis.
await monitors.log(payload, step=None)
async def stop(self) -> None:
self.stopped.set()
@@ -713,8 +713,9 @@ class DeepseekV4Attention(nn.Module):
cos, sin = packed.position_embeddings[self.rope_layer_type] # (1, t, qk_rope_head_dim // 2) each
q_residual = self.q_a_norm(self.q_a_proj(hidden_states)) # (b, t, r)
q = self.q_b_proj(q_residual).view(*hidden_shape).transpose(1, 2) # (b, h, t, d)
q = apply_rotary_pos_emb_interleaved(self.q_b_norm(q), cos, sin)
# Normalizing before the transpose keeps the input contiguous for the quack kernel.
q = self.q_b_norm(self.q_b_proj(q_residual).view(*hidden_shape)).transpose(1, 2) # (b, h, t, d)
q = apply_rotary_pos_emb_interleaved(q, cos, sin)
kv = self.kv_norm(self.kv_proj(hidden_states)) # (b, t, d)
kv = kv.view(*kv.shape[:2], 1, self.head_dim) # (b, t, 1, d)
@@ -1,4 +1,4 @@
"""Naive DeepSeek V4 attention reference.
"""Naive DeepSeek V4 attention and mHC references.
Nothing in the production path calls these. They exist for the tests, where a dense, obviously
correct implementation is the standard the fused kernel is measured against, and where it is the
@@ -170,3 +170,25 @@ def use_eager_attention(module: nn.Module) -> None:
for submodule in module.modules():
if isinstance(submodule, DeepseekV4Attention):
submodule.forward = types.MethodType(eager_attention_forward, submodule)
def eager_sinkhorn(logits: Tensor, num_iterations: int, eps: float) -> Tensor:
"""Project `logits` onto the doubly-stochastic manifold by alternating row and column sums."""
comb = torch.softmax(logits, dim=-1) + eps
comb = comb / (comb.sum(dim=-2, keepdim=True) + eps)
for _ in range(num_iterations - 1):
comb = comb / (comb.sum(dim=-1, keepdim=True) + eps)
comb = comb / (comb.sum(dim=-2, keepdim=True) + eps)
return comb
def eager_update_states(post: Tensor, comb: Tensor, sublayer_out: Tensor, mhc_states: Tensor) -> Tensor:
"""Broadcast the sublayer output over the streams via `post` and remix them via `comb`.
`comb` is consumed summing over the *source* stream axis, i.e. transposed; the fused kernel
applies that transpose internally, so both take `comb` untransposed.
"""
dtype = mhc_states.dtype
return post.to(dtype).unsqueeze(-1) * sublayer_out.unsqueeze(-2) + torch.matmul(
comb.to(dtype).transpose(-1, -2), mhc_states
)
@@ -3,23 +3,31 @@ import torch.nn.functional as F
from torch import nn
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
from prime_rl.trainer.models.kernels.deepseek_v4 import dsv4_mhc
from prime_rl.trainer.models.layers import norms
class DeepseekV4UnweightedRMSNorm(nn.Module):
"""RMS normalization without a learnable gain, computed in fp32."""
def __init__(self, eps: float = 1e-6):
def __init__(self, eps: float = 1e-6, out_dtype: torch.dtype | None = None):
super().__init__()
self.eps = eps
self.out_dtype = out_dtype
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x * torch.rsqrt(x.float().square().mean(-1, keepdim=True) + self.eps).to(x.dtype)
out_dtype = self.out_dtype if self.out_dtype is not None else x.dtype
quack_rms = norms.get_quack_rmsnorm()
if quack_rms is not None:
return quack_rms(x, eps=self.eps, out_dtype=out_dtype)
x = x.float()
return (x * torch.rsqrt(x.square().mean(-1, keepdim=True) + self.eps)).to(out_dtype)
class DeepseekV4HyperConnection(nn.Module):
"""Manifold-constrained hyper-connection (mHC) around one sublayer.
The residual is `hc_mult` parallel streams shaped `(B, S, hc_mult, hidden_size)`.
The residual, `mhc_states`, is `hc_mult` parallel streams shaped `(B, S, hc_mult, hidden_size)`.
A single projection of the normalized, flattened streams produces three gates:
- `pre`: weights that collapse the streams into the single sequence fed to the
@@ -39,16 +47,16 @@ class DeepseekV4HyperConnection(nn.Module):
self.hc_mult = config.hc_mult
self.hc_sinkhorn_iters = config.hc_sinkhorn_iters
self.hc_eps = config.hc_eps
self.input_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps)
self.input_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps, out_dtype=torch.float32)
mix = (2 + self.hc_mult) * self.hc_mult
self.fn = nn.Parameter(torch.empty(mix, self.hc_mult * config.hidden_size))
self.base = nn.Parameter(torch.empty(mix))
# One scale per gate: `pre`, `post`, `comb`.
self.scale = nn.Parameter(torch.empty(3))
def forward(self, hidden_streams: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
def forward(self, mhc_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
hc = self.hc_mult
flat = self.input_norm(hidden_streams.flatten(start_dim=2).float())
flat = self.input_norm(mhc_states.flatten(start_dim=2))
pre_w, post_w, comb_w = F.linear(flat, self.fn.float()).split([hc, hc, hc * hc], dim=-1)
pre_b, post_b, comb_b = self.base.split([hc, hc, hc * hc])
pre_scale, post_scale, comb_scale = self.scale.unbind(0)
@@ -56,15 +64,18 @@ class DeepseekV4HyperConnection(nn.Module):
pre = torch.sigmoid(pre_w * pre_scale + pre_b) + self.hc_eps
post = 2 * torch.sigmoid(post_w * post_scale + post_b)
comb_logits = comb_w.view(*comb_w.shape[:-1], hc, hc) * comb_scale + comb_b.view(hc, hc)
comb = torch.softmax(comb_logits, dim=-1) + self.hc_eps
comb = comb / (comb.sum(dim=-2, keepdim=True) + self.hc_eps)
for _ in range(self.hc_sinkhorn_iters - 1):
comb = comb / (comb.sum(dim=-1, keepdim=True) + self.hc_eps)
comb = comb / (comb.sum(dim=-2, keepdim=True) + self.hc_eps)
comb = dsv4_mhc.fused_sinkhorn(comb_logits, self.hc_sinkhorn_iters, self.hc_eps)
collapsed = (pre.unsqueeze(-1) * hidden_streams).sum(dim=2).to(hidden_streams.dtype)
collapsed = (pre.unsqueeze(-1) * mhc_states).sum(dim=2).to(mhc_states.dtype)
return post, comb, collapsed
def update_states(
self, post: torch.Tensor, comb: torch.Tensor, sublayer_out: torch.Tensor, mhc_states: torch.Tensor
) -> torch.Tensor:
"""Broadcast the sublayer output over the streams via `post` and remix them via `comb`."""
dtype = mhc_states.dtype
return dsv4_mhc.fused_post_bda(comb.to(dtype), mhc_states, post.to(dtype), sublayer_out)
def init_weights(self, init_std: float) -> None:
nn.init.normal_(self.fn, mean=0.0, std=init_std)
nn.init.zeros_(self.base)
@@ -77,17 +88,17 @@ class DeepseekV4HyperHead(nn.Module):
def __init__(self, config: DeepseekV4Config):
super().__init__()
self.hc_mult = config.hc_mult
self.input_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps)
self.input_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps, out_dtype=torch.float32)
self.eps = config.hc_eps
self.hc_fn = nn.Parameter(torch.empty(self.hc_mult, self.hc_mult * config.hidden_size))
self.hc_base = nn.Parameter(torch.empty(self.hc_mult))
self.hc_scale = nn.Parameter(torch.empty(1))
def forward(self, x: torch.Tensor) -> torch.Tensor:
flat = self.input_norm(x.flatten(2).float())
def forward(self, mhc_states: torch.Tensor) -> torch.Tensor:
flat = self.input_norm(mhc_states.flatten(2))
mixes = F.linear(flat, self.hc_fn.float())
pre = torch.sigmoid(mixes * self.hc_scale.float() + self.hc_base.float()) + self.eps
return (pre.unsqueeze(-1) * x).sum(dim=2).to(x.dtype)
return (pre.unsqueeze(-1) * mhc_states).sum(dim=2).to(mhc_states.dtype)
def init_weights(self, init_std: float) -> None:
nn.init.normal_(self.hc_fn, mean=0.0, std=init_std)
@@ -2,8 +2,9 @@
This is where the pieces built in `attention.py`, `moe.py`, `hyperconnections.py` and
`rotary.py` come together. The one structural surprise is the residual: it is not a single
stream but `hc_mult` parallel ones, carried as `(batch, seq, hc_mult, hidden)` from the
embedding all the way to `hc_head`, which collapses them back before the final norm.
stream but `hc_mult` parallel ones, carried as `mhc_states` of shape
`(batch, seq, hc_mult, hidden)` from the embedding all the way to `hc_head`, which collapses
them back before the final norm.
"""
from __future__ import annotations
@@ -19,7 +20,10 @@ from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, P
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
from prime_rl.trainer.models.deepseek_v4.converting_deepseek_v4 import conversion_chain
from prime_rl.trainer.models.deepseek_v4.dequantize import dequantize_state_dict_
from prime_rl.trainer.models.deepseek_v4.hyperconnections import DeepseekV4HyperConnection, DeepseekV4HyperHead
from prime_rl.trainer.models.deepseek_v4.hyperconnections import (
DeepseekV4HyperConnection,
DeepseekV4HyperHead,
)
from prime_rl.trainer.models.deepseek_v4.moe import DeepseekV4MoE
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
@@ -52,27 +56,21 @@ class DeepseekV4DecoderLayer(GradientCheckpointingLayer):
def forward(
self,
hidden_states: torch.Tensor,
mhc_states: torch.Tensor,
input_ids: torch.Tensor | None = None,
routed_experts: torch.Tensor | None = None,
*,
packed: PackedContext,
) -> torch.Tensor:
dtype = hidden_states.dtype
post, comb, collapsed = self.attn_hc(hidden_states)
post, comb, collapsed = self.attn_hc(mhc_states)
attn_output, _ = self.self_attn(self.input_layernorm(collapsed), packed=packed)
hidden_states = post.to(dtype).unsqueeze(-1) * attn_output.unsqueeze(-2) + torch.matmul(
comb.to(dtype).transpose(-1, -2), hidden_states
)
mhc_states = self.attn_hc.update_states(post, comb, attn_output, mhc_states)
post, comb, collapsed = self.ffn_hc(hidden_states)
post, comb, collapsed = self.ffn_hc(mhc_states)
mlp_output = self.mlp(
self.post_attention_layernorm(collapsed), input_ids=input_ids, routed_experts=routed_experts
)
return post.to(dtype).unsqueeze(-1) * mlp_output.unsqueeze(-2) + torch.matmul(
comb.to(dtype).transpose(-1, -2), hidden_states
)
return self.ffn_hc.update_states(post, comb, mlp_output, mhc_states)
# Mirrors HF's `_keep_in_fp32_modules_strict`, with `e_score_correction_bias` renamed to
@@ -265,17 +263,17 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
if position_ids is not None:
packed.check_position_ids(position_ids)
hidden_states = inputs_embeds.unsqueeze(2).expand(-1, -1, self.config.hc_mult, -1).contiguous()
mhc_states = inputs_embeds.unsqueeze(2).expand(-1, -1, self.config.hc_mult, -1).contiguous()
for layer_idx, decoder_layer in enumerate(self.layers):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
hidden_states = decoder_layer(
hidden_states,
mhc_states = decoder_layer(
mhc_states,
input_ids=input_ids,
routed_experts=routed_experts_layer,
packed=packed,
)
hidden_states = self.norm(self.hc_head(hidden_states))
hidden_states = self.norm(self.hc_head(mhc_states))
return MoeModelOutputWithPast(last_hidden_state=hidden_states)
@@ -0,0 +1,646 @@
# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Triton kernels vendored from NVIDIA/Megatron-LM under the BSD-3-clause license
# reproduced above, megatron/core/fusions/fused_mhc_kernels.py at commit bb5dfd08f,
# trimmed to the Sinkhorn-Knopp and h_post_bda fusions and rewrapped as the
# `prime_rl::dsv4_mhc_*` custom ops.
import math
import torch
import triton
import triton.language as tl
LOG2E = math.log2(math.e)
TLOG2E = tl.constexpr(LOG2E)
@triton.autotune(configs=[triton.Config({}, num_warps=nw) for nw in (1, 2, 4, 8)], key=["HC", "NUM_ITERS"])
@triton.jit
def _triton_sinkhorn_fwd_kernel(inp_ptr, out_ptr, M_init_ptr, N_batch, eps, HC: tl.constexpr, NUM_ITERS: tl.constexpr):
"""Grid: (N_batch,). Each program handles one [HC, HC] matrix."""
pid = tl.program_id(0)
if pid >= N_batch:
return
base = pid * HC * HC
offs_r = tl.arange(0, HC)
offs_c = tl.arange(0, HC)
mat_ptrs = base + offs_r[:, None] * HC + offs_c[None, :]
logits = tl.load(inp_ptr + mat_ptrs).to(tl.float32)
row_max = tl.max(logits, axis=1)
# Subtract row_max before exp to keep the exponent numerically stable.
M = tl.exp2((logits - row_max[:, None]) * TLOG2E)
tl.store(M_init_ptr + mat_ptrs, M.to(M_init_ptr.dtype.element_ty))
row_sum = tl.sum(M, axis=1)
M = M / row_sum[:, None] + eps
col_sum = tl.sum(M, axis=0)
M = M / (col_sum[None, :] + eps)
for _ in range(NUM_ITERS - 1):
row_sum = tl.sum(M, axis=1)
M = M / (row_sum[:, None] + eps)
col_sum = tl.sum(M, axis=0)
M = M / (col_sum[None, :] + eps)
tl.store(out_ptr + mat_ptrs, M.to(out_ptr.dtype.element_ty))
@triton.autotune(configs=[triton.Config({}, num_warps=nw) for nw in (1, 2, 4, 8)], key=["HC", "NUM_ITERS"])
@triton.jit
def _triton_sinkhorn_bwd_kernel(
grad_out_ptr,
M_init_ptr,
grad_inp_ptr,
ws_M_ptr,
ws_rs_ptr,
ws_cs_ptr,
N_batch,
eps,
HC: tl.constexpr,
NUM_ITERS: tl.constexpr,
):
"""Grid: (N_batch,). Each program handles one [HC, HC] backward."""
pid = tl.program_id(0)
if pid >= N_batch:
return
base = pid * HC * HC
M_ws_base = pid * 2 * NUM_ITERS * HC * HC
v_ws_base = pid * NUM_ITERS
offs_r = tl.arange(0, HC)
offs_c = tl.arange(0, HC)
mat_ptrs = base + offs_r[:, None] * HC + offs_c[None, :]
M = tl.load(M_init_ptr + mat_ptrs).to(tl.float32)
for t in range(NUM_ITERS):
ws_off = M_ws_base + (2 * t) * HC * HC
tl.store(ws_M_ptr + ws_off + offs_r[:, None] * HC + offs_c[None, :], M)
row_sum = tl.sum(M, axis=1)
tl.store(ws_rs_ptr + (v_ws_base + t) * HC + offs_r, row_sum)
if t == 0:
M = M / row_sum[:, None] + eps
else:
M = M / (row_sum[:, None] + eps)
ws_off = M_ws_base + (2 * t + 1) * HC * HC
tl.store(ws_M_ptr + ws_off + offs_r[:, None] * HC + offs_c[None, :], M)
col_sum = tl.sum(M, axis=0)
tl.store(ws_cs_ptr + (v_ws_base + t) * HC + offs_c, col_sum)
M = M / (col_sum[None, :] + eps)
# M is the final forward output. It is the right value for the first VJP
# through the last column-normalization step.
grad = tl.load(grad_out_ptr + mat_ptrs).to(tl.float32)
for t_rev in range(NUM_ITERS):
t = NUM_ITERS - 1 - t_rev
col_s = tl.load(ws_cs_ptr + (v_ws_base + t) * HC + offs_c).to(tl.float32)
grad = grad / (col_s[None, :] + eps)
col_corr = tl.sum(grad * M, axis=0)
grad = grad - col_corr[None, :]
M = tl.load(ws_M_ptr + M_ws_base + (2 * t + 1) * HC * HC + offs_r[:, None] * HC + offs_c[None, :]).to(
tl.float32
)
row_s = tl.load(ws_rs_ptr + (v_ws_base + t) * HC + offs_r).to(tl.float32)
if t == 0:
grad = grad / row_s[:, None]
row_corr = tl.sum(grad * (M - eps), axis=1)
else:
grad = grad / (row_s[:, None] + eps)
row_corr = tl.sum(grad * M, axis=1)
grad = grad - row_corr[:, None]
M = tl.load(ws_M_ptr + M_ws_base + (2 * t) * HC * HC + offs_r[:, None] * HC + offs_c[None, :]).to(tl.float32)
M_init = tl.load(M_init_ptr + mat_ptrs).to(tl.float32)
grad = grad * M_init
tl.store(grad_inp_ptr + mat_ptrs, grad.to(grad_inp_ptr.dtype.element_ty))
def _triton_sinkhorn_fwd(
input_logits: torch.Tensor, num_iterations: int, eps: float
) -> tuple[torch.Tensor, torch.Tensor]:
original_shape = input_logits.shape
hc = original_shape[-1]
N_batch = input_logits.numel() // (hc * hc)
dev = input_logits.device
out = torch.empty(N_batch, hc, hc, dtype=input_logits.dtype, device=dev)
M_init = torch.empty(N_batch, hc, hc, dtype=input_logits.dtype, device=dev)
inp = input_logits.contiguous().view(N_batch, hc, hc)
_triton_sinkhorn_fwd_kernel[(N_batch,)](inp, out, M_init, N_batch, eps, hc, num_iterations)
return out.view(original_shape), M_init.view(original_shape)
def _triton_sinkhorn_bwd(
grad_output: torch.Tensor, M_init: torch.Tensor, num_iterations: int, eps: float
) -> torch.Tensor:
original_shape = grad_output.shape
hc = original_shape[-1]
N_batch = grad_output.numel() // (hc * hc)
dev = grad_output.device
grad_input = torch.empty(N_batch, hc, hc, dtype=grad_output.dtype, device=dev)
go = grad_output.contiguous().view(N_batch, hc, hc)
mi = M_init.contiguous().view(N_batch, hc, hc)
ws_M = torch.empty(N_batch * 2 * num_iterations * hc * hc, dtype=torch.float32, device=dev)
ws_rs = torch.empty(N_batch * num_iterations * hc, dtype=torch.float32, device=dev)
ws_cs = torch.empty(N_batch * num_iterations * hc, dtype=torch.float32, device=dev)
_triton_sinkhorn_bwd_kernel[(N_batch,)](go, mi, grad_input, ws_M, ws_rs, ws_cs, N_batch, eps, hc, num_iterations)
return grad_input.view(original_shape)
@triton.autotune(
configs=[
triton.Config({"BLOCK_C": bc, "BLOCK_S": bs}, num_warps=nw)
for bc in (64, 128, 256, 512)
for bs in (1, 2, 4, 8)
for nw in (2, 4, 8)
],
key=["C", "N"],
)
@triton.jit
def _triton_hpb_fwd_kernel(
hr_ptr,
orig_ptr,
hp_ptr,
x_ptr,
bias_ptr,
out_ptr,
sb,
C: tl.constexpr,
N: tl.constexpr,
stride_hr_s,
stride_hr_i,
stride_hr_j,
stride_orig_s,
stride_orig_n,
stride_orig_c,
stride_out_s,
stride_out_n,
stride_out_c,
HAS_BIAS: tl.constexpr,
BLOCK_C: tl.constexpr,
BLOCK_S: tl.constexpr,
):
"""out = hr.T @ orig + hp * (x + bias)."""
pid_s = tl.program_id(0)
pid_c = tl.program_id(1)
offs_s = pid_s * BLOCK_S + tl.arange(0, BLOCK_S)
offs_c = pid_c * BLOCK_C + tl.arange(0, BLOCK_C)
mask_s = offs_s < sb
mask_c = offs_c < C
mask_2d = mask_s[:, None] & mask_c[None, :]
x_tile = tl.load(x_ptr + offs_s[:, None] * C + offs_c[None, :], mask=mask_2d, other=0.0).to(tl.float32)
if HAS_BIAS:
bias_tile = tl.load(bias_ptr + offs_c, mask=mask_c, other=0.0).to(tl.float32)
x_tile += bias_tile[None, :]
for i in tl.static_range(N):
hp_i = tl.load(hp_ptr + offs_s * N + i, mask=mask_s, other=0.0).to(tl.float32)
out_i = hp_i[:, None] * x_tile
for j in tl.static_range(N):
hr_ji = tl.load(
hr_ptr + offs_s * stride_hr_s + j * stride_hr_i + i * stride_hr_j,
mask=mask_s,
other=0.0,
).to(tl.float32)
orig_j = tl.load(
orig_ptr + offs_s[:, None] * stride_orig_s + j * stride_orig_n + offs_c[None, :],
mask=mask_2d,
other=0.0,
).to(tl.float32)
out_i += hr_ji[:, None] * orig_j
tl.store(
out_ptr + offs_s[:, None] * stride_out_s + i * stride_out_n + offs_c[None, :],
out_i.to(out_ptr.dtype.element_ty),
mask=mask_2d,
)
def _triton_h_post_bda_fwd(
h_res: torch.Tensor, original_residual: torch.Tensor, h_post: torch.Tensor, x: torch.Tensor
) -> torch.Tensor:
s, b, n, C = original_residual.shape
sb = s * b
dev = h_res.device
out = torch.empty(sb, n, C, dtype=h_res.dtype, device=dev)
hr_flat = h_res.contiguous().view(sb, n, n)
orig_flat = original_residual.contiguous().view(sb, n, C)
hp_flat = h_post.contiguous().view(sb, n)
x_flat = x.contiguous().view(sb, C)
grid = lambda META: (triton.cdiv(sb, META["BLOCK_S"]), triton.cdiv(C, META["BLOCK_C"]))
_triton_hpb_fwd_kernel[grid](
hr_flat,
orig_flat,
hp_flat,
x_flat,
x_flat,
out,
sb,
C,
n,
hr_flat.stride(0),
hr_flat.stride(1),
hr_flat.stride(2),
orig_flat.stride(0),
orig_flat.stride(1),
orig_flat.stride(2),
out.stride(0),
out.stride(1),
out.stride(2),
HAS_BIAS=False,
)
return out.view(s, b, n, C)
@triton.autotune(
configs=[
triton.Config({"BLOCK_C": bc, "BLOCK_S": bs}, num_warps=nw)
for bc in (64, 128, 256, 512)
for bs in (1, 2, 4, 8)
for nw in (2, 4, 8)
],
key=["C", "N"],
)
@triton.jit
def _triton_hpb_bwd_g_x_orig_kernel(
go_ptr,
hr_ptr,
hp_ptr,
g_orig_ptr,
g_x_ptr,
sb,
C: tl.constexpr,
N: tl.constexpr,
stride_go_s,
stride_go_n,
stride_go_c,
stride_hr_s,
stride_hr_i,
stride_hr_j,
stride_orig_s,
stride_orig_n,
stride_orig_c,
BLOCK_C: tl.constexpr,
BLOCK_S: tl.constexpr,
):
"""g_x = hp @ go, g_orig = hr @ go."""
pid_s = tl.program_id(0)
pid_c = tl.program_id(1)
offs_s = pid_s * BLOCK_S + tl.arange(0, BLOCK_S)
offs_c = pid_c * BLOCK_C + tl.arange(0, BLOCK_C)
mask_s = offs_s < sb
mask_c = offs_c < C
mask_2d = mask_s[:, None] & mask_c[None, :]
g_x_acc = tl.zeros((BLOCK_S, BLOCK_C), dtype=tl.float32)
for j in tl.static_range(N):
go_j = tl.load(
go_ptr + offs_s[:, None] * stride_go_s + j * stride_go_n + offs_c[None, :],
mask=mask_2d,
other=0.0,
).to(tl.float32)
hp_j = tl.load(hp_ptr + offs_s * N + j, mask=mask_s, other=0.0).to(tl.float32)
g_x_acc += hp_j[:, None] * go_j
tl.store(
g_x_ptr + offs_s[:, None] * C + offs_c[None, :],
g_x_acc.to(g_x_ptr.dtype.element_ty),
mask=mask_2d,
)
for i in tl.static_range(N):
g_orig_i = tl.zeros((BLOCK_S, BLOCK_C), dtype=tl.float32)
for j in tl.static_range(N):
go_j = tl.load(
go_ptr + offs_s[:, None] * stride_go_s + j * stride_go_n + offs_c[None, :],
mask=mask_2d,
other=0.0,
).to(tl.float32)
hr_ij = tl.load(
hr_ptr + offs_s * stride_hr_s + i * stride_hr_i + j * stride_hr_j,
mask=mask_s,
other=0.0,
).to(tl.float32)
g_orig_i += hr_ij[:, None] * go_j
tl.store(
g_orig_ptr + offs_s[:, None] * stride_orig_s + i * stride_orig_n + offs_c[None, :],
g_orig_i.to(g_orig_ptr.dtype.element_ty),
mask=mask_2d,
)
@triton.autotune(
configs=[
triton.Config({"BLOCK_C": bc, "BLOCK_S": bs}, num_warps=nw)
for bc in (64, 128, 256, 512)
for bs in (1, 2, 4, 8)
for nw in (2, 4, 8)
],
key=["C", "N"],
)
@triton.jit
def _triton_hpb_bwd_g_hp_hr_kernel(
go_ptr,
orig_ptr,
x_ptr,
bias_ptr,
g_hr_ptr,
g_hp_ptr,
sb,
C: tl.constexpr,
N: tl.constexpr,
stride_go_s,
stride_go_n,
stride_go_c,
stride_orig_s,
stride_orig_n,
stride_orig_c,
stride_hr_s,
stride_hr_i,
stride_hr_j,
HAS_BIAS: tl.constexpr,
BLOCK_C: tl.constexpr,
BLOCK_S: tl.constexpr,
):
"""g_hp = sum_c go*(x+bias), g_hr = orig @ go.T."""
pid_s = tl.program_id(0)
offs_s = pid_s * BLOCK_S + tl.arange(0, BLOCK_S)
mask_s = offs_s < sb
g_hp_acc = tl.zeros((BLOCK_S, N), dtype=tl.float32)
g_hr_acc = tl.zeros((BLOCK_S, N * N), dtype=tl.float32)
for c_start in range(0, C, BLOCK_C):
offs_c = c_start + tl.arange(0, BLOCK_C)
mask_c = offs_c < C
mask_2d = mask_s[:, None] & mask_c[None, :]
x_tile = tl.load(x_ptr + offs_s[:, None] * C + offs_c[None, :], mask=mask_2d, other=0.0).to(tl.float32)
if HAS_BIAS:
bias_tile = tl.load(bias_ptr + offs_c, mask=mask_c, other=0.0).to(tl.float32)
x_tile += bias_tile[None, :]
for i in tl.static_range(N):
go_i = tl.load(
go_ptr + offs_s[:, None] * stride_go_s + i * stride_go_n + offs_c[None, :],
mask=mask_2d,
other=0.0,
).to(tl.float32)
dot_hp = tl.sum(go_i * x_tile, axis=1)
g_hp_acc += tl.where(
tl.arange(0, N)[None, :] == i,
dot_hp[:, None],
tl.zeros((BLOCK_S, N), dtype=tl.float32),
)
for j in tl.static_range(N):
orig_j = tl.load(
orig_ptr + offs_s[:, None] * stride_orig_s + j * stride_orig_n + offs_c[None, :],
mask=mask_2d,
other=0.0,
).to(tl.float32)
dot_hr = tl.sum(go_i * orig_j, axis=1)
g_hr_acc += tl.where(
tl.arange(0, N * N)[None, :] == j * N + i,
dot_hr[:, None],
tl.zeros((BLOCK_S, N * N), dtype=tl.float32),
)
offs_n = tl.arange(0, N)
tl.store(
g_hp_ptr + offs_s[:, None] * N + offs_n[None, :],
g_hp_acc.to(g_hp_ptr.dtype.element_ty),
mask=mask_s[:, None],
)
# N is expected to stay small for mHC, so this simple extraction is acceptable.
nn_offs = tl.arange(0, N * N)
for i in tl.static_range(N):
for j in tl.static_range(N):
col_mask = (nn_offs == (i * N + j)).to(tl.float32)
val = tl.sum(g_hr_acc * col_mask[None, :], axis=1)
tl.store(
g_hr_ptr + offs_s * stride_hr_s + i * stride_hr_i + j * stride_hr_j,
val.to(g_hr_ptr.dtype.element_ty),
mask=mask_s,
)
def _triton_h_post_bda_bwd(
grad_output: torch.Tensor,
h_res: torch.Tensor,
original_residual: torch.Tensor,
h_post: torch.Tensor,
x: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
s, b, n, C = original_residual.shape
sb = s * b
dev = h_res.device
g_hr = torch.empty(sb, n, n, dtype=h_res.dtype, device=dev)
g_res = torch.empty(sb, n, C, dtype=original_residual.dtype, device=dev)
g_hp = torch.empty(sb, n, dtype=h_post.dtype, device=dev)
g_x = torch.empty(sb, C, dtype=x.dtype, device=dev)
go_flat = grad_output.contiguous().view(sb, n, C)
hr_flat = h_res.contiguous().view(sb, n, n)
orig_flat = original_residual.contiguous().view(sb, n, C)
hp_flat = h_post.contiguous().view(sb, n)
x_flat = x.contiguous().view(sb, C)
grid_a = lambda META: (triton.cdiv(sb, META["BLOCK_S"]), triton.cdiv(C, META["BLOCK_C"]))
_triton_hpb_bwd_g_x_orig_kernel[grid_a](
go_flat,
hr_flat,
hp_flat,
g_res,
g_x,
sb,
C,
n,
go_flat.stride(0),
go_flat.stride(1),
go_flat.stride(2),
hr_flat.stride(0),
hr_flat.stride(1),
hr_flat.stride(2),
g_res.stride(0),
g_res.stride(1),
g_res.stride(2),
)
grid_b = lambda META: (triton.cdiv(sb, META["BLOCK_S"]),)
_triton_hpb_bwd_g_hp_hr_kernel[grid_b](
go_flat,
orig_flat,
x_flat,
x_flat,
g_hr,
g_hp,
sb,
C,
n,
go_flat.stride(0),
go_flat.stride(1),
go_flat.stride(2),
orig_flat.stride(0),
orig_flat.stride(1),
orig_flat.stride(2),
g_hr.stride(0),
g_hr.stride(1),
g_hr.stride(2),
HAS_BIAS=False,
)
return (
g_hr.view(s, b, n, n),
g_res.view(s, b, n, C),
g_hp.view(s, b, n),
g_x.view(s, b, C),
)
@torch.library.custom_op("prime_rl::dsv4_mhc_sinkhorn", mutates_args=())
def _mhc_sinkhorn(logits: torch.Tensor, num_iterations: int, eps: float) -> tuple[torch.Tensor, torch.Tensor]:
return _triton_sinkhorn_fwd(logits, num_iterations, eps)
@_mhc_sinkhorn.register_fake
def _mhc_sinkhorn_fake(logits: torch.Tensor, num_iterations: int, eps: float) -> tuple[torch.Tensor, torch.Tensor]:
return torch.empty_like(logits), torch.empty_like(logits)
@torch.library.custom_op("prime_rl::dsv4_mhc_sinkhorn_backward", mutates_args=())
def _mhc_sinkhorn_backward(
grad_output: torch.Tensor, m_init: torch.Tensor, num_iterations: int, eps: float
) -> torch.Tensor:
return _triton_sinkhorn_bwd(grad_output, m_init, num_iterations, eps)
@_mhc_sinkhorn_backward.register_fake
def _mhc_sinkhorn_backward_fake(
grad_output: torch.Tensor, m_init: torch.Tensor, num_iterations: int, eps: float
) -> torch.Tensor:
return torch.empty_like(grad_output)
def _mhc_sinkhorn_setup_context(ctx, inputs, output) -> None:
_, num_iterations, eps = inputs
ctx.save_for_backward(output[1])
ctx.num_iterations = num_iterations
ctx.eps = eps
def _mhc_sinkhorn_autograd_backward(ctx, grad_output: torch.Tensor, grad_m_init: torch.Tensor):
(m_init,) = ctx.saved_tensors
grad_logits = _mhc_sinkhorn_backward(grad_output, m_init, ctx.num_iterations, ctx.eps)
return grad_logits, None, None
_mhc_sinkhorn.register_autograd(_mhc_sinkhorn_autograd_backward, setup_context=_mhc_sinkhorn_setup_context)
def fused_sinkhorn(logits: torch.Tensor, num_iterations: int, eps: float) -> torch.Tensor:
"""Project logits onto the doubly stochastic manifold, one Triton program per matrix."""
out, _ = _mhc_sinkhorn(logits, num_iterations, eps)
return out
@torch.library.custom_op("prime_rl::dsv4_mhc_post_bda", mutates_args=())
def _mhc_post_bda(
h_res: torch.Tensor, original_residual: torch.Tensor, h_post: torch.Tensor, x: torch.Tensor
) -> torch.Tensor:
return _triton_h_post_bda_fwd(h_res, original_residual, h_post, x)
@_mhc_post_bda.register_fake
def _mhc_post_bda_fake(
h_res: torch.Tensor, original_residual: torch.Tensor, h_post: torch.Tensor, x: torch.Tensor
) -> torch.Tensor:
return torch.empty_like(original_residual, dtype=h_res.dtype)
@torch.library.custom_op("prime_rl::dsv4_mhc_post_bda_backward", mutates_args=())
def _mhc_post_bda_backward(
grad_output: torch.Tensor,
h_res: torch.Tensor,
original_residual: torch.Tensor,
h_post: torch.Tensor,
x: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
return _triton_h_post_bda_bwd(grad_output, h_res, original_residual, h_post, x)
@_mhc_post_bda_backward.register_fake
def _mhc_post_bda_backward_fake(
grad_output: torch.Tensor,
h_res: torch.Tensor,
original_residual: torch.Tensor,
h_post: torch.Tensor,
x: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
return (
torch.empty_like(h_res),
torch.empty_like(original_residual),
torch.empty_like(h_post),
torch.empty_like(x),
)
def _mhc_post_bda_setup_context(ctx, inputs, output) -> None:
h_res, original_residual, h_post, x = inputs
ctx.save_for_backward(h_res, original_residual, h_post, x)
def _mhc_post_bda_autograd_backward(ctx, grad_output: torch.Tensor):
h_res, original_residual, h_post, x = ctx.saved_tensors
needs = ctx.needs_input_grad
g_hr, g_res, g_hp, g_x = _mhc_post_bda_backward(grad_output, h_res, original_residual, h_post, x)
return (
g_hr if needs[0] else None,
g_res if needs[1] else None,
g_hp if needs[2] else None,
g_x if needs[3] else None,
)
_mhc_post_bda.register_autograd(_mhc_post_bda_autograd_backward, setup_context=_mhc_post_bda_setup_context)
def fused_post_bda(
h_res: torch.Tensor, original_residual: torch.Tensor, h_post: torch.Tensor, x: torch.Tensor
) -> torch.Tensor:
"""Fused stream write-back `h_res.T @ original_residual + h_post * x`.
The kernel applies the transpose internally, so `h_res` is passed untransposed.
"""
return _mhc_post_bda(h_res, original_residual, h_post, x)
@@ -17,7 +17,7 @@ from prime_rl.trainer.models.kernels.fp8_utils import (
def _compute_grad_weight(
x: torch.Tensor,
grad_output: torch.Tensor,
weight_shape: torch.Size,
weight: torch.Tensor,
padded_total_m: int,
block_to_group: torch.Tensor,
ks_tensor: torch.Tensor,
@@ -78,7 +78,7 @@ def _compute_grad_weight(
)
grouped_weight_grad = deep_gemm.k_grouped_fp8_gemm_nt_contiguous
grad_weight = torch.zeros(weight_shape, device=x.device, dtype=torch.float32)
grad_weight = torch.zeros(weight.shape, device=x.device, dtype=torch.float32)
grouped_weight_grad(
x_fp8,
dy_fp8,
@@ -87,7 +87,7 @@ def _compute_grad_weight(
ks_tensor,
grad_weight,
)
return grad_weight.to(torch.bfloat16)
return grad_weight.to(weight.dtype)
@torch.library.custom_op("prime_rl::grouped_fp8_gemm", mutates_args=())
@@ -165,14 +165,14 @@ def _grouped_fp8_gemm_backward(
block_starts_tensor,
) = build_grouped_layout(offs, total_m=x.size(0))
grad_output = grad_output.contiguous()
grad_x = torch.empty_like(x)
grad_weight = torch.empty_like(weight)
grad_x = x.new_empty(x.shape)
grad_weight = weight.new_empty(weight.shape)
if needs_grad_weight:
grad_weight = _compute_grad_weight(
x,
grad_output,
weight.shape,
weight,
padded_total_m,
block_to_group,
ks_tensor,
@@ -230,7 +230,7 @@ def _grouped_fp8_gemm_backward_fake(
needs_grad_x: bool,
needs_grad_weight: bool,
) -> tuple[torch.Tensor, torch.Tensor]:
return torch.empty_like(x), torch.empty_like(weight)
return x.new_empty(x.shape), weight.new_empty(weight.shape)
def _grouped_fp8_gemm_setup_context(ctx, inputs, output) -> None:
@@ -48,8 +48,8 @@ def _fp8_blockwise_mm_backward(
x_2d = x.reshape(-1, x.shape[-1]).contiguous()
grad_output_2d = grad_output.reshape(-1, grad_output.shape[-1]).contiguous()
use_ue8m0 = ue8m0_for_device(grad_output.device)
grad_x = torch.empty_like(x)
grad_weight = torch.empty_like(weight)
grad_x = x.new_empty(x.shape)
grad_weight = weight.new_empty(weight.shape)
if needs_grad_x:
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, use_ue8m0, block_size)
@@ -68,7 +68,7 @@ def _fp8_blockwise_mm_backward(
x_2d = torch.nn.functional.pad(x_2d, (0, 0, 0, pad_rows))
grad_output_t_fp8 = per_token_cast_to_fp8_tp_triton(grad_output_2d, use_ue8m0, block_size)
x_t_fp8 = per_token_cast_to_fp8_tp_triton(x_2d, use_ue8m0, block_size)
grad_weight_fp32 = torch.zeros_like(weight, dtype=torch.float32)
grad_weight_fp32 = torch.zeros(weight.shape, device=weight.device, dtype=torch.float32)
deep_gemm.fp8_gemm_nt(
grad_output_t_fp8,
x_t_fp8,
@@ -90,7 +90,7 @@ def _fp8_blockwise_mm_backward_fake(
needs_grad_x: bool,
needs_grad_weight: bool,
) -> tuple[torch.Tensor, torch.Tensor]:
return torch.empty_like(x), torch.empty_like(weight)
return x.new_empty(x.shape), weight.new_empty(weight.shape)
def _fp8_blockwise_mm_setup_context(ctx, inputs, output) -> None:
+2 -2
View File
@@ -8,7 +8,7 @@ from transformers.integrations import use_kernel_forward_from_hub
@lru_cache(maxsize=1)
def _get_quack_rmsnorm():
def get_quack_rmsnorm():
"""Lazy-load quack rmsnorm. Returns None if unavailable or GPU is pre-Hopper."""
if not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] < 9:
return None
@@ -34,7 +34,7 @@ class RMSNorm(nn.Module):
self.variance_epsilon = config.eps
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
quack_fn = _get_quack_rmsnorm() if hidden_states.is_cuda else None
quack_fn = get_quack_rmsnorm() if hidden_states.is_cuda else None
if quack_fn is not None:
return quack_fn(hidden_states, self.weight, eps=self.variance_epsilon)
input_dtype = hidden_states.dtype
@@ -272,7 +272,7 @@ def _ring_attention_forward_fake(
window_size_right: int,
attention_backend: str,
) -> tuple[torch.Tensor, torch.Tensor]:
return torch.empty_like(q), q.new_empty((q.shape[1], q.shape[0]), dtype=torch.float32)
return q.new_empty(q.shape), q.new_empty((q.shape[1], q.shape[0]), dtype=torch.float32)
@torch.library.custom_op("prime_rl_ring::attention_backward", mutates_args=())
+1 -1
View File
@@ -105,7 +105,7 @@ def _torch_rms_norm(monkeypatch):
The kernel is a project-wide choice that predates this model and drifts from a fp32
reference by up to ~1e-2 in bf16, which would swamp what the V4-specific math contributes.
"""
monkeypatch.setattr(norms, "_get_quack_rmsnorm", lambda: None)
monkeypatch.setattr(norms, "get_quack_rmsnorm", lambda: None)
def _tid2eid(vocab_size: int, num_experts: int, top_k: int) -> torch.Tensor:
@@ -12,8 +12,9 @@ from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, eager_referenc
from prime_rl.trainer.models.deepseek_v4 import attention as dsv4_attention
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, PackedContext
from prime_rl.trainer.models.deepseek_v4.eager_reference import dense_mask_from_indices, eager_attention_with_sinks
from prime_rl.trainer.models.deepseek_v4.hyperconnections import DeepseekV4HyperConnection
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding, apply_rotary_pos_emb_interleaved
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT, dsv4_mhc
from prime_rl.utils.cp import CPContext
from prime_rl.utils.utils import default_dtype
@@ -1257,3 +1258,64 @@ def test_context_parallel_shards_reproduce_the_whole_row(layer_idx, cp_world_siz
_assert_relative(hidden_full.grad, reference_input_grad, PACKED_GRAD_RTOL, "hidden states gradient")
_compare_accumulated_grads(module, reference_grads)
MHC_SHAPES = [(1, 256), (1, 203), (3, 67)]
MHC_SHAPE_IDS = ["aligned", "misaligned", "batched"]
SINKHORN_RTOL = 1e-5
SINKHORN_GRAD_RTOL = 1e-5
POST_BDA_RTOL = 1e-2
POST_BDA_GRAD_RTOL = 1e-2
@pytest.mark.parametrize(("batch", "seq_len"), MHC_SHAPES, ids=MHC_SHAPE_IDS)
def test_fused_sinkhorn_matches_the_eager_reference(batch, seq_len):
hc = V4FLASH_MODEL["hc_mult"]
iters, eps = V4FLASH_MODEL["hc_sinkhorn_iters"], V4FLASH_MODEL["hc_eps"]
with torch.device("cuda"):
logits = torch.randn(batch, seq_len, hc, hc)
weight = torch.randn(batch, seq_len, hc, hc)
fused_logits, reference_logits = _leaves(logits, logits)
fused_comb = dsv4_mhc.fused_sinkhorn(fused_logits, iters, eps)
(fused_comb * weight).sum().backward()
reference_comb = eager_reference.eager_sinkhorn(reference_logits, iters, eps)
(reference_comb * weight).sum().backward()
_assert_relative(fused_comb, reference_comb, SINKHORN_RTOL, "comb")
_assert_relative(fused_logits.grad, reference_logits.grad, SINKHORN_GRAD_RTOL, "logits gradient")
def test_fused_post_bda_matches_the_eager_reference():
batch, seq_len = 2, 129
hc, dim = V4FLASH_MODEL["hc_mult"], V4FLASH_MODEL["hidden_size"]
with torch.device("cuda"):
module = DeepseekV4HyperConnection(V4FLASH_CONFIG)
streams = torch.randn(batch, seq_len, hc, dim, dtype=torch.bfloat16)
sublayer_out = torch.randn(batch, seq_len, dim, dtype=torch.bfloat16)
post = 2 * torch.sigmoid(torch.randn(batch, seq_len, hc))
comb = torch.softmax(torch.randn(batch, seq_len, hc, hc), dim=-1)
weight = torch.randn(batch, seq_len, hc, dim, dtype=torch.bfloat16)
fused_post, fused_comb, fused_x, fused_streams = _leaves(post, comb, sublayer_out, streams)
reference_post, reference_comb, reference_x, reference_streams = _leaves(post, comb, sublayer_out, streams)
fused_out = module.update_states(fused_post, fused_comb, fused_x, fused_streams)
(fused_out * weight).sum().backward()
reference_out = eager_reference.eager_update_states(reference_post, reference_comb, reference_x, reference_streams)
(reference_out * weight).sum().backward()
_assert_relative(fused_out, reference_out, POST_BDA_RTOL, "write-back output")
grads = (
("post gradient", fused_post, reference_post),
("comb gradient", fused_comb, reference_comb),
("sublayer output gradient", fused_x, reference_x),
("streams gradient", fused_streams, reference_streams),
)
for label, fused_leaf, reference_leaf in grads:
assert reference_leaf.grad is not None, f"{label}: the reference backward left the leaf without a gradient"
_assert_relative(fused_leaf.grad, reference_leaf.grad, POST_BDA_GRAD_RTOL, label)