Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dd2dd5461b | ||
|
|
cea63f9ef3 | ||
|
|
6a360c3029 | ||
|
|
04a61d3b75 | ||
|
|
26b3131d27 | ||
|
|
ef9dea1781 | ||
|
|
6c7b1ef375 | ||
|
|
608c75c0af | ||
|
|
b28714289a | ||
|
|
903baaaa01 | ||
|
|
ae170acda1 | ||
|
|
c84068cf9e | ||
|
|
7ad1bb9123 | ||
|
|
5990b1b9ba | ||
|
|
ffb845c13c |
Vendored
+1
-1
Submodule deps/verifiers updated: 3ed6ef7c2c...392d596de8
@@ -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
@@ -110,7 +110,7 @@ For DeepEP, set `type = "deepep"` and tune `num_sms` plus optional `token_chunk_
|
||||
|
||||
### Context Parallelism
|
||||
|
||||
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. We reccomend using `ulysses` style CP for most of the models to get the most throughput. Some models (e.g. GLM-5) only support `ring` style CP. Wrong setting will be rejected on validation.
|
||||
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. Prefer `ulysses`: it gets the most throughput and is the only style that works for hybrid linear-attention/Mamba models (Qwen3.5, NemotronH) and for VLMs. Each model class declares its supported styles in `cp_support`; an unsupported `cp_style`, or a model with no CP support at all (DeepSeek V4, GPT-OSS), is rejected at setup.
|
||||
|
||||
`ulysses` head-shards Q/K/V, so the CP degree must divide `num_attention_heads`. GQA models with fewer KV heads than the CP degree (e.g. NemotronH: 32 query heads, 2 KV heads) are supported via KV-head replication; the CP degree must then be a multiple of `num_key_value_heads`. Hybrid Mamba layers head-shard independently (`cp_mamba`), which requires the CP degree to divide `mamba_num_heads` and `n_groups`.
|
||||
|
||||
|
||||
+3
-3
@@ -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.
|
||||
|
||||
@@ -387,9 +387,9 @@ Or set it in TOML:
|
||||
name = "my-experiment"
|
||||
```
|
||||
|
||||
Every 10th step the orchestrator uploads the step's episodes (full conversations with rewards and advantages) to the run's sample viewer.
|
||||
The monitor is a thin layer over the [`prime-runs`](https://github.com/PrimeIntellect-ai/prime/tree/main/packages/prime-runs) SDK (installed as `prime-runs[train]`): it registers the run, streams per-step metrics, uploads every 10th step's episodes (full conversations with rewards and advantages) to the run's sample viewer, and closes the run out. A process that exits without finishing is reported as crashed. Uploaded episodes are keyed to the platform run by the SDK; the orchestrator's own run id (the launcher's `PRL_RUN_ID`) stays on W&B and in the local records.
|
||||
|
||||
Requires `PRIME_API_KEY` (set via `prime login` or env var) and an allowlisted team. Currently internal-only.
|
||||
Requires `PRIME_API_KEY` (`prime login` or the env var) and a team (`PRIME_TEAM_ID`, or the team selected with `prime login`) enabled for external runs. A configured monitor must work: a missing key or a team outside the allowlist fails the launch. `PRIME_RUNS_MODE=disabled` keeps the monitor configured but opens no platform run; `RUN_ID=<id>` attaches to an external run a launcher already created instead of registering a new one. Currently internal-only.
|
||||
|
||||
## Rules of Thumb
|
||||
|
||||
|
||||
+1
-1
@@ -12,6 +12,6 @@ End-to-end usage examples for prime-rl, referenced from the top-level [README](.
|
||||
- **[`advanced/`](advanced)** — larger, mostly multi-node runs on frontier models, one folder
|
||||
per model: `qwen3-30b-a3b` (math/swe/tool), `glm-4.5-air` (search/swe/terminal), `glm-5.2`
|
||||
(large-scale + PD-disaggregated inference), `minimax-m2.5` (swe), `nemotron-3-super` (swe),
|
||||
`intellect-3.1` (swe).
|
||||
`intellect-3.1` (swe), `deepseek-v4-flash` (sft + a standalone vLLM serving pre-flight).
|
||||
|
||||
Dev-sized (2-GPU) counterparts of `basic/` live in [`configs/basic/`](../configs/basic).
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# Standalone vLLM serving pre-flight: does this cluster's vLLM serve the real DeepSeek V4 Flash
|
||||
# checkpoint at all, independent of the trainer? Uses vLLM's own native DeepSeek V4 support, not
|
||||
# this repo's trainer port. Run directly on one allocated 8xH200 node (no [slurm] block):
|
||||
#
|
||||
# uv run inference @ examples/advanced/deepseek-v4-flash/inference.toml
|
||||
#
|
||||
# Then check /health and a /v1/chat/completions request from another shell on the same node, and
|
||||
# confirm a coherent response before trusting the model for a real run.
|
||||
#
|
||||
# Reference: https://recipes.vllm.ai/deepseek-ai/DeepSeek-V4-Flash
|
||||
|
||||
# Mandatory for the fp8 checkpoint, not an optimization: without it the UE8M0-scaled fp8 weights
|
||||
# route to a CUTLASS kernel that crashes on boot. That crash was observed during SM120 bring-up and
|
||||
# has not been re-tested on Hopper, but the vLLM recipe sets the flag on every NVIDIA configuration.
|
||||
# The mHC pre-norm GEMM does not need it on H200: measured there, the TileLang fallback matches the
|
||||
# reference to 1.3e-06 relative at every token count, including the >= 1024 block-M kernel.
|
||||
use_deep_gemm = true
|
||||
|
||||
[server]
|
||||
port = 8000
|
||||
|
||||
[vllm]
|
||||
model = "deepseek-ai/DeepSeek-V4-Flash-0731"
|
||||
tensor_parallel_size = 8
|
||||
enable_expert_parallel = true
|
||||
gpu_memory_utilization = 0.85
|
||||
max_model_len = 8192
|
||||
# Required, not a tuning choice. Every DeepSeek V4 attention class sets
|
||||
# `use_fp8_ds_mla_layout = True`, and the sparse-MLA layout then asserts
|
||||
# "DeepseekV4 fp8_ds_mla layout only supports fp8 kv-cache" against the `auto` default. The vLLM
|
||||
# recipe sets it on every vendor and every architecture.
|
||||
kv_cache_dtype = "fp8"
|
||||
# Recipe-derived rather than measured here: every NVIDIA configuration in the vLLM recipe pairs
|
||||
# the fp8 KV cache with this block size.
|
||||
block_size = 256
|
||||
@@ -0,0 +1,62 @@
|
||||
# Real-data SFT for deepseek-ai/DeepSeek-V4-Flash-0731 at full depth (all 43 layers, no
|
||||
# `debug.num_layers` truncation) on 4 train nodes. Trainer only: no online eval, no inference
|
||||
# node, and so no weight broadcast. Tested on 8xH200.
|
||||
#
|
||||
# uv run sft @ examples/advanced/deepseek-v4-flash/sft.toml --run.name ds-v4-sft-torch-4node
|
||||
#
|
||||
# Note: on 4 8xH200 nodes, this config is near the memory limit, using ~94%+ GPU memory.
|
||||
#
|
||||
# `dist_timeout_seconds = 14400` is needed on any run that has to build the HF -> prime-rl
|
||||
# conversion cache, which takes far longer than the 3600s default.
|
||||
#
|
||||
# To buy memory back for quicker testing on fewer nodes, set `full_offload = true` under `[model]`,
|
||||
# which keeps the fp32 masters, moments and gradients in CPU RAM and needs `optim_cpu_offload =
|
||||
# false` and `optim.max_norm = "None"` set alongside it; the lighter `optim_cpu_offload = true` is
|
||||
# already the default here.
|
||||
#
|
||||
# There is no `[ckpt]` block. The trainer saves unconditionally at the last step, and a 43-layer
|
||||
# checkpoint (fp32 master weights plus two fp32 AdamW moments) is ~3 TiB. Add one with
|
||||
# `ckpt.output_dir` pointed at a volume that can hold it if you need the trained weights.
|
||||
|
||||
dist_timeout_seconds = 14400
|
||||
max_steps = 20
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-V4-Flash-0731"
|
||||
impl = "custom"
|
||||
ep = 8
|
||||
|
||||
# Torch all-to-all, not DeepEP. At full depth DeepEP dies on the first backward with
|
||||
# "RuntimeError: Autograd not support dtype: Byte", raised from `Tensor.float()` in
|
||||
# `DeepEPTokenDispatcher.combine` while the activation-checkpoint recompute replays through a
|
||||
# `__torch_dispatch__` mode that hands back a uint8 tensor. Reproduced deterministically on 4
|
||||
# nodes against the same weights and conversion cache this config trains on.
|
||||
[model.moe.dispatch]
|
||||
type = "torch"
|
||||
|
||||
[model.ac]
|
||||
freq = 1
|
||||
|
||||
[model.ac_offloading]
|
||||
max_inflight_activations = 5
|
||||
|
||||
[data]
|
||||
name = "PrimeIntellect/Reverse-Text-SFT"
|
||||
seq_len = 2048
|
||||
batch_size = 32
|
||||
|
||||
[optim]
|
||||
lr = 1e-5
|
||||
|
||||
[monitors.wandb]
|
||||
project = "deepseek-v4-flash"
|
||||
name = "deepseek-v4-flash-sft"
|
||||
|
||||
# `num_infer_nodes` defaults to 0, so this allocates 4 nodes and runs only the trainer.
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 4
|
||||
|
||||
[slurm]
|
||||
job_name = "ds-v4-sft"
|
||||
partition = "all"
|
||||
@@ -28,6 +28,20 @@ class FileMonitorConfig(BaseConfig):
|
||||
"""Path of the metrics JSONL file, relative to the file monitor's directory under the
|
||||
component's ``output_dir`` (``monitors/file/``; absolute paths win)."""
|
||||
|
||||
chunk_bytes: int = 5 * 1024**3
|
||||
"""Size at which a trace stream (the episodes, each producer's annotations) rolls to
|
||||
a new numbered chunk file. A line never spans chunks."""
|
||||
|
||||
compress: bool = True
|
||||
"""Seal full chunks with zstd once the stream rolls past them (the live chunk stays
|
||||
plain text). Sealed chunks use seekable frames: a reader still lands on one line,
|
||||
and ``zstd -dcf stream/* | jq`` reads a whole stream."""
|
||||
|
||||
float_decimals: int | None = 4
|
||||
"""Decimals kept for per-token float streams (logprobs, entropies, advantages) in
|
||||
trace and annotation records; ``None`` keeps every digit. Training reads the wire,
|
||||
not the records, so this only trades record size against overlay precision."""
|
||||
|
||||
|
||||
class PrimeMonitorConfig(BaseConfig):
|
||||
name: str | None = None
|
||||
|
||||
@@ -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."""
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
# Trinity-Large-Thinking uses the Qwen3-Coder tool format; the rest of the family is Hermes.
|
||||
(re.compile(r"^arcee-ai/Trinity-Large-Thinking"), "qwen3_coder"),
|
||||
(re.compile(r"^arcee-ai/Trinity-"), "hermes"),
|
||||
(re.compile(r"^deepseek-ai/DeepSeek-V4"), "deepseek_v4"),
|
||||
(re.compile(r"^deepseek-ai/DeepSeek-V3\.2"), "deepseek_v32"),
|
||||
(re.compile(r"^deepseek-ai/DeepSeek-V3\.1"), "deepseek_v31"),
|
||||
(re.compile(r"^zai-org/GLM-4\.5"), "glm45"),
|
||||
@@ -25,6 +26,9 @@ TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
# Trinity-Large-Preview doesn't reason; the Thinking/Mini/Nano variants do.
|
||||
(re.compile(r"^arcee-ai/Trinity-(Large-Thinking|Mini|Nano)"), "deepseek_r1"),
|
||||
# V4 reasons inside <think> blocks, but vLLM only splits them out into `reasoning_content`
|
||||
# when this parser is set; the checkpoint ships no chat template, so nothing else supplies it.
|
||||
(re.compile(r"^deepseek-ai/DeepSeek-V4"), "deepseek_v4"),
|
||||
(re.compile(r"^deepseek-ai/DeepSeek-V3\.[12]"), "deepseek_r1"),
|
||||
(re.compile(r"^zai-org/GLM-"), "glm45"),
|
||||
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2_append_think"),
|
||||
|
||||
+5
-1
@@ -17,12 +17,14 @@ dependencies = [
|
||||
"wandb>=0.26.1",
|
||||
"wandb-workspaces>=0.4.3",
|
||||
"prime>=0.6.19",
|
||||
"prime-runs[train]>=0.1.1",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
"tenacity>=8.2.0",
|
||||
"openai>=1.106.1",
|
||||
"orjson>=3.11.0",
|
||||
"psutil>=7.0.0",
|
||||
"pyzstd>=0.16.2",
|
||||
"rich>=14.0.0",
|
||||
"setproctitle>=1.3.0",
|
||||
"uvloop>=0.21.0",
|
||||
@@ -221,6 +223,8 @@ flash_attn_3 = false
|
||||
# appear in `uv tree` need to be listed; the resolver ignores entries for
|
||||
# packages it never sees.
|
||||
prime = false
|
||||
prime-runs = false
|
||||
prime-traces = false
|
||||
prime-sandboxes = false
|
||||
prime-tunnel = false
|
||||
prime-evals = false
|
||||
@@ -251,7 +255,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'" },
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -167,24 +167,29 @@ curl -s http://localhost:8100/metrics | grep -E "num_requests|gpu_cache_usage"
|
||||
|
||||
```
|
||||
{run_dir}/monitors/file/metrics.jsonl # every metric row, tagged by producer
|
||||
{run_dir}/monitors/file/traces/stream.jsonl # every episode, appended as it arrives
|
||||
{run_dir}/monitors/file/traces/stream.index.jsonl # one compact row per episode, with its byte offset
|
||||
{run_dir}/monitors/file/traces/annotations/{producer}.jsonl # trace updates: orch ship-time facts, trainer per-token streams
|
||||
{run_dir}/monitors/file/traces/stream/00000.jsonl.zst # every episode, appended as it arrives: sealed chunks ...
|
||||
{run_dir}/monitors/file/traces/stream/00001.jsonl # ... and the live one, plain text
|
||||
{run_dir}/monitors/file/traces/stream.index.jsonl # one compact row per episode, with its chunk and byte offset
|
||||
{run_dir}/monitors/file/traces/annotations/{producer}/00000.jsonl # trace updates: orch ship-time facts, trainer per-token streams
|
||||
{run_dir}/monitors/file/traces/annotations/{producer}.index.jsonl # each update's scalars and where its record sits
|
||||
```
|
||||
|
||||
Everything the file monitor dumps lives under `monitors/file/`; nothing is written
|
||||
there when the monitor is off. The traces and everything written about them sit under
|
||||
`traces/`, and every index is named for the stream it indexes and sits beside it. Those
|
||||
indexes are what keep reading a run cheap: a consumer browses them instead of the
|
||||
streams, and seeks by the offsets they carry to read a single episode or its token
|
||||
streams. Both are derived, so deleting them only costs a reader the work of rebuilding
|
||||
what it needs. `stream.jsonl` is a stream of native `vf.Episode`
|
||||
records (training tensors excluded), one line per episode in arrival order, whatever
|
||||
kind of work it did — including trace-less failures, curriculum-rejected work, and
|
||||
work that never enters a batch, so it is crash-durable. Each record carries its
|
||||
provenance: `env` (`id` plus the orchestrator's `name`), full `task`, `group` (`id`),
|
||||
and `run`.
|
||||
`traces/`. Each stream is a directory of numbered chunks — the writer rolls to a new
|
||||
chunk at `monitors.file.chunk_bytes` (5 GiB) and, with `monitors.file.compress` (on),
|
||||
seals the full one with zstd in the background; a finished run seals its live chunk
|
||||
too. Sealed chunks use seekable frames, so a seek still costs one frame, and
|
||||
`zstd -dcf` streams them together with the plain live chunk. Every index is named for
|
||||
the stream it indexes and sits beside it. Those indexes are what keep reading a run
|
||||
cheap: a consumer browses them instead of the streams, and seeks by the chunk and
|
||||
offset they carry to read a single episode or its token streams. Both are derived, so
|
||||
deleting them only costs a reader the work of rebuilding what it needs. The stream
|
||||
holds native `vf.Episode` records (training tensors excluded; per-token floats rounded
|
||||
to `monitors.file.float_decimals`, 4 by default), one line per episode in arrival order, whatever kind of work it did —
|
||||
including trace-less failures, curriculum-rejected work, and work that never enters a
|
||||
batch, so it is crash-durable. Each record carries its provenance: `env` (`id` plus the
|
||||
orchestrator's `name`), full `task`, `group` (`id`), and `run`.
|
||||
|
||||
A trace has several steps, so each is stamped as its own event rather than implied by
|
||||
where the record sits. The file monitor stamps `info.kind` and `info.dispatch`/
|
||||
@@ -200,10 +205,10 @@ its recomputed per-token logprobs and entropies. Readers fold the updates onto t
|
||||
stream records, newest winning.
|
||||
|
||||
```bash
|
||||
wc -l {run_dir}/monitors/file/traces/stream.jsonl
|
||||
jq '.traces[].rewards' {run_dir}/monitors/file/traces/stream.jsonl
|
||||
jq 'select(.ok | not) | {id, env: .env.id, errors}' {run_dir}/monitors/file/traces/stream.jsonl
|
||||
jq '{trace_id, info}' {run_dir}/monitors/file/traces/annotations/orch.jsonl
|
||||
wc -l {run_dir}/monitors/file/traces/stream.index.jsonl
|
||||
zstd -dcf {run_dir}/monitors/file/traces/stream/* | jq '.traces[].rewards'
|
||||
zstd -dcf {run_dir}/monitors/file/traces/stream/* | jq 'select(.ok | not) | {id, env: .env.id, errors}'
|
||||
jq '{trace_id, info}' {run_dir}/monitors/file/traces/annotations/orch.index.jsonl
|
||||
```
|
||||
|
||||
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/batches/step_{n}/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank).
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -19,12 +19,14 @@ import sys
|
||||
import threading
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
from itertools import groupby
|
||||
from pathlib import Path
|
||||
|
||||
import orjson
|
||||
|
||||
from prime_rl.entrypoints.dashboard import DAEMON_FILE, DIRS_FILE, STATE_DIR, registry_lock
|
||||
from prime_rl.monitors.file.traces import get_annotations_dir, get_index_path, get_trace_stream
|
||||
from prime_rl.monitors.file.traces.chunks import open_chunk
|
||||
from prime_rl.monitors.file.traces.index import summarize_episode
|
||||
from prime_rl.monitors.file.traces.update import branch_node_paths, fold_trace_updates
|
||||
from prime_rl.utils.config import default_output_dir
|
||||
@@ -518,15 +520,32 @@ def read_metrics(run: str, offset: int = 0) -> dict:
|
||||
# ------------------------------------------------------------------------ rollouts
|
||||
|
||||
|
||||
def _file_size(path: Path) -> int:
|
||||
try:
|
||||
return path.stat().st_size
|
||||
except OSError:
|
||||
return -1
|
||||
|
||||
|
||||
def traces_file(run_dir: Path) -> Path | None:
|
||||
"""The run's episode stream. prime-rl dumps it through the file monitor; a
|
||||
verifiers ``uv run eval`` run writes its own at the run root."""
|
||||
for path in (get_trace_stream(run_dir), run_dir / "traces.jsonl"):
|
||||
if path.is_file() and path.stat().st_size > 0:
|
||||
return path
|
||||
"""The run's episode stream: the chunk directory the file monitor writes, browsed
|
||||
through its index, or the single ``traces.jsonl`` a verifiers ``uv run eval`` run
|
||||
writes at the run root."""
|
||||
stream = get_trace_stream(run_dir)
|
||||
if _file_size(get_index_path(stream)) > 0:
|
||||
return stream
|
||||
bare = run_dir / "traces.jsonl"
|
||||
if bare.is_file() and bare.stat().st_size > 0:
|
||||
return bare
|
||||
return None
|
||||
|
||||
|
||||
def stream_version(path: Path) -> int:
|
||||
"""What a stream's readers key their caches on. Both shapes are append-only, so
|
||||
a size is a version: the index for a chunked stream, the file itself for a bare one."""
|
||||
return _file_size(get_index_path(path)) if path.is_dir() else _file_size(path)
|
||||
|
||||
|
||||
def require_stream(run_dir: Path) -> Path:
|
||||
path = traces_file(run_dir)
|
||||
if path is None:
|
||||
@@ -590,6 +609,11 @@ def line_offsets(path: Path) -> list[int]:
|
||||
|
||||
|
||||
def episode_summaries(path: Path) -> list[dict]:
|
||||
"""Every episode's full summary, nested reward/metric/timing maps included. Parsed
|
||||
from the records themselves, resuming from the last one summarised, and persisted
|
||||
so a revisit skips the parse."""
|
||||
if path.is_dir():
|
||||
return chunked_summaries(path)
|
||||
offsets = line_offsets(path)
|
||||
with _lock:
|
||||
cached_count, summaries = _lru_get(_summaries_cache, path) or (0, [])
|
||||
@@ -619,6 +643,39 @@ def episode_summaries(path: Path) -> list[dict]:
|
||||
return summaries
|
||||
|
||||
|
||||
def chunked_summaries(stream: Path) -> list[dict]:
|
||||
"""The summaries of a chunked stream: its index says where each record sits, so the
|
||||
walk opens each chunk once and seeks record to record."""
|
||||
index = get_index_path(stream)
|
||||
rows = index_rows(index) or []
|
||||
with _lock:
|
||||
cached_count, summaries = _lru_get(_summaries_cache, stream) or (0, [])
|
||||
if cached_count > len(rows):
|
||||
cached_count, summaries = 0, []
|
||||
if cached_count == 0:
|
||||
loaded = load_sidecar(index)
|
||||
if loaded is not None:
|
||||
summaries = loaded[: len(rows)]
|
||||
cached_count = len(summaries)
|
||||
if cached_count == len(rows):
|
||||
with _lock:
|
||||
_lru_put(_summaries_cache, stream, (cached_count, summaries))
|
||||
return summaries
|
||||
summaries = list(summaries[:cached_count])
|
||||
for chunk, chunk_rows in groupby(rows[cached_count:], key=lambda row: row.get("chunk", 0)):
|
||||
with open_chunk(stream, chunk) as f:
|
||||
for row in chunk_rows:
|
||||
f.seek(row.get("offset", 0))
|
||||
try:
|
||||
summaries.append(summarize_episode(row["line"], orjson.loads(f.readline())))
|
||||
except orjson.JSONDecodeError:
|
||||
summaries.append({"line": row["line"], "id": None, "error": "unparseable"})
|
||||
with _lock:
|
||||
_lru_put(_summaries_cache, stream, (len(rows), summaries))
|
||||
write_sidecar(index, summaries)
|
||||
return summaries
|
||||
|
||||
|
||||
# ------------------------------------------------------- summary sidecars
|
||||
# Parsing a step's traces file for the table can mean reading gigabytes; the
|
||||
# result is persisted outside the run dir (the dashboard never writes there),
|
||||
@@ -717,54 +774,17 @@ def timeline_reward(trace: dict) -> float | None:
|
||||
)
|
||||
|
||||
|
||||
def _file_size(path: Path) -> int:
|
||||
try:
|
||||
return path.stat().st_size
|
||||
except OSError:
|
||||
return -1
|
||||
|
||||
|
||||
def annotations_files(run_dir: Path) -> list[Path]:
|
||||
"""The annotation records themselves, one file per producer — their indexes are
|
||||
named for them, so a name that is already an index is one of those."""
|
||||
def annotation_streams(run_dir: Path) -> list[Path]:
|
||||
"""The annotation streams, one chunk directory per producer, each indexed beside it."""
|
||||
directory = get_annotations_dir(run_dir)
|
||||
if not directory.is_dir():
|
||||
return []
|
||||
return sorted(path for path in directory.glob("*.jsonl") if not path.name.endswith(".index.jsonl"))
|
||||
return sorted(path for path in directory.iterdir() if path.is_dir())
|
||||
|
||||
|
||||
def annotation_source(data: Path) -> Path:
|
||||
"""The file a producer's rows are read from: its index when it wrote one, else the
|
||||
records themselves. Whatever depends on those rows versions itself by this file's
|
||||
size - the record file can grow before its index row is flushed, and a version
|
||||
taken from it would miss the index completing."""
|
||||
index = get_index_path(data)
|
||||
return index if index.is_file() else data
|
||||
|
||||
|
||||
def annotation_rows(data: Path) -> list[dict]:
|
||||
"""A producer's updates as index rows - ``{trace_id, info, offset}`` - read from its
|
||||
index when it wrote one, and derived from the records themselves when it did not."""
|
||||
rows = index_rows(get_index_path(data))
|
||||
if rows is not None:
|
||||
return rows
|
||||
size = data.stat().st_size
|
||||
with _lock:
|
||||
cached = _lru_get(_index_cache, data)
|
||||
if cached and cached[0] == size:
|
||||
return cached[1]
|
||||
rows, offset = [], 0
|
||||
with data.open("rb") as f:
|
||||
for raw in f:
|
||||
try:
|
||||
update = orjson.loads(raw)
|
||||
except orjson.JSONDecodeError:
|
||||
break
|
||||
rows.append({"trace_id": update.get("trace_id"), "info": update.get("info"), "offset": offset})
|
||||
offset += len(raw)
|
||||
with _lock:
|
||||
_lru_put(_index_cache, data, (size, rows))
|
||||
return rows
|
||||
def annotation_rows(stream: Path) -> list[dict]:
|
||||
"""A producer's updates as its index rows - ``{trace_id, info, chunk, offset}``."""
|
||||
return index_rows(get_index_path(stream)) or []
|
||||
|
||||
|
||||
def annotation_index(run_dir: Path) -> dict[str, dict]:
|
||||
@@ -773,8 +793,8 @@ def annotation_index(run_dir: Path) -> dict[str, dict]:
|
||||
Reads the producers' indexes when they exist, so answering "which cohort, what
|
||||
credit" never touches the token streams — they can outweigh the traces themselves.
|
||||
A producer that wrote no index is read in full."""
|
||||
files = annotations_files(run_dir)
|
||||
key = tuple((data.name, _file_size(annotation_source(data))) for data in files)
|
||||
files = annotation_streams(run_dir)
|
||||
key = tuple((data.name, stream_version(data)) for data in files)
|
||||
cache_key = get_annotations_dir(run_dir)
|
||||
with _lock:
|
||||
cached = _lru_get(_annotations_cache, cache_key)
|
||||
@@ -785,17 +805,17 @@ def annotation_index(run_dir: Path) -> dict[str, dict]:
|
||||
# the previous one must not see it change size under it.
|
||||
consumed, index = ({}, {}) if cached is None else (dict(cached[2]), dict(cached[1]))
|
||||
|
||||
def note(trace_id: str | None, info: dict, data: Path, offset: int) -> None:
|
||||
def note(trace_id: str | None, info: dict, data: Path, chunk: int, offset: int) -> None:
|
||||
if not trace_id:
|
||||
return
|
||||
entry = index.setdefault(trace_id, {"info": {}, "at": []})
|
||||
entry["info"].update(info)
|
||||
entry["at"].append((data, offset))
|
||||
entry["at"].append((data, chunk, offset))
|
||||
|
||||
for data in files:
|
||||
rows = annotation_rows(data)
|
||||
for row in rows[consumed.get(data, 0) :]:
|
||||
note(row.get("trace_id"), row.get("info") or {}, data, row.get("offset", 0))
|
||||
note(row.get("trace_id"), row.get("info") or {}, data, row.get("chunk", 0), row.get("offset", 0))
|
||||
consumed[data] = len(rows)
|
||||
with _lock:
|
||||
_lru_put(_annotations_cache, cache_key, (key, index, consumed))
|
||||
@@ -806,9 +826,9 @@ def trace_updates(run_dir: Path, trace_id: str) -> list[dict]:
|
||||
"""Every update recorded against one trace, read by seeking to each record."""
|
||||
entry = annotation_index(run_dir).get(trace_id)
|
||||
updates = []
|
||||
for path, offset in (entry or {}).get("at", []):
|
||||
for stream, chunk, offset in (entry or {}).get("at", []):
|
||||
try:
|
||||
with path.open("rb") as f:
|
||||
with open_chunk(stream, chunk) as f:
|
||||
f.seek(offset)
|
||||
updates.append(orjson.loads(f.readline()))
|
||||
except (OSError, orjson.JSONDecodeError):
|
||||
@@ -864,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",
|
||||
@@ -881,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"))
|
||||
@@ -971,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"),
|
||||
@@ -979,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)
|
||||
@@ -1065,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]
|
||||
@@ -1132,12 +1414,8 @@ def episode_rows(run_dir: Path) -> list[dict]:
|
||||
path = traces_file(run_dir)
|
||||
if path is None:
|
||||
return []
|
||||
files = annotations_files(run_dir)
|
||||
key = (
|
||||
_file_size(stream_index_file(run_dir)),
|
||||
path.stat().st_size,
|
||||
*(_file_size(annotation_source(f)) for f in files),
|
||||
)
|
||||
files = annotation_streams(run_dir)
|
||||
key = (stream_version(path), *(stream_version(f) for f in files))
|
||||
with _lock:
|
||||
cached = _lru_get(_rows_cache, run_dir)
|
||||
if cached and cached[0] == key:
|
||||
@@ -1322,7 +1600,7 @@ def list_rollouts(run: str) -> dict:
|
||||
def stream_etag(run_dir: Path, path: Path) -> str:
|
||||
"""What a listing depends on: the stream, and the annotations that give its rows
|
||||
their cohort and credit. Both are append-only, so their sizes are the version."""
|
||||
return f"{path.stat().st_size}-{sum(_file_size(annotation_source(f)) for f in annotations_files(run_dir))}"
|
||||
return f"{stream_version(path)}-{sum(stream_version(f) for f in annotation_streams(run_dir))}"
|
||||
|
||||
|
||||
def effective_steps(run_dir: Path) -> set[tuple[str, int]]:
|
||||
@@ -1439,15 +1717,19 @@ def episode_series(run: str, kind: str | None = None, etag: str | None = None, a
|
||||
return {"etag": current_etag, "count": len(summaries), "after": max(0, after), "series": series}
|
||||
|
||||
|
||||
def read_episode_at(path: Path, line: int, offset: int | None = None) -> dict:
|
||||
"""One episode. A written index carries the byte offset, so reading it never
|
||||
touches the rest of the stream."""
|
||||
if offset is None:
|
||||
def read_episode_at(path: Path, line: int, at: tuple[int, int] | None = None) -> dict:
|
||||
"""One episode. A written index says which chunk and byte offset it sits at, so
|
||||
reading it never touches the rest of the stream; a bare file is scanned for its
|
||||
line offsets instead."""
|
||||
if at is None:
|
||||
offsets = line_offsets(path)
|
||||
if not 1 <= line <= len(offsets):
|
||||
raise HTTPException(404, "episode line out of range")
|
||||
offset = offsets[line - 1]
|
||||
with path.open("rb") as f:
|
||||
f, offset = path.open("rb"), offsets[line - 1]
|
||||
else:
|
||||
chunk, offset = at
|
||||
f = open_chunk(path, chunk)
|
||||
with f:
|
||||
f.seek(offset)
|
||||
try:
|
||||
return orjson.loads(f.readline())
|
||||
@@ -1456,11 +1738,16 @@ def read_episode_at(path: Path, line: int, offset: int | None = None) -> dict:
|
||||
raise HTTPException(422, f"episode {line} is unparseable") from error
|
||||
|
||||
|
||||
def episode_offset(run_dir: Path, line: int) -> int | None:
|
||||
def episode_at(run_dir: Path, line: int) -> tuple[int, int] | None:
|
||||
"""Where the written index puts an episode: ``(chunk, offset)``. None only when the
|
||||
stream has no index; an index that exists is authoritative for what lines there are."""
|
||||
rows = written_index(run_dir)
|
||||
if rows is None or not 1 <= line <= len(rows):
|
||||
if rows is None:
|
||||
return None
|
||||
return rows[line - 1].get("offset")
|
||||
if not 1 <= line <= len(rows):
|
||||
raise HTTPException(404, "episode line out of range")
|
||||
row = rows[line - 1]
|
||||
return row.get("chunk", 0), row.get("offset", 0)
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/episodes/{line}")
|
||||
@@ -1473,7 +1760,7 @@ def get_episode(
|
||||
"""One episode, by its line in the stream, with every annotation folded on."""
|
||||
run_dir = get_run_dir(run)
|
||||
path = require_stream(run_dir)
|
||||
rec = read_episode_at(path, line, episode_offset(run_dir, line))
|
||||
rec = read_episode_at(path, line, episode_at(run_dir, line))
|
||||
# only the opened episode's streams are read, by seeking to each of its records
|
||||
for trace in rec.get("traces") or []:
|
||||
updates = trace_updates(run_dir, trace.get("id") or "")
|
||||
@@ -1687,7 +1974,7 @@ async def view_events() -> "StreamingResponse":
|
||||
@app.get("/api/runs/{run}/episodes/{line}/timeline")
|
||||
def get_episode_timeline(run: str, line: int) -> dict:
|
||||
run_dir = get_run_dir(run)
|
||||
return project_episode_timeline(read_episode_at(require_stream(run_dir), line, episode_offset(run_dir, line)))
|
||||
return project_episode_timeline(read_episode_at(require_stream(run_dir), line, episode_at(run_dir, line)))
|
||||
|
||||
|
||||
# -------------------------------------------------------------------------- static
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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>
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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); "
|
||||
@@ -537,6 +537,7 @@ class Evals:
|
||||
get_logger().warning(
|
||||
f"Partially evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Error {full.has_error.mean():.1%} | "
|
||||
f"Completed {len(episodes)}/{total_attempts} | Cancelled {batch.cancelled}/{total_attempts}"
|
||||
)
|
||||
return
|
||||
@@ -578,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)
|
||||
|
||||
|
||||
|
||||
@@ -17,6 +17,26 @@ def apply_shared_vllm_patches():
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
monkey_patch_kv_xfer_finished_tolerate_freed()
|
||||
monkey_patch_online_fp8_parameter_cast()
|
||||
monkey_patch_deepseek_v4_allowed_layer_types()
|
||||
monkey_patch_deepseek_v4_per_layer_rope()
|
||||
monkey_patch_deepseek_v4_bf16_o_proj()
|
||||
|
||||
|
||||
def monkey_patch_deepseek_v4_allowed_layer_types():
|
||||
"""Let vLLM's `DeepseekV4Config` construct under a transformers pin below 5.15.
|
||||
|
||||
`vllm/transformers_utils/configs/deepseek_v4.py` leaves `layer_types` to
|
||||
`PretrainedConfig`, whose validator checks it against a vocabulary that only gained V4's
|
||||
compressed attention names in transformers 5.15, so `AutoConfig.from_pretrained` on any
|
||||
DeepSeek V4 checkpoint raises. vLLM declares `transformers>=5.5.3`, so this is a gap in
|
||||
upstream's own version floor rather than something prime-rl introduced.
|
||||
|
||||
`EngineArgs.__post_init__` loads general plugins before `create_model_config`, which is why
|
||||
patching here is early enough. The trainer applies the same shim on its own import path.
|
||||
"""
|
||||
from prime_rl.utils.transformers_compat import allow_deepseek_v4_layer_types
|
||||
|
||||
allow_deepseek_v4_layer_types()
|
||||
|
||||
|
||||
def monkey_patch_online_fp8_parameter_cast():
|
||||
@@ -104,6 +124,110 @@ def monkey_patch_kv_xfer_finished_tolerate_freed():
|
||||
logger.warning("Patched Scheduler._update_from_kv_xfer_finished to tolerate freed (aborted) KV-transfer reqs.")
|
||||
|
||||
|
||||
def monkey_patch_deepseek_v4_bf16_o_proj():
|
||||
"""Run DeepSeek V4's output projection in bf16 when the weights are not FP8.
|
||||
|
||||
vLLM's DeepSeek V4 output projection is FP8-only. All three CUDA attention
|
||||
classes (``DeepseekV4FlashMLAAttention``,
|
||||
``DeepseekV4FlashInferMLAAttention``, ``DeepseekV4FlashInferSM120Attention``)
|
||||
implement ``_o_proj`` by calling ``deep_gemm_fp8_o_proj``
|
||||
(``vllm/models/deepseek_v4/nvidia/ops/o_proj.py``), which dereferences
|
||||
``wo_a.weight_scale``, falling back to ``wo_a.weight_scale_inv``, and hands
|
||||
the result to DeepGEMM's ``fp8_einsum``. There is no branch on quant config
|
||||
or weight dtype, and ``_o_proj`` is an ``@abstractmethod`` dispatched purely
|
||||
by platform subclass, so no attention backend routes around it. A bf16
|
||||
checkpoint has neither attribute and therefore fails with
|
||||
``AttributeError: 'ColumnParallelLinear' object has no attribute
|
||||
'weight_scale_inv'``.
|
||||
|
||||
Quantizing is not an answer, because nothing quantizes by default:
|
||||
``[inference.vllm] quantization`` is unset, which leaves vLLM to infer the
|
||||
scheme from the checkpoint. bf16 DeepSeek V4 checkpoints are a first-class
|
||||
artifact here, written by ``tools/convert_fp8_to_bf16.py``,
|
||||
``tools/convert_dcp_to_bf16.py``, and trainer exports, and they carry no
|
||||
scales for the op to find. Passing ``--quantization fp8_per_block`` does
|
||||
produce a correct ``weight_scale_inv`` and is a genuine alternative on
|
||||
hardware whose DeepGEMM build has block-scaled FP8 kernels, but it changes
|
||||
the served numerics, so it is a deployment decision rather than a fix for
|
||||
serving the bf16 weights as given.
|
||||
|
||||
Only the unquantized case is redirected: an FP8 weight keeps using vLLM's own
|
||||
kernel, so a real FP8-serialized checkpoint behaves exactly as before. The
|
||||
condition is the weight dtype rather than the presence of
|
||||
``weight_scale_inv``, so a checkpoint that *is* quantized but whose scales
|
||||
ended up in the wrong layout still fails loudly instead of being silently
|
||||
rerouted.
|
||||
|
||||
The replacement mirrors the Triton kernel's arithmetic
|
||||
(``vllm/models/deepseek_v4/common/ops/fused_inv_rope_fp8_quant.py:95-105``)
|
||||
without the quantization step. The trailing ``rope_dim`` channels of each head
|
||||
carry an inverse RoPE over interleaved pairs, with ``cos_sin_cache`` holding
|
||||
``rope_dim // 2`` cosines followed by the matching sines:
|
||||
|
||||
y[even] = x[even] * cos + x[odd] * sin
|
||||
y[odd] = x[odd] * cos - x[even] * sin
|
||||
|
||||
The remaining ``nope_dim`` channels pass through. The projection is the same
|
||||
grouped contraction ``fp8_einsum`` performs, with the group axis recovered by
|
||||
reshaping: head ``g * heads_per_group + i`` belongs to group ``g`` at offset
|
||||
``i * head_dim``, matching the kernel's own
|
||||
``g = pid_gh // heads_per_group`` indexing.
|
||||
|
||||
Rotation is computed in fp32 and the contraction runs in bf16, whose CUDA
|
||||
matmuls accumulate in fp32. That is strictly more accurate than the FP8 path
|
||||
it replaces, and it avoids materializing an fp32 copy of the attention output.
|
||||
"""
|
||||
from vllm.models.deepseek_v4.nvidia import flashinfer_sparse, flashmla
|
||||
from vllm.models.deepseek_v4.nvidia.ops import o_proj as o_proj_module
|
||||
|
||||
original_o_proj = o_proj_module.deep_gemm_fp8_o_proj
|
||||
if getattr(original_o_proj, "_prime_rl_has_bf16_fallback", False):
|
||||
return
|
||||
|
||||
def _inverse_rope(o, positions, cos_sin_cache, rope_dim):
|
||||
num_tokens, num_heads, head_dim = o.shape
|
||||
half_rope = rope_dim // 2
|
||||
cos_sin = cos_sin_cache[positions].float()
|
||||
cos = cos_sin[:, :half_rope].view(num_tokens, 1, half_rope)
|
||||
sin = cos_sin[:, half_rope:].view(num_tokens, 1, half_rope)
|
||||
|
||||
rotated = o[:, :, head_dim - rope_dim :].float().reshape(num_tokens, num_heads, half_rope, 2)
|
||||
even, odd = rotated[..., 0], rotated[..., 1]
|
||||
pairs = torch.stack((even * cos + odd * sin, odd * cos - even * sin), dim=-1)
|
||||
|
||||
out = o.clone()
|
||||
out[:, :, head_dim - rope_dim :] = pairs.reshape(num_tokens, num_heads, rope_dim).to(o.dtype)
|
||||
return out
|
||||
|
||||
def _patched_o_proj(o, positions, cos_sin_cache, wo_a, wo_b, *, n_groups, heads_per_group, **kwargs):
|
||||
if wo_a.weight.dtype == torch.float8_e4m3fn:
|
||||
return original_o_proj(
|
||||
o,
|
||||
positions,
|
||||
cos_sin_cache,
|
||||
wo_a,
|
||||
wo_b,
|
||||
n_groups=n_groups,
|
||||
heads_per_group=heads_per_group,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
x = _inverse_rope(o, positions, cos_sin_cache, kwargs["rope_dim"])
|
||||
x = x.reshape(o.shape[0], n_groups, heads_per_group * o.shape[-1])
|
||||
weight = wo_a.weight.view(n_groups, kwargs["o_lora_rank"], -1)
|
||||
z = torch.einsum("tgr,gdr->tgd", x, weight)
|
||||
return wo_b(z.flatten(1))
|
||||
|
||||
_patched_o_proj._prime_rl_has_bf16_fallback = True
|
||||
o_proj_module.deep_gemm_fp8_o_proj = _patched_o_proj
|
||||
|
||||
# Both attention modules did `from ...ops.o_proj import deep_gemm_fp8_o_proj` at
|
||||
# import time, so patching the defining module alone would not reach the names
|
||||
# their `_o_proj` methods actually call.
|
||||
flashmla.deep_gemm_fp8_o_proj = _patched_o_proj
|
||||
flashinfer_sparse.deep_gemm_fp8_o_proj = _patched_o_proj
|
||||
|
||||
|
||||
def monkey_patch_nano_v3_reasoning_parser():
|
||||
from vllm.reasoning.abs_reasoning_parsers import ReasoningParserManager
|
||||
from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser
|
||||
@@ -723,3 +847,124 @@ def monkey_patch_dp_coordinator_startup_timeout():
|
||||
zmq_addr_pipe.close()
|
||||
|
||||
DPCoordinator._wait_for_zmq_addrs = _patched_wait_for_zmq_addrs
|
||||
|
||||
|
||||
_DEEPSEEK_V4_YARN_ROPE_TYPES = frozenset({"yarn", "deepseek_yarn", "deepseek_llama_scaling"})
|
||||
|
||||
|
||||
def _deepseek_v4_rope_parameters(rope_parameters, *, compress_ratio, max_position_embeddings):
|
||||
"""Flat, single-layer rope parameters for `build_deepseek_v4_rope`.
|
||||
|
||||
Handles both on-disk schemas. The real checkpoint ships a flat legacy `rope_scaling`, which
|
||||
vLLM's config shim normalizes in place. HF's own `DeepseekV4Config` nests the parameters
|
||||
under `main`/`compress` rope-type labels instead, and so does this repo's port. vLLM's shim
|
||||
cannot read that: `is_rope_parameters_nested` only recognizes nesting by *attention* layer
|
||||
type, so transformers leaves the sub-dicts alone and injects a top-level
|
||||
`rope_type="default"` beside them. Upstream then builds unscaled RoPE for every layer and
|
||||
hands `get_rope` a cache key containing a dict, which is unhashable. Selecting the branch
|
||||
this layer wants resolves both. Upstream picks the base from `config.rope_theta` /
|
||||
`config.compress_rope_theta` on its own either way.
|
||||
"""
|
||||
rope_parameters = rope_parameters if isinstance(rope_parameters, dict) else {}
|
||||
# `compress_ratio` is already clamped to >= 1 by the caller, so <= 1 is "no compressor",
|
||||
# i.e. the reference's `else` branch. vLLM lumps the MTP layers in here too.
|
||||
is_sliding = compress_ratio <= 1
|
||||
|
||||
if any(isinstance(value, dict) for value in rope_parameters.values()):
|
||||
label = "main" if is_sliding else "compress"
|
||||
branch = rope_parameters.get(label)
|
||||
if not isinstance(branch, dict):
|
||||
raise ValueError(
|
||||
f"DeepSeek V4 rope_parameters is nested by rope type but has no {label!r} "
|
||||
f"sub-dict; found {sorted(rope_parameters)}."
|
||||
)
|
||||
parameters = dict(branch)
|
||||
else:
|
||||
parameters = dict(rope_parameters)
|
||||
|
||||
rope_type = parameters.get("rope_type", parameters.get("type", "default"))
|
||||
if is_sliding or rope_type not in _DEEPSEEK_V4_YARN_ROPE_TYPES:
|
||||
# Plain RoPE, written as YaRN with `factor=1` rather than as `rope_type="default"`.
|
||||
# The table is the same either way, since `_compute_inv_freq`'s interpolated and
|
||||
# extrapolated frequencies coincide at `factor=1` and `yarn_get_mscale` returns 1.0,
|
||||
# but `"default"` would route `get_rope` to a plain `RotaryEmbedding`, whose cache
|
||||
# follows the ambient dtype and so fails the fp32 assertion in
|
||||
# `vllm/models/deepseek_v4/common/ops/fused_inv_rope_fp8_quant.py`.
|
||||
# `original_max_position_embeddings` is widened because the cache is
|
||||
# `original_max * factor` rows and must still span the context.
|
||||
rope_type = "yarn"
|
||||
parameters["factor"] = 1
|
||||
parameters["original_max_position_embeddings"] = max_position_embeddings
|
||||
parameters["rope_type"] = rope_type
|
||||
return parameters
|
||||
|
||||
|
||||
def monkey_patch_deepseek_v4_per_layer_rope():
|
||||
"""Give each DeepSeek V4 layer the RoPE its reference implementation uses.
|
||||
|
||||
DeepSeek ships the reference inside the checkpoint we serve, at
|
||||
https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-0731/tree/main/inference. Its
|
||||
`model.py:481-485` picks the frequencies per layer:
|
||||
|
||||
if self.compress_ratio:
|
||||
original_seq_len, rope_theta = args.original_seq_len, args.compress_rope_theta
|
||||
else:
|
||||
# disable YaRN and use base rope_theta in pure sliding-window attention
|
||||
original_seq_len, rope_theta = 0, args.rope_theta
|
||||
|
||||
and `precompute_freqs_cis` (`model.py:206-235`) applies the NTK-by-parts ramp only when
|
||||
`original_seq_len > 0`. So a pure sliding-window layer gets plain RoPE at `rope_theta` and
|
||||
every compressed layer gets YaRN at `compress_rope_theta`. HF's `DeepseekV4Config` splits its
|
||||
`rope_parameters` into `main`/`compress` for the same reason, and so does this repo's trainer.
|
||||
|
||||
`vllm/models/deepseek_v4/common/rope.py`'s `build_deepseek_v4_rope` branches the base on
|
||||
`compress_ratio` but never the scaling, so on the real checkpoint it hands YaRN to layers 0
|
||||
and 1 as well. No config value can correct that: `rope_type` is one global field there.
|
||||
So this patch resolves `rope_parameters` per layer instead, which also gives upstream a
|
||||
schema and a dtype it can handle; see `_deepseek_v4_rope_parameters` above.
|
||||
|
||||
Measured against the reference's own frequencies, at the test's `factor=16`,
|
||||
`original_max_position_embeddings=4096` geometry, this takes the sliding layers from 5.1e-03
|
||||
max absolute error to 6e-08, the float32 residual the compressed layers already have. The
|
||||
rope tests in `tests/unit/train/models/test_deepseek_v4.py` are that comparison, over both
|
||||
on-disk schemas and both scaled and unscaled configs.
|
||||
|
||||
Note that nothing in vLLM's DeepSeek V4 calls the module's `forward`; every consumer reads
|
||||
`cos_sin_cache` and hands it to a fused kernel. The class choice is therefore about the
|
||||
cache's dtype and row count, not about which channels the module would rotate.
|
||||
"""
|
||||
from vllm.models.deepseek_v4.common import rope as dsv4_rope
|
||||
|
||||
original_build = dsv4_rope.build_deepseek_v4_rope
|
||||
|
||||
if getattr(original_build, "_prime_rl_matches_deepseek_reference", False):
|
||||
return
|
||||
|
||||
def _patched_build(config, *, head_dim, rope_head_dim, max_position_embeddings, compress_ratio):
|
||||
# Swapping a copy in also spares `config.rope_parameters` upstream's in-place mutation,
|
||||
# which otherwise leaves the last-built layer's `rope_theta` on the shared config.
|
||||
original_parameters = config.rope_parameters
|
||||
config.rope_parameters = _deepseek_v4_rope_parameters(
|
||||
original_parameters,
|
||||
compress_ratio=compress_ratio,
|
||||
max_position_embeddings=max_position_embeddings,
|
||||
)
|
||||
try:
|
||||
return original_build(
|
||||
config,
|
||||
head_dim=head_dim,
|
||||
rope_head_dim=rope_head_dim,
|
||||
max_position_embeddings=max_position_embeddings,
|
||||
compress_ratio=compress_ratio,
|
||||
)
|
||||
finally:
|
||||
config.rope_parameters = original_parameters
|
||||
|
||||
_patched_build._prime_rl_matches_deepseek_reference = True
|
||||
dsv4_rope.build_deepseek_v4_rope = _patched_build
|
||||
|
||||
# `attention.py` imports the builder into its own namespace, so the defining module alone
|
||||
# would not reach the already-bound reference.
|
||||
from vllm.models.deepseek_v4 import attention as dsv4_attention
|
||||
|
||||
dsv4_attention.build_deepseek_v4_rope = _patched_build
|
||||
|
||||
@@ -4,13 +4,14 @@ import asyncio
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, TextIO
|
||||
from typing import TYPE_CHECKING, Any, BinaryIO, TextIO
|
||||
|
||||
import orjson
|
||||
|
||||
from prime_rl.configs.monitors import FileMonitorConfig
|
||||
from prime_rl.monitors.base import Kind, Monitor, Subset
|
||||
from prime_rl.monitors.file.traces import get_annotations_dir, get_index_path, get_trace_stream
|
||||
from prime_rl.monitors.file.traces.chunks import ChunkedJsonl
|
||||
from prime_rl.monitors.file.traces.index import index_row
|
||||
from prime_rl.monitors.file.traces.update import update_index_row
|
||||
from prime_rl.utils.pathing import get_file_monitor_dir
|
||||
@@ -38,6 +39,7 @@ class FileMonitor(Monitor):
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
# Line-buffered append so a concurrently-running dashboard can tail the file.
|
||||
self.file = open(self.path, "a", buffering=1) # noqa: SIM115
|
||||
self._streams: dict[Path, tuple[ChunkedJsonl, BinaryIO]] = {}
|
||||
self.logger.info(f"Logging metrics and episodes to the local filesystem ({output_dir})")
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
|
||||
@@ -54,6 +56,14 @@ class FileMonitor(Monitor):
|
||||
row["producer"] = self.producer
|
||||
self.file.write(json.dumps(row) + "\n")
|
||||
|
||||
def _stream(self, directory: Path) -> tuple[ChunkedJsonl, BinaryIO]:
|
||||
"""A stream and its index, opened on first use and kept open. Writers flush the
|
||||
stream before the index: a row a reader sees points at a record it can read."""
|
||||
if directory not in self._streams:
|
||||
stream = ChunkedJsonl(directory, self.config.chunk_bytes, self.config.compress)
|
||||
self._streams[directory] = (stream, open(get_index_path(directory), "ab"))
|
||||
return self._streams[directory]
|
||||
|
||||
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
|
||||
"""Append each episode to the trace stream as it completes — every episode is
|
||||
serialized exactly once, in arrival order, whatever its kind, so an in-progress
|
||||
@@ -64,45 +74,42 @@ class FileMonitor(Monitor):
|
||||
return
|
||||
|
||||
def write() -> None:
|
||||
path = get_trace_stream(self.output_dir)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
stream, index = self._stream(get_trace_stream(self.output_dir))
|
||||
# An index row goes out with every episode: summarising the record here,
|
||||
# while it is already in hand, saves every reader from parsing a stream
|
||||
# that outgrows memory long before the run does.
|
||||
with open(path, "ab") as f, open(get_index_path(path), "ab") as index:
|
||||
offset = f.tell()
|
||||
for episode in episodes:
|
||||
record = episode.to_record()
|
||||
line = orjson.dumps(record, default=str, option=OPTS)
|
||||
f.write(line)
|
||||
self._logged += 1
|
||||
index.write(orjson.dumps(index_row(self._logged, record, offset), default=str, option=OPTS))
|
||||
offset += len(line)
|
||||
for episode in episodes:
|
||||
record = episode.to_record(float_decimals=self.config.float_decimals)
|
||||
chunk, offset = stream.append(orjson.dumps(record, default=str, option=OPTS))
|
||||
self._logged += 1
|
||||
index.write(orjson.dumps(index_row(self._logged, record, chunk, offset), default=str, option=OPTS))
|
||||
stream.flush()
|
||||
index.flush()
|
||||
|
||||
# Record serialization is heavy pure-Python work; keep it off the event loop.
|
||||
# Awaited (not fire-and-forget) so appends to one file never interleave.
|
||||
# Awaited (not fire-and-forget) so appends to one stream never interleave.
|
||||
await asyncio.to_thread(write)
|
||||
|
||||
async def log_annotations(self, updates: list[dict[str, Any]]) -> None:
|
||||
"""Append trace updates to this producer's annotation file — one writer per
|
||||
file, so producers never interleave."""
|
||||
"""Append trace updates to this producer's annotation stream — one writer per
|
||||
stream, so producers never interleave."""
|
||||
if not updates:
|
||||
return
|
||||
|
||||
def write() -> None:
|
||||
path = get_annotations_dir(self.output_dir) / f"{self.producer or 'unknown'}.jsonl"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
stream, index = self._stream(get_annotations_dir(self.output_dir) / (self.producer or "unknown"))
|
||||
# the scalars go to a sibling index so a reader can answer "which cohort,
|
||||
# what credit" without touching the token streams
|
||||
with open(path, "ab") as f, open(get_index_path(path), "ab") as index:
|
||||
offset = f.tell()
|
||||
for update in updates:
|
||||
line = orjson.dumps(update, option=OPTS)
|
||||
f.write(line)
|
||||
index.write(orjson.dumps(update_index_row(update, offset), option=OPTS))
|
||||
offset += len(line)
|
||||
for update in updates:
|
||||
chunk, offset = stream.append(orjson.dumps(update, option=OPTS))
|
||||
index.write(orjson.dumps(update_index_row(update, chunk, offset), option=OPTS))
|
||||
stream.flush()
|
||||
index.flush()
|
||||
|
||||
await asyncio.to_thread(write)
|
||||
|
||||
async def finalize(self) -> None:
|
||||
for stream, index in self._streams.values():
|
||||
stream.close()
|
||||
index.close()
|
||||
self.logger.info(f"Finalized metrics at {self.path}")
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""Where the file monitor puts the traces, and everything written about them.
|
||||
|
||||
The stream and its annotations live under one directory so nothing beside them has to
|
||||
be read as belonging to them, and every index is named for the stream it indexes and
|
||||
sits beside it.
|
||||
be read as belonging to them. Each stream is a directory of chunks (see ``chunks``),
|
||||
and every index is named for the stream it indexes and sits beside it.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
@@ -16,18 +16,18 @@ def get_trace_dir(output_dir: Path) -> Path:
|
||||
|
||||
def get_trace_stream(output_dir: Path) -> Path:
|
||||
"""Every episode, appended as it arrives."""
|
||||
return get_trace_dir(output_dir) / "stream.jsonl"
|
||||
return get_trace_dir(output_dir) / "stream"
|
||||
|
||||
|
||||
def get_annotations_dir(output_dir: Path) -> Path:
|
||||
"""One file per producer of trace updates: orch ship-time facts, trainer streams."""
|
||||
"""One stream per producer of trace updates: orch ship-time facts, trainer streams."""
|
||||
return get_trace_dir(output_dir) / "annotations"
|
||||
|
||||
|
||||
def get_index_path(path: Path) -> Path:
|
||||
def get_index_path(stream: Path) -> Path:
|
||||
"""A stream's index, beside it, so a reader pairs the two without knowing who
|
||||
wrote them."""
|
||||
return path.with_name(path.name.replace(".jsonl", ".index.jsonl"))
|
||||
return stream.with_name(stream.name.removesuffix(".jsonl") + ".index.jsonl")
|
||||
|
||||
|
||||
__all__ = ["get_annotations_dir", "get_index_path", "get_trace_dir", "get_trace_stream"]
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
"""Chunked JSONL — an append-only stream split into numbered files, sealed as it grows.
|
||||
|
||||
stream/00000.jsonl.zst sealed: zstd in seekable frames, so a reader still lands on one line
|
||||
stream/00001.jsonl live: plain text, so it can be tailed
|
||||
|
||||
A line never spans chunks. Once a chunk reaches its size the writer moves on and seals it
|
||||
in the background: the compressed twin is written beside it and the plain file removed
|
||||
only once the twin is complete, so a reader that misses the plain file finds the sealed
|
||||
one. ``zstd -dcf stream/* | jq`` reads a whole stream, sealed and live alike.
|
||||
"""
|
||||
|
||||
import shutil
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import BinaryIO
|
||||
|
||||
import pyzstd
|
||||
|
||||
LEVEL = 3
|
||||
"""zstd level: ~7x on episode records at hundreds of MB/s, so sealing keeps up with a run."""
|
||||
|
||||
FRAME_BYTES = 4 << 20
|
||||
"""Independent frames in a sealed chunk: a seek decompresses one of these, not the chunk."""
|
||||
|
||||
|
||||
def chunk_path(directory: Path, number: int) -> Path:
|
||||
return directory / f"{number:05d}.jsonl"
|
||||
|
||||
|
||||
def chunk_numbers(directory: Path) -> dict[int, bool]:
|
||||
"""Chunk number -> whether its plain file is present (a sealed chunk has none)."""
|
||||
numbers: dict[int, bool] = {}
|
||||
for path in directory.glob("*.jsonl*"):
|
||||
number = int(path.name.split(".", 1)[0])
|
||||
numbers[number] = numbers.get(number, False) or path.suffix == ".jsonl"
|
||||
return numbers
|
||||
|
||||
|
||||
def open_chunk(directory: Path, number: int) -> BinaryIO:
|
||||
"""A chunk for seeking reads, whether still plain or already sealed."""
|
||||
path = chunk_path(directory, number)
|
||||
try:
|
||||
return open(path, "rb")
|
||||
except FileNotFoundError:
|
||||
return pyzstd.SeekableZstdFile(path.with_name(path.name + ".zst"), "rb")
|
||||
|
||||
|
||||
def seal(path: Path) -> None:
|
||||
"""Compress a finished chunk beside itself, then drop the plain file."""
|
||||
target = path.with_name(path.name + ".zst")
|
||||
partial = target.with_name(target.name + ".tmp")
|
||||
with (
|
||||
open(path, "rb") as src,
|
||||
pyzstd.SeekableZstdFile(partial, "wb", level_or_option=LEVEL, max_frame_content_size=FRAME_BYTES) as dst,
|
||||
):
|
||||
shutil.copyfileobj(src, dst, 1 << 20)
|
||||
partial.replace(target)
|
||||
path.unlink()
|
||||
|
||||
|
||||
class ChunkedJsonl:
|
||||
"""Appends lines to the live chunk of a stream and reports where each one landed."""
|
||||
|
||||
def __init__(self, directory: Path, max_bytes: int, compress: bool) -> None:
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
self.directory = directory
|
||||
self.max_bytes = max_bytes
|
||||
self.compress = compress
|
||||
self._sealing: list[threading.Thread] = []
|
||||
numbers = chunk_numbers(directory)
|
||||
last = max(numbers, default=-1)
|
||||
# A relaunch appends to the live chunk it finds and starts a new one after a sealed
|
||||
# last chunk; anything else still plain was left mid-seal by a crash.
|
||||
self.number = last if numbers.get(last) else last + 1
|
||||
for number, plain in numbers.items():
|
||||
if plain and number != self.number and compress:
|
||||
self._seal(number)
|
||||
self.file = open(chunk_path(directory, self.number), "ab")
|
||||
self.size = self.file.tell()
|
||||
|
||||
def append(self, line: bytes) -> tuple[int, int]:
|
||||
"""Write one line; returns ``(chunk, offset)``, the address a reader seeks to."""
|
||||
if self.size and self.size + len(line) > self.max_bytes:
|
||||
self._roll()
|
||||
offset = self.size
|
||||
self.file.write(line)
|
||||
self.size += len(line)
|
||||
return self.number, offset
|
||||
|
||||
def flush(self) -> None:
|
||||
self.file.flush()
|
||||
|
||||
def close(self) -> None:
|
||||
"""Seal the live chunk too, so a finished run keeps nothing plain."""
|
||||
self.file.close()
|
||||
if not self.size:
|
||||
chunk_path(self.directory, self.number).unlink()
|
||||
elif self.compress:
|
||||
self._seal(self.number)
|
||||
for thread in self._sealing:
|
||||
thread.join()
|
||||
|
||||
def _roll(self) -> None:
|
||||
self.file.close()
|
||||
if self.compress:
|
||||
self._seal(self.number)
|
||||
self.number += 1
|
||||
self.file = open(chunk_path(self.directory, self.number), "ab")
|
||||
self.size = 0
|
||||
|
||||
def _seal(self, number: int) -> None:
|
||||
# not a daemon: a process that exits mid-seal waits for it rather than leaving a torn twin
|
||||
thread = threading.Thread(target=seal, args=(chunk_path(self.directory, number),))
|
||||
thread.start()
|
||||
self._sealing.append(thread)
|
||||
@@ -2,9 +2,9 @@
|
||||
the stream to browse it.
|
||||
|
||||
The file monitor writes a row as each episode lands, when the record is already in
|
||||
hand and summarising it is nearly free, and records the byte offset it wrote the
|
||||
episode at so a reader can seek straight to one. A stream another producer wrote has
|
||||
no index, so its reader derives the same rows itself.
|
||||
hand and summarising it is nearly free, and records the chunk and byte offset it wrote
|
||||
the episode at so a reader can seek straight to one. A stream another producer wrote
|
||||
has no index, so its reader derives the same rows itself.
|
||||
"""
|
||||
|
||||
|
||||
@@ -124,10 +124,11 @@ def _episode_duration(info: dict, timing: dict[str, float]) -> float | None:
|
||||
return sum(phases) if phases else None
|
||||
|
||||
|
||||
def index_row(line: int, rec: dict, offset: int) -> dict:
|
||||
def index_row(line: int, rec: dict, chunk: int, offset: int) -> dict:
|
||||
"""The row the file monitor writes. The nested reward/metric/timing maps are left
|
||||
out: only the per-episode series view needs them, and they dominate the size."""
|
||||
row = summarize_episode(line, rec, offset)
|
||||
row["chunk"] = chunk
|
||||
for key in ("rewards", "metrics", "timing"):
|
||||
row.pop(key, None)
|
||||
return row
|
||||
|
||||
@@ -5,8 +5,8 @@ is an update naming the trace: an ``info`` dict merged into the trace's own, plu
|
||||
per-token streams over a branch, full-length across the branch's token prefix (nulls
|
||||
mark unknown positions, so a stream never depends on the producer's loss mask).
|
||||
|
||||
Each producer appends its own file under the trace directory's ``annotations/``, so
|
||||
every file has exactly one writer. Readers fold the updates onto the arrival records
|
||||
Each producer appends its own stream under the trace directory's ``annotations/``, so
|
||||
every stream has exactly one writer. Readers fold the updates onto the arrival records
|
||||
in write order, newest wins.
|
||||
"""
|
||||
|
||||
@@ -18,11 +18,11 @@ STREAM_FIELDS = ("advantages", "trainer_logprobs", "entropies")
|
||||
"""Per-token streams an update may carry, compacted onto node fields of the same name."""
|
||||
|
||||
|
||||
def update_index_row(update: dict[str, Any], offset: int) -> dict[str, Any]:
|
||||
def update_index_row(update: dict[str, Any], chunk: int, offset: int) -> dict[str, Any]:
|
||||
"""An update's scalars plus where its record sits. The per-token streams stay in
|
||||
the annotation file: a reader browsing a run needs the scalars, and only the
|
||||
the annotation stream: a reader browsing a run needs the scalars, and only the
|
||||
episode it opens needs the streams."""
|
||||
return {"trace_id": update.get("trace_id"), "offset": offset, "info": update.get("info") or {}}
|
||||
return {"trace_id": update.get("trace_id"), "chunk": chunk, "offset": offset, "info": update.get("info") or {}}
|
||||
|
||||
|
||||
def make_update(
|
||||
|
||||
+80
-295
@@ -1,331 +1,116 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import atexit
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Coroutine
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import httpx
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import verifiers.v1 as vf
|
||||
from prime_cli.core.config import Config as PrimeConfig
|
||||
from verifiers.v1.utils.platform import build_samples
|
||||
import prime_runs as pr
|
||||
|
||||
from prime_rl.configs.monitors import PrimeMonitorConfig
|
||||
from prime_rl.monitors.base import Kind, Monitor, Subset
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.utils import sanitize
|
||||
|
||||
BASE_URL = "https://api.primeintellect.ai/api/v1/rft"
|
||||
BASE_URL_VAR = "PRIME_API_BASE"
|
||||
API_KEY_VAR = "PRIME_API_KEY"
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
SAMPLE_SCHEMA = pa.schema(
|
||||
[
|
||||
("run_id", pa.string()),
|
||||
("step", pa.int64()),
|
||||
("tag", pa.string()),
|
||||
("problem_id", pa.int64()),
|
||||
("sample_id", pa.int64()),
|
||||
("prompt", pa.string()),
|
||||
("completion", pa.string()),
|
||||
("trajectory", pa.string()),
|
||||
("answer", pa.string()),
|
||||
("env_name", pa.string()),
|
||||
("task", pa.string()),
|
||||
("info", pa.string()),
|
||||
("reward", pa.float64()),
|
||||
("advantage", pa.float64()),
|
||||
("metrics", pa.string()),
|
||||
("timing", pa.string()),
|
||||
("num_input_tokens", pa.int64()),
|
||||
("num_output_tokens", pa.int64()),
|
||||
("created_at", pa.timestamp("us", tz="UTC")),
|
||||
]
|
||||
)
|
||||
BASE_URL_VAR = "PRIME_API_BASE"
|
||||
# How long finish() and the SDK's atexit crash hook let queued uploads drain. The SDK
|
||||
# default (300 s) is sized for eval sample batches; a crashed training process should
|
||||
# not linger that long, and a clean finish rarely has more than the last step queued.
|
||||
FINISH_TIMEOUT = 60.0
|
||||
|
||||
|
||||
def _base_url() -> str | None:
|
||||
"""$PRIME_API_BASE historically points at the RFT API root (``.../api/v1/rft``);
|
||||
the SDK takes the platform base URL. Unset means the SDK resolves it."""
|
||||
base = os.getenv(BASE_URL_VAR)
|
||||
return base.rstrip("/").removesuffix("/rft") if base else None
|
||||
|
||||
|
||||
class PrimeMonitor(Monitor):
|
||||
"""Logs metrics and episodes to the Prime platform.
|
||||
"""Logs metrics and episodes to the Prime platform through ``prime_runs``.
|
||||
|
||||
Uploads are fire-and-forget tasks on the caller's event loop — the prime
|
||||
monitor only runs in the orchestrator, whose call sites are all async. The
|
||||
platform calls and the episode serialization run in worker threads via
|
||||
``asyncio.to_thread``, so they never stall the loop.
|
||||
The run handle owns what ``TrainRun`` used to do by hand: the RFT
|
||||
lifecycle (register or attach, finalize), the per-step metrics POSTs, the
|
||||
every-10th-step Parquet sample uploads (presign -> PUT -> confirm), and
|
||||
the terminal status — a process that exits without finalizing is reported
|
||||
crashed by the SDK's atexit hook, replacing the old ``_mark_failed`` one.
|
||||
|
||||
``init``/``finish`` do network I/O and run in worker threads; the log
|
||||
calls are queue puts onto the SDK's uploader thread, which owns retries
|
||||
and backpressure, so they never stall the loop.
|
||||
"""
|
||||
|
||||
config: PrimeMonitorConfig
|
||||
run: pr.Run
|
||||
|
||||
async def init(self, config: BaseConfig | None = None) -> None:
|
||||
api_key = os.getenv(API_KEY_VAR) or PrimeConfig().api_key
|
||||
if not api_key:
|
||||
raise RuntimeError(f"API key not found - set {API_KEY_VAR} or run `prime login`")
|
||||
self.run = TrainRun(api_key)
|
||||
init_kwargs: dict[str, Any]
|
||||
if run_id := os.getenv("RUN_ID"):
|
||||
# A managed launch pre-created the platform run and injected its id -
|
||||
# attach instead of registering a duplicate. The backend owns the run's
|
||||
# failure marking then; finalize still marks it completed on clean exit.
|
||||
self.run.id = run_id
|
||||
self.logger.info(f"Logging metrics and episodes to platform run {run_id} (attached via $RUN_ID)")
|
||||
return
|
||||
run_fields: dict[str, Any] = {}
|
||||
if config is not None:
|
||||
run_fields = dict(
|
||||
base_model=config.model.name,
|
||||
max_steps=config.max_steps or 0,
|
||||
batch_size=config.batch_size,
|
||||
rollouts_per_example=config.group_size,
|
||||
seq_len=config.seq_len,
|
||||
# failure marking then; a clean finish() still marks it completed.
|
||||
init_kwargs = {"id": run_id}
|
||||
elif config is not None:
|
||||
init_kwargs = dict(
|
||||
name=self.config.name,
|
||||
model=config.model.name,
|
||||
environments=[env.env_id for env in config.train.source],
|
||||
run_config=config.model_dump(exclude_none=True, mode="json"),
|
||||
wandb_project=config.monitors.wandb.project if config.monitors.wandb else None,
|
||||
training=pr.TrainingSpec(
|
||||
max_steps=config.max_steps or 0,
|
||||
batch_size=config.batch_size,
|
||||
rollouts_per_example=config.group_size,
|
||||
seq_len=config.seq_len,
|
||||
wandb_project=config.monitors.wandb.project if config.monitors.wandb else None,
|
||||
),
|
||||
config=config.model_dump(exclude_none=True, mode="json"),
|
||||
)
|
||||
await self.run.create(name=self.config.name, **run_fields)
|
||||
else:
|
||||
# The RFT API requires a base model; "unknown" is what the
|
||||
# pre-SDK register sent for a config-less init.
|
||||
init_kwargs = {"name": self.config.name, "model": "unknown"}
|
||||
|
||||
# A configured monitor must work (see monitors.setup), so the default is
|
||||
# mode="online": a missing key or a team outside the external-runs allowlist
|
||||
# raises here instead of training silently untracked. $PRIME_RUNS_MODE=disabled
|
||||
# stays the explicit opt-out.
|
||||
self.run = await asyncio.to_thread(
|
||||
pr.init,
|
||||
kind="train",
|
||||
mode=os.getenv(pr.MODE_ENV) or "online",
|
||||
base_url=_base_url(),
|
||||
finish_timeout=FINISH_TIMEOUT,
|
||||
**init_kwargs,
|
||||
)
|
||||
if self.run.url:
|
||||
attached = " (attached via $RUN_ID)" if self.run.attached else ""
|
||||
self.logger.info(f"Logging metrics and episodes to platform run {self.run.id} ({self.run.url}){attached}")
|
||||
else:
|
||||
self.logger.info(f"Platform run disabled ({pr.MODE_ENV}=disabled)")
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
|
||||
# The SDK also drops non-finite values, but silently; sanitize first so
|
||||
# the dropped paths are named in the log.
|
||||
metrics, dropped = sanitize(metrics)
|
||||
if dropped:
|
||||
self.logger.warning(f"Dropping {len(dropped)} non-finite metric value(s): {', '.join(dropped[:5])}")
|
||||
# every monitor stamps its own wall time; without it, step=None rows
|
||||
# (e.g. inference metrics) reach the platform with no time anchor
|
||||
metrics["_timestamp"] = time.time()
|
||||
self.run.submit("metrics upload", self.run.log_metrics(metrics))
|
||||
# A queue put that can block briefly under backpressure - off the loop. The SDK
|
||||
# stamps `_timestamp` on every row, so step=None rows keep a time anchor.
|
||||
await asyncio.to_thread(self.run.log_metrics, metrics, step=step)
|
||||
|
||||
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
|
||||
"""Upload one platform sample per episode via the presigned-URL Parquet flow.
|
||||
Only the trained cohort ships to the platform."""
|
||||
# Upload every 10th step, unsampled - the pre-refactor cadence - to not
|
||||
# overwhelm the platform's ingestion. TODO: Lift once we integrate the
|
||||
# prime traces SDK.
|
||||
if kind != "train" or subset != "effective" or not episodes or step % 10 != 0:
|
||||
"""Only the trained cohort ships to the platform. The upload cadence
|
||||
(every 10th step) and the Parquet encoding live in the SDK's training
|
||||
samples sink, which reads each episode's dispatch step off ``run.work``
|
||||
- the ``TrainRunInfo`` the dispatcher stamps at emit time."""
|
||||
if kind != "train" or subset != "effective" or not episodes:
|
||||
return
|
||||
|
||||
async def upload() -> None:
|
||||
# Serialization dumps every episode's full model - heavy pure-Python work
|
||||
# that would stall the event loop (and with it dispatch) if run inline.
|
||||
parquet_bytes = await asyncio.to_thread(episodes_to_parquet_bytes, episodes, self.run.id, step)
|
||||
if parquet_bytes is not None:
|
||||
await self.run.upload_samples(parquet_bytes, step)
|
||||
|
||||
self.run.submit(f"episodes upload at step {step}", upload())
|
||||
# A queue put that can block briefly under backpressure - off the loop.
|
||||
await asyncio.to_thread(self.run.log_episodes, episodes)
|
||||
|
||||
async def finalize(self) -> None:
|
||||
await self.run.finalize()
|
||||
|
||||
|
||||
class TrainRun:
|
||||
"""A training run on the Prime platform's RFT API.
|
||||
|
||||
Owns the HTTP client and the run lifecycle (create, log, finalize) — the
|
||||
natural seam to be subsumed by the train SDK, and it mirrors ``wandb.Run``'s
|
||||
exit behavior: a created run that is never finalized is marked failed at
|
||||
process exit via an atexit hook that ``finalize`` disarms. Fully async,
|
||||
except the atexit hook itself — at interpreter shutdown there is no event
|
||||
loop, so it sends one synchronous request.
|
||||
"""
|
||||
|
||||
def __init__(self, api_key: str):
|
||||
self.id: str | None = None
|
||||
self.logger = get_logger()
|
||||
self._tasks: set[asyncio.Task] = set()
|
||||
self.base_url = (os.getenv(BASE_URL_VAR) or BASE_URL).rstrip("/")
|
||||
self.headers = {
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"x-api-key": api_key,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
self.client = httpx.AsyncClient(
|
||||
base_url=self.base_url,
|
||||
headers=self.headers,
|
||||
timeout=30,
|
||||
transport=httpx.AsyncHTTPTransport(retries=3),
|
||||
)
|
||||
|
||||
def submit(self, what: str, request: Coroutine[Any, Any, None]) -> None:
|
||||
"""Run a request as a fire-and-forget task; a failure only warns. The task set
|
||||
keeps strong references - the loop alone won't."""
|
||||
|
||||
async def guarded() -> None:
|
||||
try:
|
||||
await request
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed {what}: {type(e).__name__}: {e}")
|
||||
|
||||
task = asyncio.get_running_loop().create_task(guarded())
|
||||
self._tasks.add(task)
|
||||
task.add_done_callback(self._tasks.discard)
|
||||
|
||||
async def create(
|
||||
self,
|
||||
name: str | None = None,
|
||||
team_id: str | None = None,
|
||||
base_model: str = "unknown",
|
||||
max_steps: int = 0,
|
||||
batch_size: int | None = None,
|
||||
rollouts_per_example: int | None = None,
|
||||
seq_len: int | None = None,
|
||||
environments: list[str] | None = None,
|
||||
run_config: dict[str, Any] | None = None,
|
||||
wandb_project: str | None = None,
|
||||
) -> str:
|
||||
"""Register the run with the platform and return its id."""
|
||||
prime_config = PrimeConfig()
|
||||
team_id = team_id or prime_config.team_id
|
||||
|
||||
payload: dict[str, Any] = {"base_model": base_model, "max_steps": max_steps}
|
||||
if batch_size is not None:
|
||||
payload["batch_size"] = batch_size
|
||||
if rollouts_per_example is not None:
|
||||
payload["rollouts_per_example"] = rollouts_per_example
|
||||
if seq_len is not None:
|
||||
payload["seq_len"] = seq_len
|
||||
if environments is not None:
|
||||
payload["environments"] = [{"id": env_id} for env_id in environments]
|
||||
if run_config is not None:
|
||||
payload["run_config"] = run_config
|
||||
if wandb_project is not None:
|
||||
payload["wandb_project"] = wandb_project
|
||||
if name:
|
||||
payload["name"] = name
|
||||
if team_id:
|
||||
payload["team_id"] = team_id
|
||||
|
||||
response = await self.client.post("/external-runs", json=payload)
|
||||
if response.status_code != 201:
|
||||
raise RuntimeError(f"Failed to create platform run (HTTP {response.status_code}): {response.text}")
|
||||
|
||||
self.id = response.json()["run"]["id"]
|
||||
self._owner_pid = os.getpid()
|
||||
atexit.register(self._mark_failed)
|
||||
if prime_config.frontend_url:
|
||||
self.logger.info(
|
||||
f"Logging metrics and episodes to platform run {self.id} ({prime_config.frontend_url.rstrip('/')}/dashboard/training/{self.id})"
|
||||
)
|
||||
else:
|
||||
self.logger.info(f"Logging metrics and episodes to platform run {self.id}")
|
||||
return self.id
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any]) -> None:
|
||||
(await self.client.post("/metrics", json={"run_id": self.id, "metrics": metrics})).raise_for_status()
|
||||
|
||||
async def upload_samples(self, parquet_bytes: bytes, step: int) -> None:
|
||||
"""Presigned-URL flow: presign -> R2 PUT -> confirm."""
|
||||
presign = await self.client.post("/samples/presign", json={"run_id": self.id, "step": step})
|
||||
presign.raise_for_status()
|
||||
data = presign.json()["data"]
|
||||
# Bare client - the presigned URL rejects the run client's auth headers.
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
put = await client.put(
|
||||
data["presignedUrl"], content=parquet_bytes, headers={"Content-Type": "application/parquet"}
|
||||
)
|
||||
put.raise_for_status()
|
||||
confirm = await self.client.post(
|
||||
"/samples/confirm", json={"run_id": self.id, "step": step, "s3_key": data["s3Key"]}
|
||||
)
|
||||
confirm.raise_for_status()
|
||||
|
||||
async def finalize(self) -> None:
|
||||
"""Finalize the run as completed."""
|
||||
self.logger.info(f"Finalizing platform run {self.id}")
|
||||
# Drain in-flight uploads so the final step's metrics and episodes land
|
||||
# before the run is marked completed.
|
||||
await asyncio.gather(*self._tasks, return_exceptions=True)
|
||||
try:
|
||||
(await self.client.post("/finalize", json={"run_id": self.id, "summary": {}})).raise_for_status()
|
||||
except httpx.HTTPError as e:
|
||||
self.logger.warning(f"Failed to finalize platform run {self.id}: {e}")
|
||||
await self.set_status(success=True)
|
||||
atexit.unregister(self._mark_failed)
|
||||
|
||||
def _mark_failed(self) -> None:
|
||||
# Forked children inherit the atexit table; only the creating process may
|
||||
# flip the run's status. At interpreter shutdown there is no event loop and
|
||||
# no executor for async DNS, so this path must stay synchronous.
|
||||
if os.getpid() != self._owner_pid:
|
||||
return
|
||||
self.logger.info(f"Marking platform run {self.id} as failed")
|
||||
try:
|
||||
httpx.put(
|
||||
f"{self.base_url}/external-runs/{self.id}/status",
|
||||
headers=self.headers,
|
||||
json={"status": "failed"},
|
||||
timeout=30,
|
||||
).raise_for_status()
|
||||
except httpx.HTTPError as e:
|
||||
self.logger.warning(f"Failed to mark platform run {self.id} as failed: {e}")
|
||||
|
||||
async def set_status(self, success: bool) -> None:
|
||||
"""Mark the run as completed or failed."""
|
||||
status = "completed" if success else "failed"
|
||||
self.logger.info(f"Marking platform run {self.id} as {status}")
|
||||
try:
|
||||
put = await self.client.put(f"/external-runs/{self.id}/status", json={"status": status})
|
||||
put.raise_for_status()
|
||||
except httpx.HTTPError as e:
|
||||
self.logger.warning(f"Failed to mark platform run {self.id} as {status}: {e}")
|
||||
|
||||
|
||||
def episodes_to_parquet_bytes(episodes: list[vf.Episode], run_id: str | None, step: int) -> bytes | None:
|
||||
"""One row per episode. Sample construction is shared with verifiers' eval
|
||||
``--push`` (``build_samples``: complete native episode in ``info.native_wrapper``,
|
||||
flat summary from one trainable trace), so a training episode and an eval sample
|
||||
land on the platform identically; the RFT-only columns (run/step/advantage/
|
||||
problem_id/env_name) are layered on here."""
|
||||
advantages: dict[str, float | None] = {}
|
||||
env_names: dict[str, str] = {}
|
||||
for episode in episodes:
|
||||
summary_trace = next((trace for trace in episode.traces if trace.agent.trainable), episode.traces[0])
|
||||
advantages[episode.id] = summary_trace.info.get("advantage")
|
||||
env_names[episode.id] = episode.env.id
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
rows = []
|
||||
for sample_id, sample in enumerate(build_samples(episodes)):
|
||||
trajectory = sample["trajectory"]
|
||||
if not trajectory: # no branches (e.g. an episode that errored before any message)
|
||||
continue
|
||||
advantage = advantages.get(sample["episode_id"])
|
||||
trajectory = [{**branch, "advantage": advantage} for branch in trajectory]
|
||||
|
||||
try:
|
||||
problem_id = int(sample["example_id"]) if sample["example_id"] is not None else sample_id
|
||||
except (TypeError, ValueError):
|
||||
problem_id = sample_id
|
||||
|
||||
rows.append(
|
||||
{
|
||||
"run_id": run_id,
|
||||
"step": step,
|
||||
"tag": "",
|
||||
"problem_id": problem_id,
|
||||
"sample_id": sample_id,
|
||||
"prompt": "",
|
||||
"completion": json.dumps(sample["completion"]),
|
||||
"trajectory": json.dumps(trajectory),
|
||||
"answer": "",
|
||||
"env_name": env_names.get(sample["episode_id"], ""),
|
||||
"task": json.dumps(sample["task"]),
|
||||
"info": json.dumps(sample["info"]),
|
||||
"reward": sample["reward"],
|
||||
"advantage": advantage,
|
||||
"metrics": json.dumps(sample["metrics"]),
|
||||
"timing": json.dumps(sample["timing"]),
|
||||
"num_input_tokens": trajectory[-1]["num_input_tokens"],
|
||||
"num_output_tokens": trajectory[-1]["num_output_tokens"],
|
||||
"created_at": now,
|
||||
}
|
||||
)
|
||||
|
||||
if not rows:
|
||||
return None
|
||||
|
||||
table = pa.Table.from_pylist(rows, schema=SAMPLE_SCHEMA)
|
||||
buf = io.BytesIO()
|
||||
pq.write_table(table, buf, compression="snappy", use_dictionary=True, write_statistics=True)
|
||||
return buf.getvalue()
|
||||
# Drains queued uploads so the final step's metrics and episodes land,
|
||||
# then finalizes (idempotent on the platform side); an attached run's
|
||||
# failure marking stays with the launcher.
|
||||
await asyncio.to_thread(self.run.finish)
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -64,6 +64,7 @@ DEFAULT_SELECTIVE_SAVE_OPERATIONS = frozenset(
|
||||
"aten::convolution",
|
||||
"aten::linear",
|
||||
"aten::mm",
|
||||
"prime_rl::dsv4_sparse_attn",
|
||||
"prime_rl::fp8_blockwise_mm",
|
||||
"prime_rl::grouped_fp8_gemm",
|
||||
"prime_rl::sparse_mla",
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -38,9 +38,15 @@ from prime_rl.trainer.models import (
|
||||
PreTrainedModelPrimeRL,
|
||||
PrimeLmOutput,
|
||||
cast_float_and_contiguous,
|
||||
get_custom_causal_lm_cls,
|
||||
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
|
||||
@@ -680,6 +686,18 @@ def get_model(
|
||||
"but this architecture resolved to model.impl='hf'."
|
||||
)
|
||||
|
||||
# Past the check above, cp > 1 implies impl_to_use == "custom", so the model class always
|
||||
# resolves. Queried here so a misconfigured job dies at setup rather than at the first forward.
|
||||
if config.cp > 1:
|
||||
cp_model_cls = custom_vlm_cls or get_custom_causal_lm_cls(model_config)
|
||||
support = cp_model_cls.cp_support(model_config)
|
||||
if config.cp_style not in support.styles:
|
||||
supported = f"supported styles: {sorted(support.styles)}" if support.styles else "set cp=1"
|
||||
raise ValueError(
|
||||
f"{model_config.model_type!r} does not support cp_style={config.cp_style!r} "
|
||||
f"({support.reason}); {supported}."
|
||||
)
|
||||
|
||||
if config.vlm is not None and not (is_vlm_arch and custom_vlm_cls):
|
||||
raise ValueError(
|
||||
"VLM training requires a registered custom PrimeRL VLM implementation; "
|
||||
@@ -761,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")
|
||||
@@ -806,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(
|
||||
@@ -831,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.")
|
||||
@@ -841,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:
|
||||
@@ -993,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()
|
||||
@@ -1244,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
|
||||
|
||||
@@ -12,6 +12,7 @@ from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
|
||||
|
||||
from prime_rl.trainer.models.afmoe import AfmoeConfig, AfmoeForCausalLM
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, DeepseekV4ForCausalLM
|
||||
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig, Glm4MoeForCausalLM
|
||||
from prime_rl.trainer.models.glm_moe_dsa import GlmMoeDsaConfig, GlmMoeDsaForCausalLM
|
||||
from prime_rl.trainer.models.gpt_oss import GptOssConfig, GptOssForCausalLM
|
||||
@@ -27,6 +28,7 @@ from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig, Qwen3MoeForCausalL
|
||||
|
||||
# Make custom config discoverable by AutoConfig
|
||||
AutoConfig.register("afmoe", AfmoeConfig, exist_ok=True)
|
||||
AutoConfig.register("deepseek_v4", DeepseekV4Config, exist_ok=True)
|
||||
AutoConfig.register("glm4_moe", Glm4MoeConfig, exist_ok=True)
|
||||
AutoConfig.register("glm_moe_dsa", GlmMoeDsaConfig, exist_ok=True)
|
||||
AutoConfig.register("laguna", LagunaConfig, exist_ok=True)
|
||||
@@ -45,6 +47,7 @@ _CUSTOM_CAUSAL_LM_MODELS: tuple[
|
||||
(LlamaConfig, LlamaForCausalLM),
|
||||
(Qwen3Config, Qwen3ForCausalLM),
|
||||
(AfmoeConfig, AfmoeForCausalLM),
|
||||
(DeepseekV4Config, DeepseekV4ForCausalLM),
|
||||
(Glm4MoeConfig, Glm4MoeForCausalLM),
|
||||
(GlmMoeDsaConfig, GlmMoeDsaForCausalLM),
|
||||
(LagunaConfig, LagunaForCausalLM),
|
||||
|
||||
@@ -1,6 +1,20 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
|
||||
from torch import Tensor
|
||||
from transformers.modeling_utils import PreTrainedModel
|
||||
|
||||
CPStyle = Literal["ring", "ulysses"]
|
||||
ALL_CP_STYLES: frozenset[CPStyle] = frozenset({"ring", "ulysses"})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CPSupport:
|
||||
"""Which context-parallel styles an architecture can train under, and why not the rest."""
|
||||
|
||||
styles: frozenset[CPStyle]
|
||||
reason: str = ""
|
||||
|
||||
|
||||
class PreTrainedModelPrimeRL(PreTrainedModel):
|
||||
"""
|
||||
@@ -11,6 +25,16 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
|
||||
after loading with meta device.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def cp_support(cls, config) -> CPSupport:
|
||||
"""CP styles this architecture supports, given its config.
|
||||
|
||||
Softmax attention runs through the shared ``FlashAttention._compute_attention``, which both
|
||||
``substitute_ring_attn`` and ``substitute_ulysses_attn`` rebind, so the default is both styles.
|
||||
Architectures whose attention sits outside that path declare their own support.
|
||||
"""
|
||||
return CPSupport(ALL_CP_STYLES)
|
||||
|
||||
@classmethod
|
||||
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
|
||||
"""Whether a tensor is stored in FP32 in the source checkpoint.
|
||||
@@ -145,4 +169,4 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
|
||||
raise NotImplementedError(f"init_buffers_post_meta is not implemented for {self.__class__.__name__}")
|
||||
|
||||
|
||||
__all__ = ["PreTrainedModelPrimeRL"]
|
||||
__all__ = ["ALL_CP_STYLES", "CPStyle", "CPSupport", "PreTrainedModelPrimeRL"]
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
|
||||
from prime_rl.trainer.models.deepseek_v4.modeling_deepseek_v4 import DeepseekV4ForCausalLM
|
||||
|
||||
__all__ = [
|
||||
"DeepseekV4Config",
|
||||
"DeepseekV4ForCausalLM",
|
||||
]
|
||||
@@ -0,0 +1,800 @@
|
||||
"""
|
||||
[DeepSeek V4 Attention Layers]
|
||||
|
||||
The attention layers in this architecture generally begin with a few sliding-window attention layers
|
||||
(just the first two layers in V4 Flash) followed by interleaved complex compressed attention
|
||||
variants involving either Compressed Sparse Attention (CSA) or Heavily Compressed Attention (HCA).
|
||||
CSA compresses with a smaller window (~4 toks) and adds additional sparsity on top via a "Lightning
|
||||
Indexer", while HCA uses a more aggressive window (~128 toks) with no additional sparsity. A sketch
|
||||
of the compressed variants is below, tensors flowing downwards:
|
||||
|
||||
hidden_states
|
||||
│
|
||||
┌──────────────┴──────────────┐
|
||||
│ │
|
||||
local KV long-range KV
|
||||
sliding_window ~ 128 compress hidden states
|
||||
│ into compact entries
|
||||
│ │
|
||||
│ ┌──────────────┴──────────────┐
|
||||
│ │ (choose one) │
|
||||
│ │ │
|
||||
│ CSA HCA
|
||||
│ compress_rate ~ 4 compress_rate ~ 128
|
||||
│ index_topk sparsity via │
|
||||
│ Lightning Indexer │
|
||||
│ │ │
|
||||
│ └──────────────┬──────────────┘
|
||||
│ │
|
||||
RoPE RoPE
|
||||
at token positions at each entry's
|
||||
│ first token position
|
||||
│ │
|
||||
└────────── concatenate ──────┘
|
||||
│
|
||||
gather each query's slots, then QKᵀ
|
||||
│
|
||||
softmax + sink
|
||||
│
|
||||
values (= keys) softmax weighting
|
||||
│
|
||||
de-rotate output (undo RoPE on values = keys)
|
||||
│
|
||||
grouped output projection
|
||||
|
||||
[Packing Details]
|
||||
|
||||
We describe our abstractions and nomenclature for DeepSeek V4 packed sequences below, which are
|
||||
useful due to the complexities introduced by the compressed attention variants. Ultimately, all
|
||||
necessary attention data is organized into a `PackedContext` object (directly consumed by attention
|
||||
layers), built from one `seq_lens` and carrying:
|
||||
|
||||
- `position_ids`: each token's position within its own document.
|
||||
- `tok_doc_idx`: which document each token belongs to.
|
||||
- `position_embeddings`: the RoPE tables, one per rope type, evaluated at `position_ids`.
|
||||
- `window_indices`: for each query, the indices of the tokens its local window covers, causal
|
||||
and clipped at document boundaries, with `IGNORE_SLOT` (-1) marking invalid/masked entries.
|
||||
- `compression_layouts`: one `CompressionLayout` per compress rate in the architecture.
|
||||
|
||||
The last of those characterizes the token-compression mechanism of DeepSeek V4. We start with it
|
||||
below.
|
||||
|
||||
We pack several documents end to end in a flat token stream. Each compressed attention variant
|
||||
defines a `compress_rate`: that variant compresses each group of `compress_rate` consecutive tokens
|
||||
into an individual `entry`. For packed sequence and each `compress_rate` in the architecture, we
|
||||
build one `CompressionLayout` object whose responsibility is to handle the document-aware bookkeeping
|
||||
for such packed-document compression.
|
||||
|
||||
Take the following illustrative example of two packed documents and `compress_rate = 4`:
|
||||
|
||||
token 0 1 2 3 4 5 6 7 8 │ 9 10 11 12 13
|
||||
└───────── doc 0 ─────────┘ └─── doc 1 ───┘
|
||||
entry └─── e0 ───┘└─── e1 ───┘ x └─── e2 ───┘ x
|
||||
|
||||
We've indicated which tokens get pooled into which entries (tokens marked `x` belong to no entry) .
|
||||
A complete, generic description of the packed and compressed state requires four pieces of data:
|
||||
|
||||
- Which tokens belong to which entries: `entry_tok_idx`.
|
||||
- Which document each entry belongs to (for causality): `entry_doc_idx`.
|
||||
- Where an entry sits within its own document (useful for RoPE + causality): `entry_local_idx`.
|
||||
- Which document each token belongs to (causality, again): `tok_doc_idx`.
|
||||
|
||||
For the above example:
|
||||
|
||||
token 0 1 2 3 4 5 6 7 8 │ 9 10 11 12 13
|
||||
└───────── doc 0 ─────────┘ └─── doc 1 ───┘
|
||||
entry └─── e0 ───┘└─── e1 ───┘ x └─── e2 ───┘ x
|
||||
|
||||
entry_tok_idx [0 1 2 3][4 5 6 7] [9 10 11 12]
|
||||
entry_doc_idx 0 0 1
|
||||
entry_local_idx 0 1 0
|
||||
tok_doc_idx 0 0 0 0 0 0 0 0 0 1 1 1 1 1
|
||||
|
||||
The first three depend on the compress rate and are stored on the `CompressionLayout` abstraction
|
||||
used below. The fourth does not: `tok_doc_idx` describes the token stream alone, so `PackedContext`
|
||||
holds it once and shares it across rates.
|
||||
|
||||
Compression is only part of the story: every attention layer also reads a local sliding window of
|
||||
the most recent tokens directly, and the compressed entries are how it reaches anything older.
|
||||
That window is enumerated per document by `window_indices`, and every rotation in the block needs
|
||||
`position_ids` together with the RoPE tables evaluated at them, `position_embeddings`. None of
|
||||
those belongs to any single compress rate.
|
||||
|
||||
`PackedContext.build` takes `seq_lens` and derives every one of its fields from it. Nothing else is
|
||||
an input, so a position that disagrees with a document boundary, a window slot that spans one, or a
|
||||
RoPE table evaluated at positions other than the ones the causal thresholds count in, cannot be
|
||||
constructed. It runs once per model forward.
|
||||
|
||||
[The Index Contract]
|
||||
|
||||
All three layer types reach their keys the same way. `SparseAttnInputs` lays out one KV buffer,
|
||||
|
||||
kv_buf[b, n, 0, d]: the packed token stream, then this layer's compressed entries, and
|
||||
nothing else: an absent key needs no position of its own
|
||||
|
||||
and one int32 index tensor addressing that position axis, `sliding_window + picks` slots per
|
||||
query: the local window first, the picks after. `picks` is the indexer's
|
||||
`min(index_topk, entries)` for CSA, `max_entries_per_doc` for HCA, and zero for a sliding layer,
|
||||
which reads its window alone. A slot with nothing to read holds `IGNORE_SLOT` (-1), which the
|
||||
kernel masks on, so a short window and a surplus pick cost only their loads.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import Tensor, nn
|
||||
|
||||
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
|
||||
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 DeepseekV4UnweightedRMSNorm
|
||||
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.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
# Guarded because tilelang ships in the linux-gated `gpu` extra, so some installs lack it.
|
||||
try:
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4.dsv4_sparse_attn import dsv4_sparse_attn, sparse_attn_shape_error
|
||||
except ImportError:
|
||||
dsv4_sparse_attn = None # type: ignore
|
||||
sparse_attn_shape_error = None # type: ignore
|
||||
|
||||
|
||||
def _kernel_blocker(num_heads: int, head_dim: int) -> str | None:
|
||||
"""Why the fused kernel cannot run at this shape, or ``None`` if it can."""
|
||||
if dsv4_sparse_attn is None:
|
||||
return "the tilelang sparse-attention kernel failed to import; install the `gpu` extra"
|
||||
# CSA gives every query head the same single KV head, so the kernel's `kv_group` is 1. The
|
||||
# shape constraints themselves are stated once, next to the kernels they come from.
|
||||
return sparse_attn_shape_error(num_heads, 1, head_dim)
|
||||
|
||||
|
||||
class DeepseekV4GroupedLinear(nn.Linear):
|
||||
"""Block-diagonal grouped linear, the first half of the output projection.
|
||||
|
||||
The stacked attention output is `num_attention_heads * head_dim` wide, so a direct
|
||||
projection to `hidden_size` would dominate the per-token cost. Instead the heads are split
|
||||
into `n_groups` groups, each projected independently to `out_features / n_groups` channels;
|
||||
a single follow-up linear (`o_b_proj`) mixes the concatenation back to `hidden_size`.
|
||||
|
||||
Input is `(..., n_groups, in_features_per_group)`, output `(..., n_groups, out_features / n_groups)`.
|
||||
"""
|
||||
|
||||
def __init__(self, in_features_per_group: int, out_features: int, n_groups: int, bias: bool = False):
|
||||
super().__init__(in_features_per_group, out_features, bias=bias)
|
||||
self.n_groups = n_groups
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
input_shape = x.shape[:-2]
|
||||
hidden_dim = x.shape[-1]
|
||||
w = self.weight.view(self.n_groups, -1, hidden_dim).transpose(1, 2)
|
||||
x = x.reshape(-1, self.n_groups, hidden_dim).transpose(0, 1)
|
||||
y = torch.bmm(x, w).transpose(0, 1)
|
||||
return y.reshape(*input_shape, self.n_groups, -1)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CompressionLayout:
|
||||
"""Per-document compressed-entry layout for one compress rate.
|
||||
|
||||
An entry is one compressed KV vector: a compressor pools a window of `compress_rate`
|
||||
consecutive tokens of the packed input sequence, the entry's source tokens, into a single
|
||||
`head_dim` vector, and the attention block reads the resulting series as extra keys and values
|
||||
along with its local sliding window.
|
||||
"""
|
||||
|
||||
entry_tok_idx: Tensor # (n_entries, compress_rate) int64 - token index in the packed sequence, per entry
|
||||
entry_doc_idx: Tensor # (n_entries,) int64 - which document each entry belongs to
|
||||
entry_local_idx: Tensor # (n_entries,) int64 - entry index within its own document
|
||||
first_entry_of_doc: Tensor # (n_docs,) int64 - sequence-global index of each document's first entry
|
||||
max_entries_per_doc: int # largest entry count any single document contributes
|
||||
|
||||
@classmethod
|
||||
def build(cls, *, cu_seqlens: Tensor, compress_rate: int) -> "CompressionLayout":
|
||||
"""Lay out the compressed entries of a packed sequence, document by document.
|
||||
|
||||
Document `doc` of length `L_doc` gets `L_doc // compress_rate` entries; its entry `e` covers
|
||||
the `compress_rate` source tokens starting at `cu_seqlens[doc] + e * compress_rate`. The
|
||||
trailing `L_doc % compress_rate` tokens get no entry, exactly as the unpacked case drops
|
||||
its trailing partial window; they stay visible through the local sliding window.
|
||||
|
||||
A packed sequence whose every document is shorter than `compress_rate` yields zero entries,
|
||||
which is well-formed: the compressors then contribute nothing beyond their local window.
|
||||
"""
|
||||
device = cu_seqlens.device
|
||||
starts = cu_seqlens[:-1].to(torch.int64)
|
||||
lengths = cu_seqlens[1:].to(torch.int64) - starts
|
||||
counts = lengths // compress_rate
|
||||
|
||||
entry_doc_idx = torch.repeat_interleave(torch.arange(counts.numel(), device=device), counts)
|
||||
first_entry_of_doc = counts.cumsum(0) - counts
|
||||
entry_local_idx = torch.arange(int(counts.sum()), device=device) - first_entry_of_doc[entry_doc_idx]
|
||||
entry_pos = entry_local_idx * compress_rate
|
||||
entry_tok_idx = (
|
||||
starts[entry_doc_idx, None] + entry_pos[:, None] + torch.arange(compress_rate, device=device)[None, :]
|
||||
)
|
||||
|
||||
return cls(
|
||||
entry_tok_idx=entry_tok_idx,
|
||||
entry_doc_idx=entry_doc_idx,
|
||||
entry_local_idx=entry_local_idx,
|
||||
first_entry_of_doc=first_entry_of_doc,
|
||||
max_entries_per_doc=int(counts.max()),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PackedContext:
|
||||
"""Everything an attention layer needs to know about the packed row it is running on.
|
||||
|
||||
The window indices, the positions, the RoPE tables and the layouts all encode the same
|
||||
document boundaries and are only correct together. As separate arguments they can contradict
|
||||
each other: a window enumerated without document boundaries spans documents while a layout
|
||||
does not, a sequence-global `position_ids` feeds `causal_threshold` a count that a
|
||||
per-document `entry_local_idx` cannot be compared against, and a RoPE table evaluated at one
|
||||
set of positions rotates queries the thresholds were not counted at. `build` derives every
|
||||
field from one `seq_lens`, so none of those is reachable. It runs once per model forward.
|
||||
"""
|
||||
|
||||
position_ids: Tensor # (1, seq_len) int64 - token position within its own document
|
||||
tok_doc_idx: Tensor # (seq_len,) int64 - which document each packed token belongs to
|
||||
position_embeddings: dict[str, tuple[Tensor, Tensor]] # (cos, sin) keyed by rope type
|
||||
window_indices: Tensor # (seq_len, sliding_window) int32 - packed token per window slot, IGNORE_SLOT where unused
|
||||
compression_layouts: dict[int, CompressionLayout] # keyed by compress rate
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
# Only reachable by constructing the dataclass directly; `build` cannot violate it.
|
||||
total_tokens = self.tok_doc_idx.shape[0]
|
||||
if self.position_ids.shape[-1] != total_tokens:
|
||||
raise ValueError(
|
||||
f"position_ids covers {self.position_ids.shape[-1]} tokens, but the row has {total_tokens}"
|
||||
)
|
||||
if self.window_indices.shape[0] != total_tokens:
|
||||
raise ValueError(
|
||||
f"window_indices covers {self.window_indices.shape[0]} query rows, but the row has {total_tokens}"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def build(
|
||||
cls,
|
||||
*,
|
||||
rotary_emb: DeepseekV4RotaryEmbedding,
|
||||
seq_lens: Tensor,
|
||||
dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
) -> "PackedContext":
|
||||
"""Derive every field from one `seq_lens`, ensuring mutual consistency.
|
||||
|
||||
`rotary_emb` supplies the RoPE tables and, through the config it was built from, the
|
||||
sliding window and the compress rates in use. Taking the config from it rather than
|
||||
alongside it keeps them from naming different architectures. `dtype` must be the dtype
|
||||
attention runs at, since it types the RoPE tables. The row is as wide as `seq_lens` says,
|
||||
padding included: both packers fold their padding into the last document.
|
||||
"""
|
||||
config = rotary_emb.config
|
||||
# Read the width before `seq_lens` moves: on a CPU `seq_lens` that costs no device sync.
|
||||
total_tokens = int(seq_lens.sum())
|
||||
cu_seqlens, _ = get_cu_seqlens_from_seq_lens(seq_lens.to(device=device))
|
||||
tok_idx = torch.arange(total_tokens, device=device)
|
||||
tok_doc_idx = torch.searchsorted(cu_seqlens[1:].to(tok_idx.dtype), tok_idx, right=True)
|
||||
# Document-local by construction: a token's position is its distance from its own
|
||||
# document's start, which is what `causal_threshold` and the entry rotation count in.
|
||||
position_ids = (tok_idx - cu_seqlens[tok_doc_idx])[None]
|
||||
compress_rates = {
|
||||
config.compress_rates[layer_type]
|
||||
for layer_type in set(config.layer_types)
|
||||
if layer_type in config.compress_rates
|
||||
}
|
||||
|
||||
# A token attends the last `sliding_window` positions (itself included), clipped to its own
|
||||
# document.
|
||||
window_base = torch.maximum(tok_idx - position_ids[0], tok_idx - config.sliding_window + 1)
|
||||
slots = window_base[:, None] + torch.arange(config.sliding_window, device=device)[None, :]
|
||||
window_indices = torch.where(slots <= tok_idx[:, None], slots, IGNORE_SLOT).to(torch.int32)
|
||||
|
||||
return cls(
|
||||
position_ids=position_ids,
|
||||
tok_doc_idx=tok_doc_idx,
|
||||
position_embeddings={
|
||||
rope_type: rotary_emb(position_ids, rope_type, dtype=dtype) for rope_type in rotary_emb.layer_types
|
||||
},
|
||||
compression_layouts={
|
||||
rate: CompressionLayout.build(cu_seqlens=cu_seqlens, compress_rate=rate) for rate in compress_rates
|
||||
},
|
||||
window_indices=window_indices,
|
||||
)
|
||||
|
||||
def check_position_ids(self, position_ids: Tensor) -> None:
|
||||
"""Raise unless `position_ids` agrees with the document boundaries this context came from.
|
||||
|
||||
A document starts exactly where the derived positions are zero, so the check is that the
|
||||
caller's positions vanish there too. A padded micro-batch restarts `position_ids` at 0
|
||||
inside its last document, which this permits: padding sits mid-document, never at a start.
|
||||
A sequence-global `arange` over a packed row never restarts, and a 1-based one never
|
||||
reaches zero at all; both are rejected.
|
||||
"""
|
||||
disagrees = (self.position_ids == 0) & (position_ids != 0)
|
||||
if disagrees.any():
|
||||
token = int(disagrees.any(dim=0).nonzero()[0])
|
||||
raise ValueError(
|
||||
f"position_ids must restart at 0 at every document boundary of seq_lens: token "
|
||||
f"{token} starts a document but carries {position_ids[:, token].tolist()}. A caller "
|
||||
"that passes none of its own gets the 1-based arange the injected LM head "
|
||||
"substitutes (see `prime_rl.trainer.models.layers.lm_head`), which this rejects."
|
||||
)
|
||||
|
||||
def token_entry_causal_mask(self, compress_rate: int, threshold: Tensor) -> Tensor:
|
||||
"""`(1, seq_len, n_entries)` bool: which compressed entries each query token may read.
|
||||
|
||||
Element `[0, t, e]` is true when query token `t` may read entry `e` of the rate's layout.
|
||||
Both of these have to hold:
|
||||
|
||||
- `e` belongs to `t`'s own document, so no query reads another document's history;
|
||||
- `e` closed before `t` arrived, i.e. its index within that document is below
|
||||
`threshold[0, t]`, the count of entries the query's position has completed.
|
||||
|
||||
One `seq_lens` describes one packed row, so the leading axis is 1 and broadcasts over the
|
||||
batch, as `threshold` does.
|
||||
|
||||
`threshold` counts per document, so it is compared against `entry_local_idx` and not
|
||||
against the sequence-global entry number; those two coordinate systems disagree for every
|
||||
document after the first.
|
||||
"""
|
||||
layout = self.compression_layouts[compress_rate]
|
||||
same_document = self.tok_doc_idx[None, :, None] == layout.entry_doc_idx[None, None, :]
|
||||
return same_document & (threshold.unsqueeze(-1) > layout.entry_local_idx[None, None, :])
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SparseAttnInputs:
|
||||
"""The KV buffer one attention layer gathers from, and the gather indices addressing it.
|
||||
|
||||
`build` constructs the two together so they stay mutually consistent and cannot drift apart.
|
||||
|
||||
With `S` tokens in the packed row and `E` compressed entries for this layer's rate, `E` being
|
||||
zero for a layer that reads no entries at all:
|
||||
|
||||
kv_buf[b, n, 0, d]: n in [0, S) -> local token stream
|
||||
n in [S, S + E) -> compressed entry (n - S)
|
||||
|
||||
Every index must be a real key in `[0, n_positions)` or `IGNORE_SLOT` (-1), which marks an absent
|
||||
key, which `build` enforces.
|
||||
"""
|
||||
|
||||
kv_buf: Tensor # (batch, n_positions, 1, head_dim)
|
||||
indices: Tensor # (batch, seq_len, 1, n_slots) int32 into kv_buf's position axis
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
# Shape invariants only. Asserting on index values would read the device, and this runs
|
||||
# once per layer per step.
|
||||
if self.kv_buf.ndim != 4 or self.kv_buf.shape[2] != 1:
|
||||
raise ValueError(f"kv_buf must be (batch, n_positions, 1, head_dim), got {tuple(self.kv_buf.shape)}")
|
||||
if self.indices.ndim != 4 or self.indices.shape[2] != 1:
|
||||
raise ValueError(f"indices must be (batch, seq_len, 1, n_slots), got {tuple(self.indices.shape)}")
|
||||
if self.indices.shape[0] != self.kv_buf.shape[0]:
|
||||
raise ValueError(f"kv_buf covers {self.kv_buf.shape[0]} batch entries and indices {self.indices.shape[0]}")
|
||||
|
||||
@classmethod
|
||||
def build(
|
||||
cls,
|
||||
*,
|
||||
kv: Tensor, # (batch, 1, seq_len, head_dim), the rotated local token stream
|
||||
compressed_kv: Tensor | None = None, # (batch, 1, n_entries, head_dim)
|
||||
top_k_indices: Tensor | None = None, # (batch, seq_len, n_picks) int64, IGNORE_SLOT (-1) marks a surplus pick
|
||||
window_indices: Tensor, # (seq_len, sliding_window) int32, IGNORE_SLOT marks an invalid slot
|
||||
) -> "SparseAttnInputs":
|
||||
"""Lay out one layer's gather slots: the local window first, then any compressed picks.
|
||||
|
||||
A layer with no entries passes neither `compressed_kv` nor `top_k_indices`, receiving only
|
||||
the local sliding window.
|
||||
"""
|
||||
if (compressed_kv is None) != (top_k_indices is None):
|
||||
raise ValueError("compressed_kv and top_k_indices describe the same entries: pass both or neither")
|
||||
batch, _, seq_len, _ = kv.shape
|
||||
|
||||
positions = kv if compressed_kv is None else torch.cat([kv, compressed_kv], dim=2)
|
||||
kv_buf = positions.transpose(1, 2).contiguous() # (b, S + E, 1, d)
|
||||
|
||||
window = window_indices[None, :, None, :].expand(batch, seq_len, 1, -1)
|
||||
if top_k_indices is None:
|
||||
return cls(kv_buf=kv_buf, indices=window.contiguous())
|
||||
|
||||
# A surplus pick is `IGNORE_SLOT` (-1) and stays `IGNORE_SLOT`; a real one names an entry,
|
||||
# which sits past the token stream in `kv_buf`, hence the shift by `seq_len`.
|
||||
# NOTE: the attention kernel recompiles for every unique `indices.shape[-1]` value. If
|
||||
# recompilation becomes a bottleneck, consider padding to fixed length with `IGNORE_SLOT` values.
|
||||
picks = torch.where(top_k_indices >= 0, top_k_indices + seq_len, IGNORE_SLOT)
|
||||
indices = torch.cat([window, picks[:, :, None, :].to(torch.int32)], dim=-1)
|
||||
return cls(kv_buf=kv_buf, indices=indices)
|
||||
|
||||
|
||||
class DeepseekV4Compressor(nn.Module):
|
||||
"""Softmax-gated pooling of the token stream into one entry per `compress_rate` tokens, per the
|
||||
`CompressionLayout` specification. Schematic output:
|
||||
|
||||
`C[e,d] = sum_s softmax_s(gate[e,s,d] + position_bias[s,d]) * kv[e,s,d]`
|
||||
|
||||
`kv` and `gate` are this compressor's own projections of the hidden state, gathered at the
|
||||
source tokens of entry `e`'s pooling window, and `d` runs over `head_dim`. Each entry is
|
||||
RMSNormed and rotated with the `compress` RoPE at its window's first source position, which
|
||||
is what makes it comparable with the attention block's locally rotated KV stream. `forward`
|
||||
returns the entries alongside this layer's entry selection: the per-query entry indices the
|
||||
attention block gathers, with `IGNORE_SLOT` (-1) marking a slot the query has nothing to read into.
|
||||
|
||||
`n_series` sets the slots `s` the gate ranges over. With `1` a token joins only its own
|
||||
window, so windows are disjoint. With `2` the projections emit two `head_dim`-wide series
|
||||
`Ca` and `Cb`, and entry `e` pools `Ca` from entry `e - 1`'s tokens together with `Cb` from
|
||||
its own, so windows overlap at stride `compress_rate`; a document's first entry has no
|
||||
predecessor, so its `Ca` slots are gated with `-inf`.
|
||||
"""
|
||||
|
||||
rope_layer_type = "compress"
|
||||
|
||||
def __init__(self, config: DeepseekV4Config, head_dim: int, compress_rate: int, n_series: int):
|
||||
super().__init__()
|
||||
if n_series not in (1, 2):
|
||||
raise ValueError(f"n_series must be 1 or 2, got {n_series}")
|
||||
self.compress_rate = compress_rate
|
||||
self.head_dim = head_dim
|
||||
self.n_series = n_series
|
||||
self.kv_proj = nn.Linear(config.hidden_size, n_series * head_dim, bias=False)
|
||||
self.gate_proj = nn.Linear(config.hidden_size, n_series * head_dim, bias=False)
|
||||
self.position_bias = nn.Parameter(torch.zeros(compress_rate, n_series * head_dim))
|
||||
self.kv_norm = RMSNorm(RMSNormConfig(hidden_size=head_dim, eps=config.rms_norm_eps))
|
||||
self.rotary_emb = DeepseekV4RotaryEmbedding(config)
|
||||
|
||||
def _overlap_with_previous_window(
|
||||
self, kv: torch.Tensor, gate: torch.Tensor, layout: CompressionLayout
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Widen each entry from `compress_rate` slots to `2 * compress_rate`, the `n_series == 2` case."""
|
||||
n_entries = layout.entry_tok_idx.shape[0]
|
||||
|
||||
# Shift the `Ca` series one entry later so entry `e` sees entry `e - 1`'s. The first
|
||||
# entry of every document has no predecessor, and the entry sitting before it in the
|
||||
# packed sequence belongs to another document, so both halves are cleared: the gate to
|
||||
# `-inf` and the values to zero. Zeroing is not redundant with the gate, because a
|
||||
# zero softmax weight against a non-finite value would still yield NaN.
|
||||
previous = (torch.arange(n_entries, device=kv.device) - 1).clamp(min=0)
|
||||
is_first_entry_in_doc = (layout.entry_local_idx == 0)[None, :, None, None]
|
||||
previous_kv = kv[:, previous, :, : self.head_dim].masked_fill(is_first_entry_in_doc, 0.0)
|
||||
previous_gate = gate[:, previous, :, : self.head_dim].masked_fill(is_first_entry_in_doc, float("-inf"))
|
||||
return (
|
||||
torch.cat([previous_kv, kv[..., self.head_dim :]], dim=2),
|
||||
torch.cat([previous_gate, gate[..., self.head_dim :]], dim=2),
|
||||
)
|
||||
|
||||
def compress(self, hidden_states: torch.Tensor, packed: PackedContext) -> torch.Tensor:
|
||||
"""Compress `(batch, seq_len, hidden_size)` to `(batch, n_entries, head_dim)`.
|
||||
|
||||
The layout at this compressor's own rate decides which source tokens each entry pools.
|
||||
"""
|
||||
batch = hidden_states.shape[0]
|
||||
layout = packed.compression_layouts[self.compress_rate]
|
||||
|
||||
kv = self.kv_proj(hidden_states)[:, layout.entry_tok_idx]
|
||||
gate = self.gate_proj(hidden_states)[:, layout.entry_tok_idx] + self.position_bias
|
||||
if self.n_series == 2:
|
||||
kv, gate = self._overlap_with_previous_window(kv, gate, layout)
|
||||
|
||||
# fp32 softmax: in bf16 the gate logits of a wide window collapse onto each other.
|
||||
weights = gate.softmax(dim=2, dtype=torch.float32).to(kv.dtype)
|
||||
compressed = self.kv_norm((kv * weights).sum(dim=2))
|
||||
|
||||
entry_first_tok_pos = layout.entry_local_idx * self.compress_rate
|
||||
cos, sin = self.rotary_emb(
|
||||
entry_first_tok_pos.unsqueeze(0).expand(batch, -1), self.rope_layer_type, dtype=compressed.dtype
|
||||
)
|
||||
return apply_rotary_pos_emb_interleaved(compressed.unsqueeze(1), cos, sin).squeeze(1)
|
||||
|
||||
def causal_threshold(self, position_ids: torch.Tensor) -> torch.Tensor:
|
||||
"""Number of compressed entries that query `t` may read, shaped like `position_ids`.
|
||||
|
||||
Entry `e` pools source tokens up to index `(e + 1) * compress_rate - 1`, so it only
|
||||
becomes readable once the query has reached that token.
|
||||
"""
|
||||
return (position_ids + 1) // self.compress_rate
|
||||
|
||||
def init_weights(self, init_std: float) -> None:
|
||||
# `init_std` is unused: the projections are initialized by the caller and the
|
||||
# position bias starts at zero, i.e. a uniform gate over the pooling window.
|
||||
nn.init.zeros_(self.position_bias)
|
||||
|
||||
|
||||
class DeepseekV4IndexerScorer(nn.Module):
|
||||
"""Lightning-Indexer score `score[t,e] = sum_h w[t,h] * ReLU(q[t,h,d] * k[e,d])`.
|
||||
|
||||
Query token `t` against compressed entry `e`, over indexer heads `h` and `index_head_dim`
|
||||
channels `d`. The per-head weights `w[t,h]` come off the hidden state directly rather than
|
||||
from a query-key interaction, which keeps the scorer one matmul deep. It runs in fp32: the
|
||||
scores only feed a top-k, so the width costs little and near-ties are not decided by bf16
|
||||
rounding.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config):
|
||||
super().__init__()
|
||||
self.softmax_scale = config.index_head_dim**-0.5
|
||||
self.weights_scaling = config.index_n_heads**-0.5
|
||||
self.weights_proj = nn.Linear(config.hidden_size, config.index_n_heads, bias=False)
|
||||
|
||||
def forward(self, q: torch.Tensor, compressed_kv: torch.Tensor, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
"""Score `q` `(batch, seq, heads, dim)` against `compressed_kv` `(batch, entries, dim)`."""
|
||||
scores = torch.matmul(q.float(), compressed_kv.transpose(-1, -2).float().unsqueeze(1))
|
||||
scores = F.relu(scores) * self.softmax_scale
|
||||
weights = self.weights_proj(hidden_states).float() * self.weights_scaling
|
||||
return (scores * weights.unsqueeze(-1)).sum(dim=2)
|
||||
|
||||
|
||||
class DeepseekV4Indexer(nn.Module):
|
||||
"""Lightning Indexer: picks the `index_topk` compressed entries each query may read.
|
||||
|
||||
It owns a compressor at the narrow `index_head_dim` and scores each query against its
|
||||
entries. The indices it returns address the entries of the compressor that owns it: both
|
||||
share `compress_rate` and the `compress` RoPE base, so entry `e` in one covers the same
|
||||
source tokens as entry `e` in the other, and the scores depend only on the query-key
|
||||
distance.
|
||||
|
||||
Each query gets `min(index_topk, entries)` picks. An early query has fewer entries whose
|
||||
source tokens all lie at or before it, and its surplus picks come back as `IGNORE_SLOT` (-1).
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config):
|
||||
super().__init__()
|
||||
self.head_dim = config.index_head_dim
|
||||
self.num_heads = config.index_n_heads
|
||||
self.index_topk = config.index_topk
|
||||
self.compressor = DeepseekV4Compressor(
|
||||
config, self.head_dim, config.compress_rates["compressed_sparse_attention"], n_series=2
|
||||
)
|
||||
self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.head_dim, bias=False)
|
||||
self.scorer = DeepseekV4IndexerScorer(config)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor, q_residual: torch.Tensor, packed: PackedContext) -> torch.Tensor:
|
||||
batch, seq_len, _ = hidden_states.shape
|
||||
compressed_kv = self.compressor.compress(hidden_states, packed)
|
||||
compressed_len = compressed_kv.shape[1]
|
||||
top_k = min(self.index_topk, compressed_len)
|
||||
|
||||
# The token-position table for this rope type is already on `packed`; the compressor's own
|
||||
# rotary is only ever evaluated at entry positions.
|
||||
cos, sin = packed.position_embeddings[self.compressor.rope_layer_type]
|
||||
q = self.q_b_proj(q_residual).view(batch, seq_len, -1, self.head_dim).transpose(1, 2)
|
||||
q = apply_rotary_pos_emb_interleaved(q, cos, sin).transpose(1, 2)
|
||||
|
||||
scores = self.scorer(q, compressed_kv, hidden_states)
|
||||
if compressed_len == 0:
|
||||
return scores.topk(top_k, dim=-1).indices
|
||||
|
||||
threshold = self.compressor.causal_threshold(packed.position_ids)
|
||||
readable = packed.token_entry_causal_mask(self.compressor.compress_rate, threshold).expand_as(scores)
|
||||
scores = scores.masked_fill(~readable, float("-inf"))
|
||||
top_k_indices = scores.topk(top_k, dim=-1).indices
|
||||
# An early query has fewer than `top_k` readable entries, so top-k still hands back
|
||||
# masked-out ones. Mark those `IGNORE_SLOT` (-1) rather than letting them leak into attention.
|
||||
return torch.where(
|
||||
readable.gather(-1, top_k_indices), top_k_indices, torch.full_like(top_k_indices, IGNORE_SLOT)
|
||||
)
|
||||
|
||||
def init_weights(self, init_std: float) -> None:
|
||||
self.compressor.init_weights(init_std)
|
||||
|
||||
|
||||
class DeepseekV4CSACompressor(DeepseekV4Compressor):
|
||||
"""Compressed Sparse Attention compressor: the sparse long-range half of a CSA layer.
|
||||
|
||||
Two series at a fine compress rate, with overlapping windows. A Lightning Indexer scores
|
||||
the entries and keeps the `index_topk` best per query, and the returned `top_k_indices` is
|
||||
that selection, with `IGNORE_SLOT` (-1) marking a surplus pick. It needs no separate causal term,
|
||||
because the indexer only selects entries whose source tokens all lie at or before the query.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config):
|
||||
super().__init__(config, config.head_dim, config.compress_rates["compressed_sparse_attention"], n_series=2)
|
||||
self.indexer = DeepseekV4Indexer(config)
|
||||
|
||||
def forward(
|
||||
self, hidden_states: torch.Tensor, q_residual: torch.Tensor, packed: PackedContext
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
compressed_kv = self.compress(hidden_states, packed).unsqueeze(1)
|
||||
# The indexer reads the same layout: it compresses the same source windows at a narrower
|
||||
# head dim, so its entry `e` and this compressor's entry `e` are the same window.
|
||||
return compressed_kv, self.indexer(hidden_states, q_residual, packed)
|
||||
|
||||
def init_weights(self, init_std: float) -> None:
|
||||
super().init_weights(init_std)
|
||||
self.indexer.init_weights(init_std)
|
||||
|
||||
|
||||
class DeepseekV4HCACompressor(DeepseekV4Compressor):
|
||||
"""Heavily Compressed Attention compressor: the dense long-range half of an HCA layer.
|
||||
|
||||
One series at a coarse compress rate, with disjoint windows. There is no indexer: a query
|
||||
reads every entry whose source tokens all lie at or before it. A document's entries are
|
||||
numbered consecutively, so that set is the contiguous range starting at the document's first
|
||||
entry, and the picks the layer gathers are arithmetic rather than learned. Every document is
|
||||
afforded `max_entries_per_doc` picks; a query that has completed fewer entries than that pads
|
||||
the rest with `IGNORE_SLOT` (-1), as the indexer's surplus picks do.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config):
|
||||
super().__init__(config, config.head_dim, config.compress_rates["heavily_compressed_attention"], n_series=1)
|
||||
|
||||
def forward(
|
||||
self, hidden_states: torch.Tensor, q_residual: torch.Tensor, packed: PackedContext
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""`q_residual` is part of the compressor contract but unused: HCA has no indexer."""
|
||||
batch = hidden_states.shape[0]
|
||||
compressed_kv = self.compress(hidden_states, packed).unsqueeze(1)
|
||||
|
||||
layout = packed.compression_layouts[self.compress_rate]
|
||||
# `threshold` counts entries within the query's own document, so it selects how far into
|
||||
# that document's range to read, and the document's own base turns that into an entry index.
|
||||
threshold = self.causal_threshold(packed.position_ids).unsqueeze(-1) # (1, seq_len, 1)
|
||||
base = layout.first_entry_of_doc[packed.tok_doc_idx][None, :, None] # (1, seq_len, 1)
|
||||
offsets = torch.arange(layout.max_entries_per_doc, device=hidden_states.device)
|
||||
picks = torch.where(offsets < threshold, base + offsets, IGNORE_SLOT)
|
||||
return compressed_kv, picks.expand(batch, -1, -1)
|
||||
|
||||
|
||||
COMPRESSOR_CLASSES = {
|
||||
"sliding_attention": None,
|
||||
"compressed_sparse_attention": DeepseekV4CSACompressor,
|
||||
"heavily_compressed_attention": DeepseekV4HCACompressor,
|
||||
}
|
||||
|
||||
|
||||
class DeepseekV4Attention(nn.Module):
|
||||
"""DeepSeek-V4 self-attention.
|
||||
|
||||
Four things set it apart from a standard attention block:
|
||||
|
||||
1. Shared-KV multi-query attention. `kv_proj` emits a single `head_dim`-wide vector
|
||||
per token that serves as both key and value for every query head.
|
||||
2. Partial interleaved RoPE on the trailing `qk_rope_head_dim` channels of each head.
|
||||
Because the value carries that rotation too, the conjugate rotation is applied to
|
||||
the attention output, which leaves each key's contribution a function of its
|
||||
relative distance to the query.
|
||||
3. A per-head learnable attention sink.
|
||||
4. A grouped low-rank output projection (`o_a_proj` then `o_b_proj`).
|
||||
|
||||
Every layer type runs that same core over its local sliding window. The two compressed
|
||||
types additionally own a `compressor` whose output is concatenated onto the local KV,
|
||||
which is how a layer sees past the window.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config, layer_idx: int):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.layer_idx = layer_idx
|
||||
self.layer_type = config.layer_types[layer_idx]
|
||||
# Rope types are labelled `main` / `compress`, independently of `layer_types`:
|
||||
# sliding layers take the plain base, the compressed variants share their
|
||||
# compressor's base.
|
||||
self.rope_layer_type = "main" if self.layer_type == "sliding_attention" else "compress"
|
||||
self.num_heads = config.num_attention_heads
|
||||
self.head_dim = config.head_dim
|
||||
self.attention_dropout = config.attention_dropout
|
||||
self.scaling = self.head_dim**-0.5
|
||||
|
||||
self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=False)
|
||||
self.q_a_norm = RMSNorm(RMSNormConfig(hidden_size=config.q_lora_rank, eps=config.rms_norm_eps))
|
||||
self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.head_dim, bias=False)
|
||||
self.q_b_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps)
|
||||
self.kv_proj = nn.Linear(config.hidden_size, self.head_dim, bias=False)
|
||||
self.kv_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
|
||||
self.o_a_proj = DeepseekV4GroupedLinear(
|
||||
self.num_heads * self.head_dim // config.o_groups,
|
||||
config.o_groups * config.o_lora_rank,
|
||||
config.o_groups,
|
||||
)
|
||||
self.o_b_proj = nn.Linear(config.o_groups * config.o_lora_rank, config.hidden_size, bias=False)
|
||||
self.sinks = nn.Parameter(torch.zeros(self.num_heads))
|
||||
self.attn_impl = config._attn_impl
|
||||
# Raised here rather than from the first forward, where it would surface as an ImportError
|
||||
# or a tilelang compile failure a long way from the config that caused it.
|
||||
blocker = _kernel_blocker(self.num_heads, self.head_dim) if self.attn_impl == "kernel" else None
|
||||
if blocker is not None:
|
||||
raise ValueError(f"DeepSeek V4 cannot run the fused sparse-attention kernel: {blocker}")
|
||||
compressor_class = COMPRESSOR_CLASSES[self.layer_type]
|
||||
self.compressor = compressor_class(config) if compressor_class is not None else None
|
||||
|
||||
def _eager(self, q: Tensor, kv: Tensor, attention_mask: Tensor) -> Tensor:
|
||||
return eager_attention_with_sinks(
|
||||
q,
|
||||
kv,
|
||||
kv,
|
||||
self.sinks,
|
||||
attention_mask,
|
||||
scaling=self.scaling,
|
||||
dropout=self.attention_dropout,
|
||||
training=self.training,
|
||||
)
|
||||
|
||||
def _attend(self, q: Tensor, kv: Tensor, compressed: tuple[Tensor, Tensor] | None, packed: PackedContext) -> Tensor:
|
||||
"""Attend `q` (b, h, t, d) over the local KV `kv` (b, 1, t, d), plus any compressed entries.
|
||||
|
||||
Returns (b, t, h, d). A sliding layer sees only its window and passes `compressed` as
|
||||
`None`; a compressed layer reaches further through its compressor's output, the entries
|
||||
paired with the per-query indices selecting among them.
|
||||
|
||||
Every layer lays its slots out once, in `SparseAttnInputs`, and then differs only in the
|
||||
attention core it hands them to, so the eager consumer is an oracle for the kernel rather
|
||||
than a second answer to which keys a query reads.
|
||||
"""
|
||||
compressed_kv, top_k_indices = compressed if compressed is not None else (None, None)
|
||||
inputs = SparseAttnInputs.build(
|
||||
kv=kv,
|
||||
compressed_kv=compressed_kv,
|
||||
top_k_indices=top_k_indices,
|
||||
window_indices=packed.window_indices,
|
||||
)
|
||||
if self.attn_impl == "eager":
|
||||
n_positions = inputs.kv_buf.shape[1]
|
||||
attention_mask = dense_mask_from_indices(inputs.indices, n_positions, q.dtype)
|
||||
return self._eager(q, inputs.kv_buf.transpose(1, 2), attention_mask)
|
||||
|
||||
# `eager_attention_with_sinks` drops attention weights and the kernel does not, so the
|
||||
# two only agree at zero. The default is 0.0 but a config may set it.
|
||||
assert self.attention_dropout == 0.0, "the fused sparse attention kernel implements no dropout"
|
||||
q = q.transpose(1, 2).contiguous() # the kernel asserts contiguity
|
||||
out, _ = dsv4_sparse_attn(q, inputs.kv_buf, inputs.indices, self.sinks, self.scaling)
|
||||
return out
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor, packed: PackedContext) -> tuple[torch.Tensor, None]:
|
||||
"""`packed` carries the document boundaries every pathway below is clipped at."""
|
||||
# Shape keys in the comments below:
|
||||
#
|
||||
# - `b`: batch
|
||||
# - `t`: token in the packed row
|
||||
# - `h`: attention head
|
||||
# - `d`: head_dim
|
||||
# - `e`: compressed entry
|
||||
# - `r`: q_lora_rank
|
||||
# - `g`: o_groups
|
||||
# - `l`: o_lora_rank
|
||||
#
|
||||
# `hidden_states` is (b, t, hidden_size).
|
||||
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim) # (b, t, -1, d): the -1 is h for q, 1 for kv
|
||||
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)
|
||||
|
||||
kv = self.kv_norm(self.kv_proj(hidden_states)).view(*hidden_shape).transpose(1, 2) # (b, 1, t, d)
|
||||
kv = apply_rotary_pos_emb_interleaved(kv, cos, sin)
|
||||
|
||||
compressed = self.compressor(hidden_states, q_residual, packed) if self.compressor is not None else None
|
||||
attn_output = self._attend(q, kv, compressed, packed) # (b, t, h, d)
|
||||
|
||||
# The value stream is the key stream, so it arrived rotated. Rotating the output
|
||||
# by the conjugate angle at the query position cancels that out.
|
||||
attn_output = apply_rotary_pos_emb_interleaved(attn_output, cos, -sin, unsqueeze_dim=2)
|
||||
|
||||
# (b, t, g, h * d // g) -> (b, t, g, l) -> (b, t, g * l)
|
||||
grouped = self.o_a_proj(attn_output.reshape(*input_shape, self.config.o_groups, -1)).flatten(2)
|
||||
return self.o_b_proj(grouped), None # (b, t, hidden_size)
|
||||
|
||||
def init_weights(self, init_std: float) -> None:
|
||||
# `init_std` is only passed through: the sinks are the only parameter this owns
|
||||
# outright and they start at zero.
|
||||
nn.init.zeros_(self.sinks)
|
||||
if self.compressor is not None:
|
||||
self.compressor.init_weights(init_std)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"CompressionLayout",
|
||||
"DeepseekV4Attention",
|
||||
"DeepseekV4CSACompressor",
|
||||
"DeepseekV4GroupedLinear",
|
||||
"DeepseekV4HCACompressor",
|
||||
"DeepseekV4Indexer",
|
||||
"DeepseekV4IndexerScorer",
|
||||
"PackedContext",
|
||||
"SparseAttnInputs",
|
||||
"dense_mask_from_indices",
|
||||
"eager_attention_with_sinks",
|
||||
]
|
||||
@@ -0,0 +1,367 @@
|
||||
from typing import Any, Literal
|
||||
|
||||
from huggingface_hub.dataclasses import strict
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
|
||||
from prime_rl.utils.transformers_compat import DEEPSEEK_V4_LAYER_TYPES, allow_deepseek_v4_layer_types
|
||||
|
||||
# Below transformers 5.15 the base `validate_layer_type` rejects V4's layer types outright, and
|
||||
# it runs from `super().__init__()`, ahead of this class's own override. The inference half of
|
||||
# the repo needs the same shim (see `inference/patches.py`).
|
||||
allow_deepseek_v4_layer_types()
|
||||
|
||||
|
||||
@strict
|
||||
class DeepseekV4Config(PretrainedConfig):
|
||||
"""Configuration for DeepSeek-V4 (Flash / Pro) models.
|
||||
|
||||
DeepSeek-V4 differs from V3 in three structural ways, all controlled from here:
|
||||
|
||||
1. The residual stream is `hc_mult` parallel streams tied together by
|
||||
manifold-constrained hyper-connections (mHC), governed by `hc_mult`,
|
||||
`hc_sinkhorn_iters` and `hc_eps`.
|
||||
2. Attention is a per-layer mix of compressed variants selected by `layer_types`,
|
||||
with the per-type compression rate given by `compress_rates` and a Lightning
|
||||
Indexer sized by `index_n_heads` / `index_head_dim` / `index_topk`.
|
||||
3. The MLP schedule bootstraps the first `num_hash_layers` layers with a frozen hash
|
||||
router before switching to standard top-k routed MoE.
|
||||
|
||||
Args:
|
||||
vocab_size: Vocabulary size.
|
||||
hidden_size: Dimension of the hidden representations.
|
||||
moe_intermediate_size: Intermediate dimension of each expert. Also aliased as
|
||||
`intermediate_size` (the shared expert reads that name).
|
||||
num_hidden_layers: Number of decoder layers.
|
||||
num_attention_heads: Number of attention query heads.
|
||||
num_key_value_heads: Number of key/value heads. V4 is MQA, so this is 1.
|
||||
head_dim: Dimension of each attention head.
|
||||
q_lora_rank: Rank of the query down-projection.
|
||||
partial_rotary_factor: Fraction of `head_dim` that gets RoPE. Defaults to
|
||||
`qk_rope_head_dim / head_dim` if `qk_rope_head_dim` is given, else 64/512.
|
||||
qk_rope_head_dim: Legacy way to express `partial_rotary_factor`. Only read when
|
||||
`partial_rotary_factor` is not given; the derived value is always stored as
|
||||
the `qk_rope_head_dim` attribute.
|
||||
rope_theta: RoPE base for the main self-attention rotary.
|
||||
compress_rope_theta: RoPE base for the compressed attention branches.
|
||||
rope_parameters: RoPE parameters, nested under the `main` and `compress` rope
|
||||
types. A flat dict is broadcast into both.
|
||||
rope_scaling: Legacy alias for `rope_parameters`.
|
||||
max_position_embeddings: Maximum sequence length.
|
||||
sliding_window: Local window size used by every attention block's
|
||||
sliding-window branch.
|
||||
o_groups: Number of head groups in the grouped output projection.
|
||||
o_lora_rank: Per-group intermediate dimension of the grouped output projection.
|
||||
layer_types: Per-layer attention schedule, entries drawn from
|
||||
`DEEPSEEK_V4_LAYER_TYPES`. Defaults to two heavily-compressed bootstrap
|
||||
layers followed by an alternating heavy/sparse interleave.
|
||||
compress_rates: Per-layer-type compression rate.
|
||||
index_n_heads: Number of Lightning Indexer query heads.
|
||||
index_head_dim: Lightning Indexer head dimension.
|
||||
index_topk: Number of compressed entries the Lightning Indexer keeps per query.
|
||||
num_experts_per_tok: Number of routed experts activated per token.
|
||||
n_routed_experts: Total number of routed experts.
|
||||
n_shared_experts: Number of always-on shared experts.
|
||||
scoring_func: Router activation. Only `sqrtsoftplus` is implemented; any other
|
||||
value is rejected when the MoE layer is built.
|
||||
topk_method: Router top-k selection. Only `noaux_tc` (aux-loss-free bias correction) is
|
||||
implemented; the field is carried because vLLM gates `e_score_correction_bias` on it.
|
||||
norm_topk_prob: Whether to renormalize the top-k routing probabilities.
|
||||
routed_scaling_factor: Scaling factor applied to the routed expert output.
|
||||
num_hash_layers: Number of leading hash-routed layers; the remaining layers use
|
||||
standard top-k routed MoE.
|
||||
swiglu_limit: Clamp applied to the expert gate/up pre-activations.
|
||||
hc_mult: Number of parallel residual streams carried by mHC.
|
||||
hc_sinkhorn_iters: Sinkhorn-Knopp iterations used to project the mHC combine
|
||||
matrix onto the doubly-stochastic manifold.
|
||||
hc_eps: Numerical floor for the Sinkhorn-Knopp normalization.
|
||||
hidden_act: Activation function of the MLPs.
|
||||
initializer_range: Standard deviation of the weight initializer.
|
||||
rms_norm_eps: Epsilon of the RMS normalization layers.
|
||||
use_cache: Whether to return past key/values.
|
||||
tie_word_embeddings: Whether to tie the input and output embeddings.
|
||||
attention_bias: Whether the attention projections carry a bias.
|
||||
mlp_bias: Whether the MLP projections carry a bias.
|
||||
attention_dropout: Dropout ratio on the attention probabilities.
|
||||
output_router_logits: Whether to return the router logits.
|
||||
router_aux_loss_coef: Coefficient of the router auxiliary loss.
|
||||
router_jitter_noise: Jitter noise added to the router inputs during training.
|
||||
"""
|
||||
|
||||
model_type = "deepseek_v4"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
# `num_local_experts` is the name FP8 / EP integrations read; `intermediate_size` is
|
||||
# what the shared-expert MLP reads, and V4 only ships `moe_intermediate_size`.
|
||||
attribute_map = {
|
||||
"num_local_experts": "n_routed_experts",
|
||||
"intermediate_size": "moe_intermediate_size",
|
||||
}
|
||||
# `rope_parameters` is keyed by rope type, not by `layer_types`.
|
||||
_rope_type_labels = ("main", "compress")
|
||||
# `qk_rope_head_dim` (64) / `head_dim` (512).
|
||||
default_partial_rotary_factor = 64 / 512
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size: int = 129280,
|
||||
hidden_size: int = 4096,
|
||||
moe_intermediate_size: int = 2048,
|
||||
num_hidden_layers: int = 43,
|
||||
num_attention_heads: int = 64,
|
||||
num_key_value_heads: int = 1,
|
||||
head_dim: int = 512,
|
||||
q_lora_rank: int = 1024,
|
||||
partial_rotary_factor: float | None = None,
|
||||
qk_rope_head_dim: int | None = None,
|
||||
rope_theta: float = 10000.0,
|
||||
compress_rope_theta: float = 160000.0,
|
||||
rope_parameters: dict[str, Any] | None = None,
|
||||
rope_scaling: dict[str, Any] | None = None,
|
||||
max_position_embeddings: int = 1048576,
|
||||
sliding_window: int = 128,
|
||||
o_groups: int = 8,
|
||||
o_lora_rank: int = 1024,
|
||||
layer_types: list[str] | None = None,
|
||||
compress_rates: dict[str, int] | None = None,
|
||||
index_n_heads: int = 64,
|
||||
index_head_dim: int = 128,
|
||||
index_topk: int = 512,
|
||||
_attn_impl: Literal["kernel", "eager"] = "kernel",
|
||||
num_experts_per_tok: int = 6,
|
||||
n_routed_experts: int = 256,
|
||||
n_shared_experts: int = 1,
|
||||
scoring_func: str = "sqrtsoftplus",
|
||||
topk_method: str = "noaux_tc",
|
||||
norm_topk_prob: bool = True,
|
||||
routed_scaling_factor: float = 1.5,
|
||||
num_hash_layers: int = 3,
|
||||
swiglu_limit: float = 10.0,
|
||||
hc_mult: int = 4,
|
||||
hc_sinkhorn_iters: int = 20,
|
||||
hc_eps: float = 1e-6,
|
||||
hidden_act: str = "silu",
|
||||
initializer_range: float = 0.02,
|
||||
rms_norm_eps: float = 1e-6,
|
||||
use_cache: bool = True,
|
||||
tie_word_embeddings: bool = False,
|
||||
attention_bias: bool = False,
|
||||
mlp_bias: bool = False,
|
||||
attention_dropout: float = 0.0,
|
||||
output_router_logits: bool = False,
|
||||
router_aux_loss_coef: float = 0.001,
|
||||
router_jitter_noise: float = 0.0,
|
||||
pad_token_id: int | None = None,
|
||||
bos_token_id: int | None = 0,
|
||||
eos_token_id: int | list[int] | None = 1,
|
||||
**kwargs,
|
||||
):
|
||||
# Real checkpoints ship the V3-flavoured legacy schema (a flat per-layer
|
||||
# `compress_ratios` list of 0/CSA-rate/HCA-rate) instead of `layer_types`. Pop it before
|
||||
# `super().__init__(**kwargs)` sees it, so it can't silently overwrite the derived
|
||||
# `self.compress_ratios` below without ever informing `self.layer_types`.
|
||||
legacy_compress_ratios = kwargs.pop("compress_ratios", None)
|
||||
raw_rope_parameters = rope_parameters if rope_parameters is not None else rope_scaling
|
||||
|
||||
self.vocab_size = vocab_size
|
||||
self.hidden_size = hidden_size
|
||||
self.moe_intermediate_size = moe_intermediate_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
|
||||
# Attention
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.head_dim = head_dim
|
||||
self.q_lora_rank = q_lora_rank
|
||||
self.rope_theta = rope_theta
|
||||
self.compress_rope_theta = compress_rope_theta
|
||||
self.sliding_window = sliding_window
|
||||
self.o_groups = o_groups
|
||||
self.o_lora_rank = o_lora_rank
|
||||
self.attention_bias = attention_bias
|
||||
self.attention_dropout = attention_dropout
|
||||
self.index_n_heads = index_n_heads
|
||||
self.index_head_dim = index_head_dim
|
||||
self.index_topk = index_topk
|
||||
# Exists so tests can run toy shapes the kernel rejects; no shipped config may set it,
|
||||
# and `to_dict` drops it so it never reaches disk.
|
||||
self._attn_impl = _attn_impl
|
||||
|
||||
self.partial_rotary_factor = (
|
||||
partial_rotary_factor
|
||||
if partial_rotary_factor is not None
|
||||
else (qk_rope_head_dim / head_dim if qk_rope_head_dim is not None else self.default_partial_rotary_factor)
|
||||
)
|
||||
self.qk_rope_head_dim = int(head_dim * self.partial_rotary_factor)
|
||||
|
||||
self.compress_rates = (
|
||||
dict(compress_rates)
|
||||
if compress_rates is not None
|
||||
else {"compressed_sparse_attention": 4, "heavily_compressed_attention": 128}
|
||||
)
|
||||
if layer_types is None and legacy_compress_ratios is not None:
|
||||
ratio_to_layer_type = {0: "sliding_attention", **{rate: lt for lt, rate in self.compress_rates.items()}}
|
||||
layer_types = [ratio_to_layer_type[ratio] for ratio in legacy_compress_ratios[:num_hidden_layers]]
|
||||
if layer_types is None:
|
||||
# Two heavily-compressed bootstrap layers, then alternate sparse / heavy.
|
||||
interleave = [
|
||||
"compressed_sparse_attention" if i % 2 else "heavily_compressed_attention"
|
||||
for i in range(max(num_hidden_layers - 2, 0))
|
||||
]
|
||||
layer_types = ["heavily_compressed_attention"] * min(num_hidden_layers, 2) + interleave
|
||||
self.layer_types = list(layer_types)
|
||||
# We don't use this, but vLLM's attention code reads it directly.
|
||||
self.compress_ratios = [self.compress_rates.get(lt, 0) for lt in self.layer_types]
|
||||
|
||||
# MoE
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.n_routed_experts = n_routed_experts
|
||||
self.n_shared_experts = n_shared_experts
|
||||
self.scoring_func = scoring_func
|
||||
self.topk_method = topk_method
|
||||
self.norm_topk_prob = norm_topk_prob
|
||||
self.routed_scaling_factor = routed_scaling_factor
|
||||
self.num_hash_layers = num_hash_layers
|
||||
self.swiglu_limit = swiglu_limit
|
||||
self.output_router_logits = output_router_logits
|
||||
self.router_aux_loss_coef = router_aux_loss_coef
|
||||
self.router_jitter_noise = router_jitter_noise
|
||||
|
||||
# Manifold-constrained hyper-connections
|
||||
self.hc_mult = hc_mult
|
||||
self.hc_sinkhorn_iters = hc_sinkhorn_iters
|
||||
self.hc_eps = hc_eps
|
||||
|
||||
self.hidden_act = hidden_act
|
||||
self.initializer_range = initializer_range
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.use_cache = use_cache
|
||||
self.mlp_bias = mlp_bias
|
||||
|
||||
super().__init__(
|
||||
pad_token_id=pad_token_id,
|
||||
bos_token_id=bos_token_id,
|
||||
eos_token_id=eos_token_id,
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
# Set after the base __init__: its `validate_layer_type` hook is registered at
|
||||
# class-decoration time on `PretrainedConfig` (so a subclass override never runs)
|
||||
# and only accepts the generic "dense" / "sparse" labels, not V4's hash_moe / moe.
|
||||
# Only exists for duck-typing with HF's real modeling code (see `to_dict`) --
|
||||
# `num_hash_layers` is this class's own source of truth.
|
||||
self.mlp_layer_types = ["hash_moe"] * min(num_hidden_layers, num_hash_layers) + ["moe"] * max(
|
||||
0, num_hidden_layers - num_hash_layers
|
||||
)
|
||||
self.rope_parameters = self._nest_rope_parameters(raw_rope_parameters)
|
||||
self.validate_architecture()
|
||||
|
||||
def _nest_rope_parameters(self, raw_rope_parameters: dict[str, Any] | None) -> dict[str, dict[str, Any]]:
|
||||
"""Split RoPE parameters into the `main` and `compress` sets the rotary reads."""
|
||||
rope_parameters = raw_rope_parameters or {}
|
||||
if isinstance(rope_parameters.get("main"), dict) and isinstance(rope_parameters.get("compress"), dict):
|
||||
return {"main": dict(rope_parameters["main"]), "compress": dict(rope_parameters["compress"])}
|
||||
|
||||
scaling = {key: value for key, value in rope_parameters.items() if key not in ("main", "compress")}
|
||||
main = {
|
||||
"rope_type": "default",
|
||||
"rope_theta": self.rope_theta,
|
||||
"partial_rotary_factor": self.partial_rotary_factor,
|
||||
}
|
||||
compress = {
|
||||
**scaling,
|
||||
"rope_theta": self.compress_rope_theta,
|
||||
"partial_rotary_factor": self.partial_rotary_factor,
|
||||
}
|
||||
# Real checkpoints store the compress branch's YaRN scaling under the legacy flat
|
||||
# `rope_scaling` key, which only ever carries `"type"`, never `"rope_type"` -- HF's
|
||||
# own config gets that renamed for free via a generic mixin method that runs before
|
||||
# its DS4-specific post-init logic, but our manual __init__ never goes through it.
|
||||
compress["rope_type"] = scaling.get("rope_type", scaling.get("type", "default"))
|
||||
if compress["rope_type"] == "yarn":
|
||||
# The V4 reference does not scale cos/sin by YaRN's computed mscale; leaving the
|
||||
# key unset lets `_compute_yarn_parameters` derive `0.1*log(factor)+1 != 1.0`.
|
||||
compress.setdefault("attention_factor", 1.0)
|
||||
return {"main": main, "compress": compress}
|
||||
|
||||
def convert_rope_params_to_dict(self, **kwargs):
|
||||
# Dead code: `rope_theta`/`rope_scaling` never reach here via `**kwargs`, and
|
||||
# `self.rope_parameters` is overwritten by `_nest_rope_parameters` right after
|
||||
# `super().__init__()` returns regardless. Kept for parity with the same
|
||||
# (also-dead) override in `laguna/configuration_laguna.py`.
|
||||
return kwargs
|
||||
|
||||
def validate_architecture(self) -> None:
|
||||
"""Compress_rates completeness: every non-sliding layer type needs a rate."""
|
||||
for layer_type in set(self.layer_types) - {"sliding_attention"}:
|
||||
if layer_type not in self.compress_rates:
|
||||
raise ValueError(f"compress_rates is missing a rate for layer type {layer_type!r}.")
|
||||
|
||||
def validate_rope(self) -> None:
|
||||
"""Validate the `main`/`compress` rope-type-keyed sub-dicts directly.
|
||||
|
||||
The base `RotaryEmbeddingConfigMixin.validate_rope` checks `keys ⊆ layer_types`
|
||||
against the *attention* layer types and falls back to treating the whole
|
||||
`rope_parameters` dict as one rope type's params when that fails -- which is always,
|
||||
for V4, since it's keyed by `main`/`compress` rope-type labels instead. Iterate
|
||||
those labels directly, matching upstream HF's own `DeepseekV4Config.validate_rope`.
|
||||
"""
|
||||
rope_parameters_dict = self.rope_parameters or {}
|
||||
ignore_keys = self.ignore_keys_at_rope_validation
|
||||
for rope_type_label in self._rope_type_labels:
|
||||
rope_parameters = rope_parameters_dict.get(rope_type_label)
|
||||
if not isinstance(rope_parameters, dict):
|
||||
continue
|
||||
rope_type = rope_parameters.get("rope_type", rope_parameters.get("type", "default"))
|
||||
rope_parameters["rope_type"] = rope_type
|
||||
validation_fn = getattr(self, f"_validate_{rope_type}_rope_parameters", None)
|
||||
if validation_fn is None:
|
||||
continue
|
||||
self.rope_parameters = rope_parameters
|
||||
try:
|
||||
validation_fn(rope_parameters, ignore_keys=ignore_keys)
|
||||
finally:
|
||||
self.rope_parameters = rope_parameters_dict
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Drop the in-memory-only fields before serializing.
|
||||
|
||||
`num_hash_layers` is the on-disk source of truth (matching the real checkpoint);
|
||||
`mlp_layer_types` only exists in memory so HF's real `DeepseekV4SparseMoeBlock`
|
||||
(which reads `config.mlp_layer_types[layer_idx]` directly) still works when this
|
||||
config is handed to it, e.g. in HF-parity tests. `_attn_impl` is a test knob: an
|
||||
underscore prefix alone would not keep it out, since the base method strips an
|
||||
explicit list of names.
|
||||
"""
|
||||
output = super().to_dict()
|
||||
output.pop("mlp_layer_types", None)
|
||||
output.pop("_attn_impl", None)
|
||||
return output
|
||||
|
||||
def validate_layer_type(self) -> None:
|
||||
"""Narrow `@strict`'s generic layer-type check to V4's own attention vocabulary.
|
||||
|
||||
Re-decorating this class with `@strict` (matching upstream HF's own
|
||||
`DeepseekV4Config`) makes `@strict` rediscover validators scoped to this
|
||||
class, so this override is what runs after `__init__` returns, unlike a
|
||||
plain method override on an undecorated subclass, whose `validate()`
|
||||
closure would keep calling the base `PretrainedConfig.validate_layer_type`.
|
||||
The base one still runs first, from `super().__init__()`, but it checks
|
||||
`layer_types` against transformers' generic vocabulary, which
|
||||
`allow_deepseek_v4_layer_types` widened above precisely so V4's names get
|
||||
through it. Narrowing them to `DEEPSEEK_V4_LAYER_TYPES` is what this adds.
|
||||
"""
|
||||
if len(self.layer_types) != self.num_hidden_layers:
|
||||
raise ValueError(
|
||||
f"layer_types length ({len(self.layer_types)}) must equal num_hidden_layers ({self.num_hidden_layers})."
|
||||
)
|
||||
unknown = sorted({layer_type for layer_type in self.layer_types if layer_type not in DEEPSEEK_V4_LAYER_TYPES})
|
||||
if unknown:
|
||||
raise ValueError(f"layer_types entries must be one of {DEEPSEEK_V4_LAYER_TYPES}; got {unknown}.")
|
||||
if not 0 <= self.num_hash_layers <= self.num_hidden_layers:
|
||||
raise ValueError(
|
||||
f"num_hash_layers ({self.num_hash_layers}) must be between 0 and num_hidden_layers ({self.num_hidden_layers})."
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["DeepseekV4Config"]
|
||||
@@ -0,0 +1,109 @@
|
||||
"""On-disk <-> PrimeRL weight conversion for DeepSeek V4.
|
||||
|
||||
"On-disk" means the safetensors keys DeepSeek publishes for
|
||||
`deepseek-ai/DeepSeek-V4-Flash-0731`, listed in its `model.safetensors.index.json`: a compact
|
||||
naming (`attn`, `ffn`, `wkv`, `wq_a`, `hc_attn_base`, per-expert `w1`/`w2`/`w3`) that carries no
|
||||
`model.` prefix on any of its 72317 keys.
|
||||
|
||||
Nothing else translates those names. The pinned `transformers` ships no DeepSeek V4 model and no
|
||||
`conversion_mapping` entry for one, and prime-rl reads the raw safetensors directly for DCP
|
||||
sharding rather than going through `from_pretrained`, so the chain below is the only mapping
|
||||
between the published checkpoint and prime-rl's module tree.
|
||||
|
||||
It runs both ways: forward for `load_dcp_from_hf`, and reversed (`convert_to_hf`) for the weight
|
||||
broadcast, whose output vLLM's own loader reads back under the published names.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import (
|
||||
ConvOp,
|
||||
Drop,
|
||||
PrefixRename,
|
||||
Rename,
|
||||
routed_experts_op,
|
||||
)
|
||||
|
||||
|
||||
def _layer_ops(layer_idx: int, layer_type: str) -> list[ConvOp]:
|
||||
"""One layer's published names -> prime-rl's module names, one hop per key."""
|
||||
p = f"layers.{layer_idx}"
|
||||
attn, moe = f"{p}.attn", f"{p}.ffn"
|
||||
prime_attn, prime_moe = f"{p}.self_attn", f"{p}.mlp"
|
||||
ops: list[ConvOp] = [
|
||||
Rename(f"{p}.attn_norm.weight", f"{p}.input_layernorm.weight"),
|
||||
Rename(f"{p}.ffn_norm.weight", f"{p}.post_attention_layernorm.weight"),
|
||||
Rename(f"{p}.hc_attn_fn", f"{p}.attn_hc.fn"),
|
||||
Rename(f"{p}.hc_attn_base", f"{p}.attn_hc.base"),
|
||||
Rename(f"{p}.hc_attn_scale", f"{p}.attn_hc.scale"),
|
||||
Rename(f"{p}.hc_ffn_fn", f"{p}.ffn_hc.fn"),
|
||||
Rename(f"{p}.hc_ffn_base", f"{p}.ffn_hc.base"),
|
||||
Rename(f"{p}.hc_ffn_scale", f"{p}.ffn_hc.scale"),
|
||||
Rename(f"{attn}.wq_a.weight", f"{prime_attn}.q_a_proj.weight"),
|
||||
Rename(f"{attn}.q_norm.weight", f"{prime_attn}.q_a_norm.weight"),
|
||||
Rename(f"{attn}.wq_b.weight", f"{prime_attn}.q_b_proj.weight"),
|
||||
Rename(f"{attn}.wkv.weight", f"{prime_attn}.kv_proj.weight"),
|
||||
# Attention's own kv_norm keeps its leaf name; only the parent module differs.
|
||||
Rename(f"{attn}.kv_norm.weight", f"{prime_attn}.kv_norm.weight"),
|
||||
Rename(f"{attn}.wo_a.weight", f"{prime_attn}.o_a_proj.weight"),
|
||||
Rename(f"{attn}.wo_b.weight", f"{prime_attn}.o_b_proj.weight"),
|
||||
Rename(f"{attn}.attn_sink", f"{prime_attn}.sinks"),
|
||||
Rename(f"{moe}.gate.weight", f"{prime_moe}.router.gate.weight"),
|
||||
Rename(f"{moe}.gate.bias", f"{prime_moe}.router.selection_bias"),
|
||||
Rename(f"{moe}.gate.tid2eid", f"{prime_moe}.router.tid2eid"),
|
||||
Rename(f"{moe}.shared_experts.w1.weight", f"{prime_moe}.shared_expert.gate_proj.weight"),
|
||||
Rename(f"{moe}.shared_experts.w2.weight", f"{prime_moe}.shared_expert.down_proj.weight"),
|
||||
Rename(f"{moe}.shared_experts.w3.weight", f"{prime_moe}.shared_expert.up_proj.weight"),
|
||||
# The routed experts' per-expert w1/w2/w3 stack into prime's per-expert-batched tensors,
|
||||
# named as in every other prime-rl MoE.
|
||||
routed_experts_op(
|
||||
p,
|
||||
hf_experts="ffn.experts",
|
||||
prime_experts="mlp.experts",
|
||||
proj_order=(("gate_proj", "w1"), ("down_proj", "w2"), ("up_proj", "w3")),
|
||||
),
|
||||
]
|
||||
if layer_type in ("compressed_sparse_attention", "heavily_compressed_attention"):
|
||||
comp, prime_comp = f"{attn}.compressor", f"{prime_attn}.compressor"
|
||||
ops += [
|
||||
Rename(f"{comp}.wkv.weight", f"{prime_comp}.kv_proj.weight"),
|
||||
Rename(f"{comp}.wgate.weight", f"{prime_comp}.gate_proj.weight"),
|
||||
Rename(f"{comp}.norm.weight", f"{prime_comp}.kv_norm.weight"),
|
||||
Rename(f"{comp}.ape", f"{prime_comp}.position_bias"),
|
||||
]
|
||||
if layer_type == "compressed_sparse_attention":
|
||||
# PrimeRL hangs the indexer off the CSA compressor rather than beside it, so its whole
|
||||
# subtree moves one level in. Its own (much narrower) compressor nests inside either way.
|
||||
idx, prime_idx = f"{attn}.indexer", f"{prime_attn}.compressor.indexer"
|
||||
ops += [
|
||||
Rename(f"{idx}.wq_b.weight", f"{prime_idx}.q_b_proj.weight"),
|
||||
Rename(f"{idx}.weights_proj.weight", f"{prime_idx}.scorer.weights_proj.weight"),
|
||||
Rename(f"{idx}.compressor.wkv.weight", f"{prime_idx}.compressor.kv_proj.weight"),
|
||||
Rename(f"{idx}.compressor.wgate.weight", f"{prime_idx}.compressor.gate_proj.weight"),
|
||||
Rename(f"{idx}.compressor.norm.weight", f"{prime_idx}.compressor.kv_norm.weight"),
|
||||
Rename(f"{idx}.compressor.ape", f"{prime_idx}.compressor.position_bias"),
|
||||
]
|
||||
return ops
|
||||
|
||||
|
||||
def conversion_chain(config) -> list[ConvOp]:
|
||||
# Neither HF nor prime-rl instantiates the multi-token-prediction heads a V4 checkpoint
|
||||
# ships. They sit at the top level (`mtp.0.hc_attn_base`, ...), never nested inside a layer.
|
||||
ops: list[ConvOp] = [
|
||||
Drop("mtp.", is_prefix=True),
|
||||
Rename("head.weight", "lm_head.weight"),
|
||||
]
|
||||
for layer_idx in range(config.num_hidden_layers):
|
||||
ops.extend(_layer_ops(layer_idx, config.layer_types[layer_idx]))
|
||||
# Every op above is written in the bare on-disk spelling, so the `model.` prefix that
|
||||
# prime-rl's module tree carries goes on last: the non-layer parameters individually, and
|
||||
# everything under `layers.` in one reparenting pass.
|
||||
ops += [
|
||||
Rename("embed.weight", "model.embed_tokens.weight"),
|
||||
Rename("norm.weight", "model.norm.weight"),
|
||||
Rename("hc_head_fn", "model.hc_head.hc_fn"),
|
||||
Rename("hc_head_base", "model.hc_head.hc_base"),
|
||||
Rename("hc_head_scale", "model.hc_head.hc_scale"),
|
||||
PrefixRename("layers.", "model.layers."),
|
||||
]
|
||||
return ops
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Dequantize the real DeepSeek V4 Flash checkpoint's on-disk fp8/MXFP4 weights.
|
||||
|
||||
The real `deepseek-ai/DeepSeek-V4-Flash-0731` checkpoint ships dense linear layers as
|
||||
block-quantized FP8 (`float8_e4m3fn` weight + `float8_e8m0fnu` per-block scale, 128x128
|
||||
blocks) and MoE expert weights as packed MXFP4 (two 4-bit e2m1 values per `int8` byte,
|
||||
`float8_e8m0fnu` scale, 1x32 blocks after unpacking). Neither prime-rl's model code nor its
|
||||
DCP loading path can consume either format directly, so this module turns both back into
|
||||
plain `bfloat16` tensors before the checkpoint's state dict reaches the model.
|
||||
|
||||
This is intentionally a one-way, plain preprocessing pass, not a `ConvOp`
|
||||
(`prime_rl.trainer.models.conversion_ops`): that framework is for two-way *structural*
|
||||
conversions between per-key HF and PrimeRL names, whereas dequantization merges two source
|
||||
keys (`*.weight`, `*.scale`) into one output key and is never reversed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import StateDict
|
||||
|
||||
FP4_E2M1_LUT = torch.tensor(
|
||||
[0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0],
|
||||
dtype=torch.float32,
|
||||
)
|
||||
|
||||
|
||||
def _unpack_mxfp4(packed: Tensor) -> Tensor:
|
||||
"""Two packed e2m1 nibbles per `int8` byte -> `float32`, doubling the last dim."""
|
||||
lut = FP4_E2M1_LUT.to(packed.device)
|
||||
u8 = packed.contiguous().view(torch.uint8)
|
||||
low_nibble = (u8 & 0xF).long()
|
||||
high_nibble = ((u8 >> 4) & 0xF).long()
|
||||
unpacked = torch.stack([lut[low_nibble], lut[high_nibble]], dim=-1)
|
||||
return unpacked.reshape(*packed.shape[:-1], 2 * packed.shape[-1])
|
||||
|
||||
|
||||
def dequantize_weight(weight: Tensor, scale: Tensor) -> Tensor:
|
||||
"""Dequantize one on-disk `(weight, scale)` pair to `bfloat16`.
|
||||
|
||||
Dispatches on `weight.dtype`: `torch.int8` is a packed MXFP4 MoE expert weight
|
||||
(unpacked before scaling); `torch.float8_e4m3fn` is a dense fp8 weight. Both apply the
|
||||
same per-block scale multiply, with block size derived from the ratio between the
|
||||
(unpacked) weight's shape and the scale's shape, since dense layers use 128x128 blocks
|
||||
and MoE experts use 1x32 blocks. `scale` is `float8_e8m0fnu`, which decodes correctly via
|
||||
a plain `.float()` cast.
|
||||
"""
|
||||
if weight.dtype == torch.int8:
|
||||
values = _unpack_mxfp4(weight)
|
||||
elif weight.dtype == torch.float8_e4m3fn:
|
||||
values = weight.float()
|
||||
else:
|
||||
raise ValueError(f"Unsupported quantized weight dtype: {weight.dtype}")
|
||||
|
||||
rows, cols = values.shape[-2:]
|
||||
scale_rows, scale_cols = scale.shape[-2:]
|
||||
if rows % scale_rows or cols % scale_cols:
|
||||
raise ValueError(
|
||||
f"Weight shape {tuple(values.shape[-2:])} not divisible by scale grid {tuple(scale.shape[-2:])}"
|
||||
)
|
||||
block_rows, block_cols = rows // scale_rows, cols // scale_cols
|
||||
|
||||
scale_expanded = scale.float().repeat_interleave(block_rows, dim=-2).repeat_interleave(block_cols, dim=-1)
|
||||
return (values * scale_expanded).bfloat16()
|
||||
|
||||
|
||||
def dequantize_state_dict_(state_dict: StateDict) -> None:
|
||||
"""Dequantize every on-disk `*.weight` / `*.scale` pair in place, dropping the scale.
|
||||
|
||||
Must run on raw on-disk key names (e.g. `layers.0.attn.wq_a.weight`,
|
||||
`layers.0.ffn.experts.0.w1.weight`), before any renaming. Keys with no `.scale` sibling
|
||||
(plain `bfloat16`/`float32` params, the `int64` `tid2eid` routing table) have no sibling
|
||||
to pop and are left untouched.
|
||||
"""
|
||||
for key in [k for k in state_dict if k.endswith(".weight")]:
|
||||
scale_key = key.removesuffix(".weight") + ".scale"
|
||||
scale = state_dict.pop(scale_key, None)
|
||||
if scale is None:
|
||||
continue
|
||||
state_dict[key] = dequantize_weight(state_dict[key], scale)
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Naive DeepSeek V4 attention reference.
|
||||
|
||||
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. They take plain
|
||||
tensors, so this module imports nothing from `attention.py` and the dependency runs one way only.
|
||||
"""
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import Tensor
|
||||
|
||||
|
||||
def eager_attention_with_sinks(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
sinks: torch.Tensor,
|
||||
attention_mask: torch.Tensor,
|
||||
scaling: float,
|
||||
dropout: float = 0.0,
|
||||
training: bool = False,
|
||||
) -> torch.Tensor:
|
||||
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
|
||||
attn_weights = attn_weights + attention_mask
|
||||
|
||||
sink_logits = sinks.reshape(1, -1, 1, 1).expand(query.shape[0], -1, query.shape[-2], -1)
|
||||
combined_logits = torch.cat([attn_weights, sink_logits], dim=-1)
|
||||
# Row-max subtraction is not free here: without it the exponentials overflow in bf16.
|
||||
combined_logits = combined_logits - combined_logits.max(dim=-1, keepdim=True).values
|
||||
probs = F.softmax(combined_logits, dim=-1, dtype=combined_logits.dtype)
|
||||
|
||||
scores = F.dropout(probs[..., :-1], p=dropout, training=training).to(value.dtype)
|
||||
attn_output = torch.matmul(scores, value)
|
||||
return attn_output.transpose(1, 2).contiguous()
|
||||
|
||||
|
||||
def build_sliding_window_mask(*, tok_doc_idx: Tensor, sliding_window: int, dtype: torch.dtype) -> Tensor:
|
||||
"""Additive `(1, 1, seq_len, seq_len)` mask over query rows and key columns.
|
||||
|
||||
A key is readable when it lies in the query's own document and within the `sliding_window`
|
||||
tokens up to and including the query.
|
||||
|
||||
A padded micro-batch folds its padding into the last document, so the padding is masked as a
|
||||
continuation of the last document. Causality already keeps it away from every real token, and it
|
||||
is loss-masked.
|
||||
"""
|
||||
seq_len = tok_doc_idx.shape[0]
|
||||
device = tok_doc_idx.device
|
||||
tok_idx = torch.arange(seq_len, device=device)
|
||||
|
||||
distance = tok_idx[:, None] - tok_idx[None, :]
|
||||
in_causal_window = (distance >= 0) & (distance < sliding_window)
|
||||
same_document = tok_doc_idx[:, None] == tok_doc_idx[None, :]
|
||||
readable = in_causal_window & same_document
|
||||
|
||||
mask = torch.zeros(seq_len, seq_len, dtype=dtype, device=device)
|
||||
return mask.masked_fill_(~readable, torch.finfo(dtype).min)[None, None]
|
||||
|
||||
|
||||
def block_bias_from_indices(top_k_indices: Tensor, n_entries: int, dtype: torch.dtype) -> Tensor:
|
||||
"""Render the indexer's picks as the dense additive `(batch, 1, seq_len, n_entries)` bias.
|
||||
|
||||
`0` on the selected entries, `-inf` everywhere else. The dense and sparse attention paths
|
||||
both start from the same index tensor, so they cannot disagree about which entries a query
|
||||
reads.
|
||||
"""
|
||||
batch, seq_len, _ = top_k_indices.shape
|
||||
# The `IGNORE_SLOT` (-1) sentinels are scattered into one throwaway column that is sliced back off.
|
||||
safe_indices = torch.where(top_k_indices >= 0, top_k_indices, torch.full_like(top_k_indices, n_entries))
|
||||
block_bias = torch.full((batch, 1, seq_len, n_entries + 1), float("-inf"), dtype=dtype, device=top_k_indices.device)
|
||||
block_bias.scatter_(-1, safe_indices.unsqueeze(1), 0.0)
|
||||
return block_bias[..., :n_entries]
|
||||
|
||||
|
||||
def dense_mask_from_indices(indices: Tensor, n_positions: int, dtype: torch.dtype) -> Tensor:
|
||||
"""Render a gather-index tensor as the dense additive `(batch, 1, seq_len, n_positions)` mask.
|
||||
|
||||
`indices` is the `(batch, seq_len, 1, n_slots)` int32 tensor addressing the position axis of a
|
||||
`kv_buf` with `n_positions` positions. The mask is `0` on every position at least one of a
|
||||
query's slots names and `-inf` everywhere else. A slot holding `IGNORE_SLOT` (-1) marks an absent
|
||||
key and names no position, so it admits nothing.
|
||||
|
||||
This is the fused kernel's oracle. Rendering the index tensor dense and running naive eager
|
||||
attention over the whole `kv_buf` exercises the index contract and the attention math together.
|
||||
"""
|
||||
batch, seq_len, _, _ = indices.shape
|
||||
slots = indices[:, :, 0, :].to(torch.int64).unsqueeze(1)
|
||||
# `scatter_` has no negative indexing, so `IGNORE_SLOT` (-1) goes into one throwaway column that
|
||||
# is sliced back off. Clamping it to a real position instead would admit a key the query cannot read.
|
||||
safe = torch.where(slots >= 0, slots, n_positions)
|
||||
mask = torch.full((batch, 1, seq_len, n_positions + 1), float("-inf"), dtype=dtype, device=indices.device)
|
||||
mask.scatter_(-1, safe, 0.0)
|
||||
return mask[..., :n_positions].contiguous()
|
||||
@@ -0,0 +1,102 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
|
||||
|
||||
|
||||
class DeepseekV4UnweightedRMSNorm(nn.Module):
|
||||
"""RMS normalization without a learnable gain, computed in fp32."""
|
||||
|
||||
def __init__(self, eps: float = 1e-6):
|
||||
super().__init__()
|
||||
self.eps = eps
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return x * torch.rsqrt(x.float().square().mean(-1, keepdim=True) + self.eps).to(x.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)`.
|
||||
A single projection of the normalized, flattened streams produces three gates:
|
||||
|
||||
- `pre`: weights that collapse the streams into the single sequence fed to the
|
||||
sublayer. Returned already applied, as `collapsed`.
|
||||
- `post`: weights in `[0, 2]` that broadcast the sublayer output back over the
|
||||
streams. Returned for the caller to apply.
|
||||
- `comb`: an `hc_mult x hc_mult` matrix that remixes the streams. It is projected
|
||||
onto the doubly-stochastic manifold by Sinkhorn-Knopp (alternating row and column
|
||||
normalization), which is what makes signal propagation non-expansive across depth.
|
||||
|
||||
The projection and the Sinkhorn iterations run in fp32; only `collapsed` is cast
|
||||
back to the input dtype.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config):
|
||||
super().__init__()
|
||||
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)
|
||||
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]:
|
||||
hc = self.hc_mult
|
||||
flat = self.input_norm(hidden_streams.flatten(start_dim=2).float())
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
collapsed = (pre.unsqueeze(-1) * hidden_streams).sum(dim=2).to(hidden_streams.dtype)
|
||||
return post, comb, collapsed
|
||||
|
||||
def init_weights(self, init_std: float) -> None:
|
||||
nn.init.normal_(self.fn, mean=0.0, std=init_std)
|
||||
nn.init.zeros_(self.base)
|
||||
nn.init.ones_(self.scale)
|
||||
|
||||
|
||||
class DeepseekV4HyperHead(nn.Module):
|
||||
"""Final collapse of the `hc_mult` residual streams, before the model's last norm."""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config):
|
||||
super().__init__()
|
||||
self.hc_mult = config.hc_mult
|
||||
self.input_norm = DeepseekV4UnweightedRMSNorm(eps=config.rms_norm_eps)
|
||||
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())
|
||||
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)
|
||||
|
||||
def init_weights(self, init_std: float) -> None:
|
||||
nn.init.normal_(self.hc_fn, mean=0.0, std=init_std)
|
||||
nn.init.zeros_(self.hc_base)
|
||||
nn.init.ones_(self.hc_scale)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DeepseekV4HyperConnection",
|
||||
"DeepseekV4HyperHead",
|
||||
"DeepseekV4UnweightedRMSNorm",
|
||||
]
|
||||
@@ -0,0 +1,339 @@
|
||||
"""DeepSeek V4 decoder stack, model and causal-LM head.
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
from torch import Tensor, nn
|
||||
from transformers.generation import GenerationMixin
|
||||
from transformers.modeling_layers import GradientCheckpointingLayer
|
||||
from transformers.modeling_outputs import MoeModelOutputWithPast
|
||||
|
||||
from prime_rl.trainer.models.base import CPSupport, PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.deepseek_v4.attention import DeepseekV4Attention, PackedContext
|
||||
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.moe import DeepseekV4MoE
|
||||
from prime_rl.trainer.models.deepseek_v4.rotary import DeepseekV4RotaryEmbedding
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.moe import MoE
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
|
||||
|
||||
class DeepseekV4DecoderLayer(GradientCheckpointingLayer):
|
||||
"""One hyper-connected block: mHC, attention, mHC, MoE.
|
||||
|
||||
Both sublayers read the single sequence their `DeepseekV4HyperConnection` collapsed the
|
||||
streams into, and write back through two gates. `post` broadcasts the sublayer output
|
||||
over the streams; `comb` remixes the streams among themselves and is consumed
|
||||
transposed, i.e. summing over the *source* stream axis. Sinkhorn leaves `comb` doubly
|
||||
stochastic but not symmetric, so that direction is not a free choice.
|
||||
|
||||
Both gates come out of the hyper-connection in fp32 and are cast back to the residual's
|
||||
dtype before mixing, so the residual keeps the dtype it entered with.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config, layer_idx: int):
|
||||
super().__init__()
|
||||
self.layer_idx = layer_idx
|
||||
self.self_attn = DeepseekV4Attention(config, layer_idx)
|
||||
self.mlp = DeepseekV4MoE(config, layer_idx)
|
||||
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.attn_hc = DeepseekV4HyperConnection(config)
|
||||
self.ffn_hc = DeepseekV4HyperConnection(config)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_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)
|
||||
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
|
||||
)
|
||||
|
||||
post, comb, collapsed = self.ffn_hc(hidden_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
|
||||
)
|
||||
|
||||
|
||||
# Mirrors HF's `_keep_in_fp32_modules_strict`, with `e_score_correction_bias` renamed to
|
||||
# the `selection_bias` prime-rl's router keeps it under. The bare `norm` entry subsumes the
|
||||
# named norms; both are kept so the list stays a one-to-one image of HF's.
|
||||
KEEP_IN_FP32_MODULES = (
|
||||
"attn_hc",
|
||||
"ffn_hc",
|
||||
"hc_head",
|
||||
"sinks",
|
||||
"position_bias",
|
||||
"selection_bias",
|
||||
"q_a_norm",
|
||||
"kv_norm",
|
||||
"input_layernorm",
|
||||
"post_attention_layernorm",
|
||||
"norm",
|
||||
)
|
||||
|
||||
|
||||
class DeepseekV4PreTrainedModel(PreTrainedModelPrimeRL):
|
||||
config: DeepseekV4Config
|
||||
config_class = DeepseekV4Config
|
||||
base_model_prefix = "model"
|
||||
supports_gradient_checkpointing = True
|
||||
_no_split_modules = ["DeepseekV4DecoderLayer"]
|
||||
_skip_keys_device_placement = ["past_key_values"]
|
||||
# V4 attention runs its own fused kernel; no transformers backend can serve it.
|
||||
_supports_flash_attn = False
|
||||
_supports_sdpa = False
|
||||
_supports_flex_attn = False
|
||||
_can_compile_fullgraph = False
|
||||
_supports_attention_backend = True
|
||||
_can_record_outputs = {"hidden_states": DeepseekV4DecoderLayer}
|
||||
_keys_to_ignore_on_load_unexpected = [r"(^|\.)mtp\..*"]
|
||||
|
||||
@classmethod
|
||||
def cp_support(cls, config) -> CPSupport:
|
||||
return CPSupport(
|
||||
frozenset(),
|
||||
"its sliding window is built from post-shard document boundaries, "
|
||||
"which CP's global (pre-shard) boundaries cannot address",
|
||||
)
|
||||
|
||||
def _init_weights(self, module: nn.Module) -> None:
|
||||
super()._init_weights(module)
|
||||
init_std = self.config.initializer_range
|
||||
if isinstance(module, (DeepseekV4Attention, DeepseekV4HyperConnection, DeepseekV4HyperHead)):
|
||||
module.init_weights(init_std)
|
||||
elif isinstance(module, DeepseekV4MoE):
|
||||
module.init_weights(init_std, module.tokens_per_expert.device)
|
||||
elif isinstance(module, DeepseekV4RotaryEmbedding):
|
||||
module.init_buffers_post_meta()
|
||||
|
||||
@classmethod
|
||||
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
|
||||
return any(module_name in name for module_name in KEEP_IN_FP32_MODULES)
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
# The published checkpoint's `ffn.*` naming, the only unconverted naming that exists --
|
||||
# see `converting_deepseek_v4.py`'s module docstring.
|
||||
return any(name.endswith("ffn.gate.weight") or "ffn.shared_experts." in name for name in state_dict)
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
# The NCCL transport broadcasts one decoder layer at a time, plus everything outside
|
||||
# `model.layers.` as its own group, and asks this of each group separately. That last group
|
||||
# (embeddings, final norm, `hc_head`, `lm_head`) holds no MoE key, so `model.hc_head.` is
|
||||
# what stops it claiming to be unconverted and skipping the chain.
|
||||
return any(
|
||||
name.endswith("mlp.router.gate.weight") or "mlp.shared_expert." in name or "model.hc_head." in name
|
||||
for name in state_dict
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def conversion_chain(cls, config):
|
||||
return conversion_chain(config)
|
||||
|
||||
def convert_to_prime(self, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
"""Convert a HuggingFace state dict to PrimeRL format in-place.
|
||||
|
||||
Dequantizes the real checkpoint's fp8/MXFP4 weights to `bfloat16` first, on the raw
|
||||
on-disk key names: a no-op for any snapshot that doesn't carry `.scale` siblings
|
||||
(e.g. the plain-`bfloat16` mini test checkpoint).
|
||||
"""
|
||||
dequantize_state_dict_(state_dict)
|
||||
return super().convert_to_prime(state_dict)
|
||||
|
||||
def init_buffers_post_meta(self) -> None:
|
||||
# `to_empty()` leaves every buffer uninitialized and this runs before `dcp_load`, so a
|
||||
# buffer is restored either here or by the checkpoint. Rebuilt here are the ones no
|
||||
# checkpoint carries: the rotary tables (non-persistent, and there is one rotary per
|
||||
# compressor and per indexer on top of the model-level one, so every instance has to be
|
||||
# walked) and `tokens_per_expert`. The router's persistent buffers, `selection_bias` and a
|
||||
# hash layer's `tid2eid`, are in the checkpoint that `dcp_load` applies next, so they are
|
||||
# left to it.
|
||||
for module in self.modules():
|
||||
if isinstance(module, DeepseekV4RotaryEmbedding):
|
||||
module.init_buffers_post_meta()
|
||||
elif isinstance(module, MoE) and module.tokens_per_expert.device.type != "meta":
|
||||
module.tokens_per_expert.zero_()
|
||||
|
||||
|
||||
class DeepseekV4Model(DeepseekV4PreTrainedModel):
|
||||
def __init__(self, config: DeepseekV4Config):
|
||||
super().__init__(config)
|
||||
self.padding_idx = config.pad_token_id
|
||||
self.vocab_size = config.vocab_size
|
||||
|
||||
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
||||
self.layers = nn.ModuleList(
|
||||
[DeepseekV4DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
||||
)
|
||||
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
|
||||
self.rotary_emb = DeepseekV4RotaryEmbedding(config)
|
||||
self.hc_head = DeepseekV4HyperHead(config)
|
||||
self.gradient_checkpointing = False
|
||||
|
||||
self.post_init()
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor | None = None,
|
||||
position_ids: torch.LongTensor | None = None,
|
||||
inputs_embeds: torch.FloatTensor | None = None,
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
) -> MoeModelOutputWithPast:
|
||||
"""
|
||||
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
||||
Token ids. Threaded down to every decoder layer, not just the embedding: the
|
||||
bootstrap layers route on `tid2eid[input_ids]` and cannot run without them.
|
||||
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
||||
Each token's position within its own document. Only checked, never consulted: the
|
||||
positions every rotation and every causal threshold reads are derived from
|
||||
`seq_lens`, so the two cannot disagree.
|
||||
|
||||
NOTE: omitting it is not the same as having no positions. `inject_prime_lm_head`
|
||||
rebinds this model's forward and substitutes a 1-based `arange(1, N + 1)`, which is
|
||||
wrong for V4 twice over, since entries are numbered and rotated from 0: it shifts
|
||||
every query-entry RoPE distance by one and admits an entry whose last source token
|
||||
is one past the query. `check_position_ids` rejects it, so a caller that passes
|
||||
nothing gets a `ValueError` rather than a working default.
|
||||
|
||||
TODO: make that substitution 0-based, matching HF's convention and every other
|
||||
model's own fallback, after which an omitted `position_ids` would just be accepted.
|
||||
routed_experts (`torch.LongTensor` of shape `(batch_size, sequence_length, num_hidden_layers, num_experts_per_tok)`, *optional*):
|
||||
Routed experts for each token in the sequence. Only used for router replay.
|
||||
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
|
||||
Per-document lengths of the packed row (PrimeRL packed-batch contract). Clips the
|
||||
sliding window at document boundaries and lays out the compressors' entries per
|
||||
document, so a packed row gives every document what running it alone would.
|
||||
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
|
||||
Whether `seq_lens` holds pre-CP-shard (global) document boundaries.
|
||||
"""
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
if seq_lens_are_pre_shard:
|
||||
raise NotImplementedError(
|
||||
"DeepSeek V4 does not support context parallelism: the sliding window and the "
|
||||
"compressors' entry layout become indices into this shard's own KV buffer, and "
|
||||
"boundaries for the whole row would put them past its end."
|
||||
)
|
||||
|
||||
if inputs_embeds is None:
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
# Every layer type attends over the same local window; the compressed variants add their
|
||||
# own out-of-window entries and the per-query bias that gates them. One layout per distinct
|
||||
# compress rate, shared by every layer that pools at that rate; sliding layers own no
|
||||
# compressor and contribute no rate.
|
||||
packed = PackedContext.build(
|
||||
rotary_emb=self.rotary_emb,
|
||||
seq_lens=seq_lens,
|
||||
dtype=inputs_embeds.dtype,
|
||||
device=inputs_embeds.device,
|
||||
)
|
||||
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()
|
||||
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,
|
||||
input_ids=input_ids,
|
||||
routed_experts=routed_experts_layer,
|
||||
packed=packed,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(self.hc_head(hidden_states))
|
||||
return MoeModelOutputWithPast(last_hidden_state=hidden_states)
|
||||
|
||||
|
||||
class DeepseekV4ForCausalLM(DeepseekV4PreTrainedModel, GenerationMixin):
|
||||
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
||||
_tp_plan = {"lm_head": "colwise_gather_output"}
|
||||
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
||||
|
||||
def __init__(self, config: DeepseekV4Config):
|
||||
super().__init__(config)
|
||||
self.model = DeepseekV4Model(config)
|
||||
self.vocab_size = config.vocab_size
|
||||
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
||||
self.post_init()
|
||||
|
||||
def get_decoder(self):
|
||||
return self.model
|
||||
|
||||
def set_decoder(self, decoder):
|
||||
self.model = decoder
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor | None = None,
|
||||
position_ids: torch.LongTensor | None = None,
|
||||
inputs_embeds: torch.FloatTensor | None = None,
|
||||
labels: torch.LongTensor | None = None,
|
||||
logits_to_keep: int | torch.Tensor = 0,
|
||||
temperature: torch.Tensor | None = None,
|
||||
routed_experts: torch.LongTensor | None = None,
|
||||
*,
|
||||
seq_lens: torch.LongTensor,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
**kwargs,
|
||||
) -> PrimeLmOutput:
|
||||
"""
|
||||
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
||||
Labels used by PrimeRL's wrapped LM head to optionally compute per-token
|
||||
logprobs/entropy.
|
||||
temperature (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
||||
Per-token temperatures for logprobs/entropy computation when `labels` are given.
|
||||
seq_lens (`torch.LongTensor` of shape `(num_documents,)`):
|
||||
Per-document lengths of the packed row. Required rather than defaulting to one
|
||||
document, so a caller that forgets it fails instead of silently getting a window
|
||||
that spans neighbouring rollouts.
|
||||
"""
|
||||
outputs = self.model(
|
||||
input_ids=input_ids,
|
||||
position_ids=position_ids,
|
||||
inputs_embeds=inputs_embeds,
|
||||
routed_experts=routed_experts,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
)
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
||||
return self.lm_head(
|
||||
hidden_states[:, slice_indices, :],
|
||||
labels[:, slice_indices] if labels is not None else None,
|
||||
temperature=temperature,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DeepseekV4DecoderLayer",
|
||||
"DeepseekV4ForCausalLM",
|
||||
"DeepseekV4Model",
|
||||
"DeepseekV4PreTrainedModel",
|
||||
]
|
||||
@@ -0,0 +1,259 @@
|
||||
"""DeepSeek V4 mixture of experts: router, routed experts and shared expert.
|
||||
|
||||
Both MLP layer types live here. `num_hash_layers` picks between standard token-choice
|
||||
routing and the hash routing of the bootstrap layers, which replaces the learned
|
||||
selection with a frozen token-id lookup but keeps the learned gating weights.
|
||||
"""
|
||||
|
||||
import torch
|
||||
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.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.layers.moe import GroupedExperts, MoE, TokenChoiceTopKRouter
|
||||
|
||||
|
||||
class ClampedSwiglu:
|
||||
"""SwiGLU with both branches clamped, as in HF's `DeepseekV4Experts`.
|
||||
|
||||
Structurally an `Activation`, but with `limit` as instance state: V4 reads its clamp
|
||||
off `config.swiglu_limit`, while the shared `ActivationDispatch` holds stateless
|
||||
classes keyed by name and so has nowhere to put a per-model number.
|
||||
"""
|
||||
|
||||
def __init__(self, limit: float) -> None:
|
||||
self.limit = limit
|
||||
|
||||
def apply(self, gate: torch.Tensor | None, up: torch.Tensor) -> torch.Tensor:
|
||||
assert gate is not None, "V4's routed experts are gated"
|
||||
gate = gate.clamp(max=self.limit)
|
||||
up = up.clamp(min=-self.limit, max=self.limit)
|
||||
return F.silu(gate) * up
|
||||
|
||||
|
||||
class DeepseekV4Router(TokenChoiceTopKRouter):
|
||||
"""Token-choice router scored with `sqrt(softplus(.))`, V4's only scoring function.
|
||||
|
||||
`TokenChoiceTopKRouter.forward` picks its scoring function from an inline
|
||||
`if/elif/else: raise` chain with no hook to extend, and `"sqrtsoftplus"` is outside
|
||||
the `ScoreFuncType` it accepts, so the whole method is restated below. Only the
|
||||
scoring line is new: the `routed_experts` bypass, the selection bias, the
|
||||
normalization, the scaling and the per-expert token count are the base class's,
|
||||
unchanged.
|
||||
"""
|
||||
|
||||
def forward(
|
||||
self, x: torch.Tensor, routed_experts: torch.Tensor | None = None
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
assert routed_experts is None or routed_experts.shape[-1] == self.top_k, (
|
||||
f"routed_experts shape: {routed_experts.shape}, top_k: {self.top_k}"
|
||||
)
|
||||
if self.fp32_gate:
|
||||
gate_bias = self.gate.bias.float() if self.gate.bias is not None else None
|
||||
logits = F.linear(x.float(), self.gate.weight.float(), gate_bias)
|
||||
else:
|
||||
logits = self.gate(x)
|
||||
|
||||
# Scoring runs in float32 to avoid loss explosion, as in the base class. HF scores
|
||||
# in the input dtype instead, so bf16 activations drift from HF by ~1e-3 here.
|
||||
scores = F.softplus(logits.float()).sqrt()
|
||||
|
||||
# NOTE: the selection bias only steers selection. The gating value top_scores is
|
||||
# still derived from the original scores.
|
||||
if routed_experts is not None:
|
||||
top_scores = scores.gather(dim=1, index=routed_experts)
|
||||
selected_experts_indices = routed_experts
|
||||
elif self.force_balanced:
|
||||
num_tokens = scores.shape[0]
|
||||
arange = torch.arange(num_tokens * self.top_k, device=scores.device)
|
||||
selected_experts_indices = (arange % self.num_experts).view(num_tokens, self.top_k)
|
||||
top_scores = scores.gather(dim=1, index=selected_experts_indices)
|
||||
else:
|
||||
selection_scores = scores
|
||||
if self.selection_bias is not None:
|
||||
selection_scores = selection_scores + self.selection_bias
|
||||
_, selected_experts_indices = torch.topk(selection_scores, k=self.top_k, dim=1, sorted=self.topk_sorted)
|
||||
top_scores = scores.gather(dim=1, index=selected_experts_indices)
|
||||
|
||||
with torch.no_grad():
|
||||
selected_probability_mass = top_scores / (scores.sum(dim=-1, keepdim=True) + 1e-20)
|
||||
routing_confidence_sum = selected_probability_mass.sum()
|
||||
|
||||
if self.route_norm:
|
||||
denominator = top_scores.sum(dim=-1, keepdim=True) + 1e-20
|
||||
top_scores = top_scores / denominator
|
||||
top_scores = top_scores * self.route_scale
|
||||
|
||||
num_tokens_per_expert = torch.histc(
|
||||
selected_experts_indices.reshape(-1).float(),
|
||||
bins=self.num_experts,
|
||||
min=0,
|
||||
max=self.num_experts,
|
||||
).to(torch.int64)
|
||||
|
||||
return top_scores, selected_experts_indices, num_tokens_per_expert, routing_confidence_sum
|
||||
|
||||
|
||||
class DeepseekV4HashRouter(DeepseekV4Router):
|
||||
"""A bootstrap layer's router: selection is a frozen token-id lookup, gating still learned.
|
||||
|
||||
`tid2eid` replaces the top-k of the scores with `tid2eid[token_id]`, read from the checkpoint
|
||||
and zeros until one fills it. A frozen selection cannot be steered, so a hash layer has no use
|
||||
for the aux-loss-free load-balancing bias, and HF's `DeepseekV4HashRouter` carries no
|
||||
`e_score_correction_bias` to load into it either; `selection_bias=False` leaves that buffer
|
||||
unbuilt, keeping the state dict aligned with HF's.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dim: int,
|
||||
num_experts: int,
|
||||
top_k: int,
|
||||
score_func: str,
|
||||
route_norm: bool,
|
||||
route_scale: float,
|
||||
vocab_size: int,
|
||||
) -> None:
|
||||
super().__init__(
|
||||
dim=dim,
|
||||
num_experts=num_experts,
|
||||
top_k=top_k,
|
||||
score_func=score_func,
|
||||
route_norm=route_norm,
|
||||
route_scale=route_scale,
|
||||
selection_bias=False,
|
||||
)
|
||||
self.register_buffer("tid2eid", torch.zeros(vocab_size, top_k, dtype=torch.long), persistent=True)
|
||||
|
||||
|
||||
class DeepseekV4Experts(GroupedExperts):
|
||||
"""Routed experts with V4's clamped SwiGLU.
|
||||
|
||||
The shared `GroupedExperts` already stores the stacked `gate_proj`/`up_proj`/`down_proj`
|
||||
that the on-disk per-expert `w1`/`w2`/`w3` convert into, and its `forward` reaches the
|
||||
activation through `self.activation`, so only that attribute and the initialization
|
||||
spread differ from the base class.
|
||||
"""
|
||||
|
||||
def __init__(self, dim: int, hidden_dim: int, num_experts: int, swiglu_limit: float) -> None:
|
||||
super().__init__(dim, hidden_dim, num_experts, expert_type="gated")
|
||||
self.activation = ClampedSwiglu(swiglu_limit)
|
||||
|
||||
def init_weights(self, init_std: float) -> None:
|
||||
# Both halves of HF's fused gate_up_proj are drawn from the same std=0.02
|
||||
# distribution, so gate and up match that here despite being separate tensors.
|
||||
# The base class scales up_proj by init_std instead.
|
||||
nn.init.trunc_normal_(self.gate_proj, mean=0.0, std=0.02)
|
||||
nn.init.trunc_normal_(self.up_proj, mean=0.0, std=0.02)
|
||||
nn.init.trunc_normal_(self.down_proj, mean=0.0, std=init_std)
|
||||
|
||||
|
||||
class DeepseekV4MLP(FeedForward):
|
||||
"""Dense SwiGLU MLP with V4's clamp, used as the MoE layer's shared expert.
|
||||
|
||||
The shared `FeedForward` already names its projections the way HF's `LlamaMLP` (which
|
||||
HF's `DeepseekV4MLP` subclasses) does, and initializes them the same way, so only the
|
||||
activation changes: gate and up are clamped before the SwiGLU. Unlike the routed
|
||||
experts they are separate tensors here, so there is nothing to chunk.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config):
|
||||
# `FeedForward` builds its projections without a bias whatever `bias` says.
|
||||
assert not config.mlp_bias, "mlp_bias is not supported by the shared `FeedForward`"
|
||||
super().__init__(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
activation=config.hidden_act,
|
||||
)
|
||||
self.limit = config.swiglu_limit
|
||||
|
||||
def forward(self, x: torch.Tensor, routed_experts: torch.Tensor | None = None) -> torch.Tensor:
|
||||
gate = self.gate_proj(x).clamp(max=self.limit)
|
||||
up = self.up_proj(x).clamp(min=-self.limit, max=self.limit)
|
||||
return self.down_proj(F.silu(gate) * up)
|
||||
|
||||
|
||||
class DeepseekV4MoE(MoE):
|
||||
"""A V4 MoE layer, hash-routed or standard according to `config.num_hash_layers`.
|
||||
|
||||
Subclasses the shared `MoE` so `configure_moe_runtime` / `setup_fsdp` keep recognizing
|
||||
it, then hands the three V4-specific pieces to the base constructor. `MoE.forward`'s
|
||||
orchestration is unchanged.
|
||||
|
||||
A hash layer routes each token to `tid2eid[token_id]`, the frozen table its
|
||||
`DeepseekV4HashRouter` carries, instead of to the top-k of the router's scores. That is
|
||||
precisely what the shared router's `routed_experts` bypass does, so only the `forward` below
|
||||
differs between the two layer types: it reads the indices out of the table and lets the base
|
||||
class weight them with the learned scores as usual.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config, layer_idx: int):
|
||||
assert config.hidden_act == "silu", (
|
||||
f"the routed experts hardcode SiLU; hidden_act={config.hidden_act!r} is not supported"
|
||||
)
|
||||
if config.scoring_func != "sqrtsoftplus":
|
||||
raise ValueError(
|
||||
f"the router hardcodes sqrt(softplus(.)); scoring_func={config.scoring_func!r} is not supported"
|
||||
)
|
||||
|
||||
is_hash = layer_idx < config.num_hash_layers
|
||||
|
||||
router_kwargs = dict(
|
||||
dim=config.hidden_size,
|
||||
num_experts=config.n_routed_experts,
|
||||
top_k=config.num_experts_per_tok,
|
||||
score_func=config.scoring_func,
|
||||
# HF normalizes the top-k scores unconditionally and never reads
|
||||
# `config.norm_topk_prob`, so neither do we.
|
||||
route_norm=True,
|
||||
route_scale=config.routed_scaling_factor,
|
||||
)
|
||||
router = (
|
||||
DeepseekV4HashRouter(**router_kwargs, vocab_size=config.vocab_size)
|
||||
if is_hash
|
||||
else DeepseekV4Router(**router_kwargs, selection_bias=True)
|
||||
)
|
||||
experts = DeepseekV4Experts(
|
||||
dim=config.hidden_size,
|
||||
hidden_dim=config.moe_intermediate_size,
|
||||
num_experts=config.n_routed_experts,
|
||||
swiglu_limit=config.swiglu_limit,
|
||||
)
|
||||
# HF sizes its shared expert at `moe_intermediate_size` regardless of
|
||||
# `n_shared_experts`, which therefore only decides whether one exists at all.
|
||||
shared_expert = DeepseekV4MLP(config) if config.n_shared_experts > 0 else None
|
||||
|
||||
super().__init__(
|
||||
router=router,
|
||||
experts=experts,
|
||||
shared_expert=shared_expert,
|
||||
# HF scales each expert's output by its routing weight after `down_proj`.
|
||||
score_before_experts=False,
|
||||
load_balance_coeff=None if is_hash else 1e-3,
|
||||
)
|
||||
self.layer_idx = layer_idx
|
||||
self.is_hash = is_hash
|
||||
|
||||
def forward(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
input_ids: torch.Tensor | None = None,
|
||||
routed_experts: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Args:
|
||||
x (torch.Tensor): Input tensor with shape ``(bs, slen, dim)``.
|
||||
input_ids (torch.Tensor | None, optional): Token ids with shape ``(bs, slen)``.
|
||||
Required by a hash layer, ignored by a standard one.
|
||||
routed_experts (torch.Tensor | None, optional): Optional tensor with shape
|
||||
``(bs, slen, top_k)``. Replayed expert indices take precedence over the table.
|
||||
|
||||
Returns:
|
||||
out (torch.Tensor): Output tensor with shape ``(bs, slen, dim)``.
|
||||
"""
|
||||
if self.is_hash and routed_experts is None:
|
||||
assert input_ids is not None, f"layer {self.layer_idx} is hash-routed and needs input_ids"
|
||||
# `(vocab_size, top_k)` indexed by `(bs, slen)` token ids gives `(bs, slen, top_k)`.
|
||||
routed_experts = self.router.tid2eid[input_ids]
|
||||
return super().forward(x, routed_experts=routed_experts)
|
||||
@@ -0,0 +1,155 @@
|
||||
from collections.abc import Callable
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
||||
|
||||
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
|
||||
|
||||
# The rope types whose inverse frequencies are fixed once computed. The two left out,
|
||||
# `dynamic` and `longrope`, rescale theirs per forward against the running sequence length,
|
||||
# which the buffers below, written once in `__init__`, never do.
|
||||
SUPPORTED_ROPE_TYPES = frozenset({"default", "linear", "llama3", "proportional", "yarn"})
|
||||
|
||||
|
||||
def rotate_half_interleaved(x: torch.Tensor) -> torch.Tensor:
|
||||
"""Rotate consecutive channel pairs: `(x0, x1, x2, x3, ...) -> (-x1, x0, -x3, x2, ...)`.
|
||||
|
||||
Not the same as `prime_rl.trainer.models.layers.rotary_emb.rotate_half`, which pairs
|
||||
channel `i` with channel `i + dim / 2` (the GPT-NeoX layout). DeepSeek-V4 stores each
|
||||
rotary pair adjacently, so the two are not interchangeable.
|
||||
"""
|
||||
x1 = x[..., 0::2]
|
||||
x2 = x[..., 1::2]
|
||||
return torch.stack((-x2, x1), dim=-1).flatten(-2)
|
||||
|
||||
|
||||
def apply_rotary_pos_emb_interleaved(
|
||||
x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, unsqueeze_dim: int = 1
|
||||
) -> torch.Tensor:
|
||||
"""Apply interleaved RoPE to the trailing rotary slice of `x`.
|
||||
|
||||
`cos` and `sin` arrive at half width (one entry per interleaved pair) and are widened
|
||||
with `repeat_interleave`. Each head is laid out as `[nope | rope]`, so only the last
|
||||
`2 * cos.shape[-1]` channels rotate and the leading ones pass through untouched.
|
||||
The rotation itself runs in fp32 and is cast back to `x`'s dtype.
|
||||
|
||||
Args:
|
||||
x: Tensor whose last dimension is the head dimension.
|
||||
cos: Half-width cosines, shape `(batch, seq, rope_dim / 2)`.
|
||||
sin: Half-width sines, same shape as `cos`.
|
||||
unsqueeze_dim: Axis of `x` that `cos` / `sin` must broadcast over. Use `1` for a
|
||||
`(batch, heads, seq, head_dim)` layout and `2` for `(batch, seq, heads, head_dim)`.
|
||||
"""
|
||||
cos = cos.repeat_interleave(2, dim=-1).unsqueeze(unsqueeze_dim)
|
||||
sin = sin.repeat_interleave(2, dim=-1).unsqueeze(unsqueeze_dim)
|
||||
rope_dim = cos.shape[-1]
|
||||
nope, rope = x[..., :-rope_dim], x[..., -rope_dim:]
|
||||
rotated = ((rope.float() * cos) + (rotate_half_interleaved(rope).float() * sin)).to(x.dtype)
|
||||
return torch.cat([nope, rotated], dim=-1)
|
||||
|
||||
|
||||
class DeepseekV4RotaryEmbedding(nn.Module):
|
||||
"""Rotary embedding carrying one inverse-frequency table per RoPE type.
|
||||
|
||||
DeepSeek-V4 keys its RoPE parameters by rope type (`main` / `compress`), which is
|
||||
independent of `config.layer_types`: sliding-window layers read `main`, the two
|
||||
compressed attention variants share `compress` with their compressor. Each type gets
|
||||
its own `<type>_inv_freq` / `<type>_original_inv_freq` buffers and
|
||||
`<type>_attention_scaling` scalar.
|
||||
|
||||
Because the rotation is interleaved, `forward` returns `cos` / `sin` at half the
|
||||
rotary width (one entry per pair). `apply_rotary_pos_emb_interleaved` widens them.
|
||||
|
||||
`rope_type` is checkpoint data rather than architecture: V4 ships `default` on `main` and
|
||||
`default` or `yarn` on `compress`, but the config reads whatever the file says. Anything
|
||||
outside `SUPPORTED_ROPE_TYPES` is refused at construction, rather than rotating at
|
||||
frequencies that were meant to be rescaled and never were.
|
||||
"""
|
||||
|
||||
def __init__(self, config: DeepseekV4Config, device: torch.device | None = None):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.max_seq_len_cached = config.max_position_embeddings
|
||||
self.original_max_seq_len = config.max_position_embeddings
|
||||
# Only the nested per-rope-type sub-dicts are real rope types; a flat leftover
|
||||
# `rope_type` key at the top level is not one.
|
||||
self.layer_types = [name for name, params in config.rope_parameters.items() if isinstance(params, dict)]
|
||||
self.rope_type: dict[str, str] = {}
|
||||
for layer_type in self.layer_types:
|
||||
self.rope_type[layer_type] = config.rope_parameters[layer_type]["rope_type"]
|
||||
if self.rope_type[layer_type] not in SUPPORTED_ROPE_TYPES:
|
||||
raise ValueError(
|
||||
f"rope type {self.rope_type[layer_type]!r} on {layer_type!r} is not supported; "
|
||||
f"the supported types are {sorted(SUPPORTED_ROPE_TYPES)}, whose inverse "
|
||||
"frequencies are computed once here and never rescaled per forward"
|
||||
)
|
||||
inv_freq, attention_scaling = self._rope_init_fn(layer_type)(config, device, layer_type=layer_type)
|
||||
self.register_buffer(f"{layer_type}_inv_freq", inv_freq, persistent=False)
|
||||
self.register_buffer(f"{layer_type}_original_inv_freq", inv_freq.clone(), persistent=False)
|
||||
setattr(self, f"{layer_type}_attention_scaling", attention_scaling)
|
||||
|
||||
def _rope_init_fn(self, layer_type: str) -> Callable[..., tuple[torch.Tensor, float]]:
|
||||
rope_type = self.rope_type[layer_type]
|
||||
if rope_type == "default":
|
||||
return self.compute_default_rope_parameters
|
||||
return ROPE_INIT_FUNCTIONS[rope_type]
|
||||
|
||||
def init_buffers_post_meta(self) -> None:
|
||||
"""Re-derive the per-rope-type inverse frequencies in place.
|
||||
|
||||
The tables are computed eagerly in `__init__` and registered non-persistently, so they
|
||||
survive neither meta-device construction nor a `load_state_dict`. Re-deriving them is
|
||||
cheap and idempotent.
|
||||
"""
|
||||
for layer_type in self.layer_types:
|
||||
inv_freq_buffer = getattr(self, f"{layer_type}_inv_freq")
|
||||
inv_freq, attention_scaling = self._rope_init_fn(layer_type)(
|
||||
self.config, inv_freq_buffer.device, layer_type=layer_type
|
||||
)
|
||||
inv_freq_buffer.copy_(inv_freq)
|
||||
getattr(self, f"{layer_type}_original_inv_freq").copy_(inv_freq)
|
||||
setattr(self, f"{layer_type}_attention_scaling", attention_scaling)
|
||||
|
||||
@staticmethod
|
||||
def compute_default_rope_parameters(
|
||||
config: DeepseekV4Config,
|
||||
device: torch.device | None = None,
|
||||
seq_len: int | None = None,
|
||||
layer_type: str | None = None,
|
||||
) -> tuple[torch.Tensor, float]:
|
||||
"""Unscaled inverse frequencies for one rope type's partial rotary slice."""
|
||||
rope_parameters = config.rope_parameters[layer_type]
|
||||
base = rope_parameters["rope_theta"]
|
||||
partial_rotary_factor = rope_parameters.get("partial_rotary_factor", 1.0)
|
||||
head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
||||
dim = int(head_dim * partial_rotary_factor)
|
||||
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float, device=device) / dim))
|
||||
return inv_freq, 1.0
|
||||
|
||||
@torch.no_grad()
|
||||
def forward(
|
||||
self, position_ids: torch.Tensor, layer_type: str, *, dtype: torch.dtype
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
device = position_ids.device
|
||||
inv_freq = getattr(self, f"{layer_type}_inv_freq")
|
||||
attention_scaling = getattr(self, f"{layer_type}_attention_scaling")
|
||||
inv_freq_expanded = inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(device)
|
||||
position_ids_expanded = position_ids[:, None, :].float()
|
||||
|
||||
device_type = device.type if isinstance(device.type, str) and device.type != "mps" else "cpu"
|
||||
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
||||
# No `cat([freqs, freqs])`: interleaved RoPE needs one theta per pair, and
|
||||
# `apply_rotary_pos_emb_interleaved` widens cos/sin next to the rotation.
|
||||
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
||||
cos = freqs.cos() * attention_scaling
|
||||
sin = freqs.sin() * attention_scaling
|
||||
|
||||
return cos.to(dtype=dtype), sin.to(dtype=dtype)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DeepseekV4RotaryEmbedding",
|
||||
"apply_rotary_pos_emb_interleaved",
|
||||
"rotate_half_interleaved",
|
||||
]
|
||||
@@ -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
|
||||
@@ -18,7 +18,7 @@ from transformers.models.gpt_oss.modeling_gpt_oss import (
|
||||
from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.base import CPSupport, PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.gpt_oss.configuration_gpt_oss import GptOssConfig
|
||||
from prime_rl.trainer.models.gpt_oss.converting_gpt_oss import (
|
||||
conversion_chain,
|
||||
@@ -111,6 +111,15 @@ class GptOssPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
_compatible_flash_implementations = ["kernels-community/vllm-flash-attn3", "flash_attention_4"]
|
||||
_can_record_outputs = {"hidden_states": GptOssDecoderLayer}
|
||||
|
||||
@classmethod
|
||||
def cp_support(cls, config) -> CPSupport:
|
||||
return CPSupport(
|
||||
frozenset(),
|
||||
"its attention is HuggingFace's GptOssAttention, which passes per-head sink logits as "
|
||||
"`s_aux`; neither the ring nor the ulysses path forwards them, so CP would silently drop "
|
||||
"the sinks",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return is_hf_state_dict(state_dict)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
IGNORE_SLOT = -1
|
||||
"""A slot is one key a query may read. `IGNORE_SLOT` stands in a slot where the query has no key
|
||||
at all.
|
||||
|
||||
Every query is given the same maximum number of slots, so a query with fewer keys to read leaves
|
||||
the rest empty, and an empty slot contributes nothing to its attention.
|
||||
"""
|
||||
@@ -0,0 +1,222 @@
|
||||
# Torch-facing layer for the DeepSeek V4 sparse attention kernels: the `prime_rl::dsv4_sparse_attn`
|
||||
# and `prime_rl::dsv4_sparse_attn_backward` custom ops, their fake (meta) implementations, and the
|
||||
# autograd rule that ties them together and forms the attention-sink gradient in torch. The
|
||||
# TileLang kernels themselves live in `dsv4_sparse_attn_fwd.py` and `dsv4_sparse_attn_bwd.py`; this
|
||||
# module is the only place that knows both exist.
|
||||
|
||||
# TileLang ships a libcudart stub that proxies to the real CUDA runtime via
|
||||
# dlsym(RTLD_DEFAULT, ...). If the stub's own symbols are the first ones found
|
||||
# (because nothing loaded the real libcudart globally yet), the self-check fails
|
||||
# and the stub calls abort(). Pre-loading the real library with RTLD_GLOBAL
|
||||
# ensures dlsym finds it before the stub's own exports.
|
||||
import ctypes as _ctypes
|
||||
|
||||
try:
|
||||
_ctypes.CDLL("libcudart.so", mode=_ctypes.RTLD_GLOBAL)
|
||||
except Exception:
|
||||
# This is expected on CPU-only machines
|
||||
pass
|
||||
|
||||
import tilelang
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4 import IGNORE_SLOT
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4.dsv4_sparse_attn_bwd import bwd, postprocess, preprocess
|
||||
from prime_rl.trainer.models.kernels.deepseek_v4.dsv4_sparse_attn_fwd import dsv4_sparse_attn_fwd
|
||||
|
||||
LOG2E = 1.44269504
|
||||
|
||||
# The forward tiles the gather-slot axis at `block_I = 64` and the backward at `block_size = 32`,
|
||||
# so the slot count must be a multiple of `lcm(64, 32) = 64`.
|
||||
SLOT_TILE = 64
|
||||
|
||||
|
||||
def _pad_slots_to_tile(indices: torch.Tensor) -> torch.Tensor:
|
||||
"""Widen the gather-slot axis to a multiple of the tile, marking the slots that adds absent.
|
||||
|
||||
Callers state the slots they mean and this covers the difference, so the tile stays a fact
|
||||
about these kernels rather than something the modeling code has to lay out for them. An
|
||||
`IGNORE_SLOT` (-1) slot is masked, so the padding changes no output. Production widths are
|
||||
usually aligned already (`sliding_window + index_topk = 128 + 512 = 640`), and then this
|
||||
returns its argument.
|
||||
"""
|
||||
remainder = indices.shape[-1] % SLOT_TILE
|
||||
if remainder == 0:
|
||||
return indices
|
||||
return F.pad(indices, (0, SLOT_TILE - remainder), value=IGNORE_SLOT).contiguous()
|
||||
|
||||
|
||||
def sparse_attn_shape_error(heads: int, kv_group: int, dim: int) -> str | None:
|
||||
"""The reason these kernels cannot serve this shape, or ``None`` if they can.
|
||||
|
||||
The forward, the backward and the constructor check in `deepseek_v4/attention.py` all need
|
||||
the same answer, so the constraints live here only.
|
||||
"""
|
||||
# The backward's `preprocess` tiles the channel axis at `block_ND = 32` and reads whole
|
||||
# tiles, so a `dim` below that (or not a multiple of it) over-reads into the next head and
|
||||
# silently corrupts `Delta`, hence every gradient. This subsumes `atomic_addx4`'s own
|
||||
# requirement that four channels be contiguous.
|
||||
if dim % 32 != 0:
|
||||
return f"the kernels tile the channel axis at 32 and read whole tiles, but head_dim is {dim}"
|
||||
# The kernels tile the head axis up to a power of two, at least 16, and index `Sinks`, `Q`,
|
||||
# `dO`, `Lse` and `dQ` over that padded block. A head count the tiler pads runs off the end
|
||||
# of all of them; `Q` and `Output` absorb the over-read into the next token's heads, but
|
||||
# `Sinks` is one row with nothing after it.
|
||||
head_kv = heads // kv_group
|
||||
padded_heads = max(tilelang.math.next_power_of_2(head_kv), 16)
|
||||
if padded_heads != head_kv:
|
||||
return (
|
||||
f"the kernels tile {padded_heads} heads per group but this shape has {head_kv}; "
|
||||
"a head count the tiler pads would read and write past the end of the head axis"
|
||||
)
|
||||
# The backward runs `block_H = min(64, padded_H)` rows through a GEMM that needs at least 32.
|
||||
# At 16 heads the forward compiles and runs, then the backward dies mid-step inside tilelang
|
||||
# with "warp_row_tiles must be greater than 16", so a forward-only test will not catch this.
|
||||
if head_kv < 32:
|
||||
return (
|
||||
f"the sparse attention backward needs at least 32 heads per group, got {head_kv}; "
|
||||
"its GEMM over min(64, heads) rows fails to compile below that"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl::dsv4_sparse_attn", mutates_args=())
|
||||
def dsv4_sparse_attn(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
sinks: torch.Tensor,
|
||||
sm_scale: float | None = None,
|
||||
block_I: int = 64,
|
||||
num_stages: int = 2,
|
||||
threads: int = 256,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
assert q.is_contiguous(), "q must be contiguous"
|
||||
assert kv.is_contiguous(), "kv must be contiguous"
|
||||
assert indices.is_contiguous(), "indices must be contiguous"
|
||||
batch, seq_len, heads, dim = q.shape
|
||||
_, _, kv_group, _ = kv.shape
|
||||
|
||||
assert kv.shape[-1] == dim, "q and kv must share the full channel dim; DS V4 has no score-only tail"
|
||||
assert kv.shape[0] == batch
|
||||
assert q.dtype == torch.bfloat16, (
|
||||
f"the sparse attention kernel runs in bfloat16 only, but the queries are {q.dtype}"
|
||||
)
|
||||
shape_error = sparse_attn_shape_error(heads, kv_group, dim)
|
||||
assert shape_error is None, shape_error
|
||||
assert indices.shape[:3] == (batch, seq_len, kv_group)
|
||||
assert sinks.shape == (heads,)
|
||||
indices = _pad_slots_to_tile(indices)
|
||||
topk = indices.shape[-1]
|
||||
|
||||
kernel = dsv4_sparse_attn_fwd(
|
||||
heads,
|
||||
dim,
|
||||
topk,
|
||||
kv_group,
|
||||
sm_scale,
|
||||
True,
|
||||
block_I=block_I,
|
||||
num_stages=num_stages,
|
||||
threads=threads,
|
||||
)
|
||||
out, lse = kernel(q, kv, indices, sinks.float().contiguous())
|
||||
return out, lse
|
||||
|
||||
|
||||
# A fake must mirror the op's signature exactly, so it takes every argument even though only `q`,
|
||||
# the one argument that determines the output shapes, is read.
|
||||
@dsv4_sparse_attn.register_fake
|
||||
def _dsv4_sparse_attn_fake(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
sinks: torch.Tensor,
|
||||
sm_scale: float | None = None,
|
||||
block_I: int = 64,
|
||||
num_stages: int = 2,
|
||||
threads: int = 256,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
return torch.empty_like(q), q.new_empty(q.shape[:-1], dtype=torch.float32)
|
||||
|
||||
|
||||
@torch.library.custom_op("prime_rl::dsv4_sparse_attn_backward", mutates_args=())
|
||||
def dsv4_sparse_attn_backward(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
grad_out: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
lse: torch.Tensor,
|
||||
sm_scale: float | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
assert q.is_contiguous(), "q must be contiguous"
|
||||
assert kv.is_contiguous(), "kv must be contiguous"
|
||||
assert indices.is_contiguous(), "indices must be contiguous"
|
||||
assert lse.is_contiguous(), "lse must be contiguous"
|
||||
grad_out = grad_out.contiguous()
|
||||
batch, seq_len, heads, dim = q.shape
|
||||
_, _, kv_group, _ = kv.shape
|
||||
assert kv.shape[-1] == dim, "q and kv must share the full channel dim; DS V4 has no score-only tail"
|
||||
assert kv.shape[0] == batch
|
||||
# This op is public, so it repeats the forward's shape checks rather than trusting autograd.
|
||||
shape_error = sparse_attn_shape_error(heads, kv_group, dim)
|
||||
assert shape_error is None, shape_error
|
||||
assert indices.shape[:3] == (batch, seq_len, kv_group)
|
||||
assert lse.shape == (batch, seq_len, heads)
|
||||
indices = _pad_slots_to_tile(indices)
|
||||
topk = indices.shape[-1]
|
||||
|
||||
preprocess_kernel = preprocess(heads, dim)
|
||||
bwd_kernel = bwd(heads, dim, topk, kv_group, sm_scale, True)
|
||||
postprocess_kernel = postprocess(dim, kv_group)
|
||||
|
||||
delta = preprocess_kernel(out, grad_out)
|
||||
dkv = torch.zeros_like(kv, dtype=torch.float32)
|
||||
dq = bwd_kernel(q, kv, grad_out, indices, lse, delta, dkv)
|
||||
dkv = postprocess_kernel(dkv)
|
||||
|
||||
return dq, dkv, delta
|
||||
|
||||
|
||||
@dsv4_sparse_attn_backward.register_fake
|
||||
def _dsv4_sparse_attn_backward_fake(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
grad_out: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
lse: torch.Tensor,
|
||||
sm_scale: float | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
return torch.empty_like(q), torch.empty_like(kv), torch.empty_like(lse)
|
||||
|
||||
|
||||
def _dsv4_sparse_attn_setup_context(ctx, inputs, output) -> None:
|
||||
q, kv, indices, sinks, sm_scale, _block_I, _num_stages, _threads = inputs
|
||||
out, lse = output
|
||||
ctx.save_for_backward(q, kv, out, indices, lse, sinks)
|
||||
ctx.sm_scale = sm_scale
|
||||
ctx.mark_non_differentiable(lse)
|
||||
|
||||
|
||||
def _dsv4_sparse_attn_autograd_backward(ctx, grad_out: torch.Tensor, _grad_lse: torch.Tensor | None):
|
||||
q, kv, out, indices, lse, sinks = ctx.saved_tensors
|
||||
dq, dkv, delta = dsv4_sparse_attn_backward(
|
||||
q.detach(),
|
||||
kv.detach(),
|
||||
out.detach(),
|
||||
grad_out,
|
||||
indices,
|
||||
lse.detach(),
|
||||
ctx.sm_scale,
|
||||
)
|
||||
# dp_k/dsink = -p_k * p_sink, so do[d]/dsink = -p_sink * o[d] and the head's sink gradient
|
||||
# contracts to -p_sink * Delta. The sink logit is unscaled, hence no sm_scale factor.
|
||||
p_sink = torch.exp2(sinks.float().view(1, 1, -1) * LOG2E - lse)
|
||||
dsink = -(p_sink * delta).sum(dim=(0, 1)).to(sinks.dtype)
|
||||
return dq, dkv, None, dsink, None, None, None, None
|
||||
|
||||
|
||||
dsv4_sparse_attn.register_autograd(_dsv4_sparse_attn_autograd_backward, setup_context=_dsv4_sparse_attn_setup_context)
|
||||
@@ -0,0 +1,326 @@
|
||||
"""
|
||||
[DeepSeek V4 Sparse Attention: Backward]
|
||||
|
||||
Gradients for the forward in `dsv4_sparse_attn_fwd.py`, whose shapes, index letters and masking
|
||||
rule carry over unchanged. Three kernels:
|
||||
|
||||
preprocess Delta, a per-query-head reduction over the channel axis
|
||||
bwd dQ, and dKV scattered into a float32 buffer
|
||||
postprocess casts that buffer back to bfloat16
|
||||
|
||||
Beyond the forward's tensors:
|
||||
|
||||
dO[b, s, h, d] (B, S, H, D) incoming output gradient, bfloat16
|
||||
Delta[b, s, h] (B, S, H) float32
|
||||
dQ[b, s, h, d] (B, S, H, D) bfloat16
|
||||
dKV[b, n, g, d] (B, N, G, D) float32 until `postprocess`
|
||||
|
||||
[What it computes]
|
||||
|
||||
With `key[b,s,k,d] = KV[b, Indices[b,s,0,k], 0, d]` and `scale = D ** -0.5` as in the forward:
|
||||
|
||||
Delta[b,s,h] = Output[b,s,h,d] dO[b,s,h,d]
|
||||
p[b,s,h,k] = exp2(scale * Q[b,s,h,d] key[b,s,k,d] * log2(e) - Lse[b,s,h])
|
||||
dp[b,s,h,k] = dO[b,s,h,d] key[b,s,k,d]
|
||||
ds[b,s,h,k] = scale * p[b,s,h,k] * (dp[b,s,h,k] - Delta[b,s,h])
|
||||
|
||||
dQ[b,s,h,d] = ds[b,s,h,k] key[b,s,k,d]
|
||||
dkey[b,s,k,d] = ds[b,s,h,k] Q[b,s,h,d] + p[b,s,h,k] dO[b,s,h,d]
|
||||
|
||||
`dkey` has two terms because `V == K`: a gathered position is read once as a key inside the logit
|
||||
and once as a value inside the output. Per tile of `block_size` slots the block runs five GEMMs,
|
||||
two rebuilding `p` and `dp`, one for `dQ`, and two accumulating into the `dkey` tile.
|
||||
|
||||
`p` is recovered from `Lse` with a single `exp2`, never by a second max pass. The sink needs no
|
||||
handling here: it is already inside the `Z` that `Lse` encodes, so this `p` is the shrunken
|
||||
probability the forward produced. No sink gradient is formed in this file; `Delta` is returned so a
|
||||
caller can build one from it.
|
||||
|
||||
[dQ is local, dKV is a scatter]
|
||||
|
||||
A block owns one query position, so that query's `dQ` accumulates in registers and is written once.
|
||||
`dKV` is the opposite: many queries gather the same KV position `n` and they live in different
|
||||
blocks, so the tile is scattered with `atomic_addx4`, four contiguous channels at a time. That is
|
||||
why `dKV` is float32 while everything else here is bfloat16, and why `postprocess` exists.
|
||||
|
||||
Masked slots skip the store rather than adding their exact zero, and no predicate is written for
|
||||
it: TileLang already guards the atomic on both bounds, `0 <= idx < N`, and a masked slot's index is
|
||||
negative.
|
||||
|
||||
[How the loop runs]
|
||||
|
||||
The grid is `(query position, batch, head block)`, the third axis also carrying the KV head when
|
||||
`G > 1`, and at `H <= 64` it is a single block covering every query head. The block walks the `K`
|
||||
slots in tiles of `block_size`, half the forward's tile, and per tile:
|
||||
|
||||
1. gather `KV_shared[k,d]`, and seed `acc_p` to `0` or `-inf` from the mask
|
||||
2. `acc_p[h,k] += Q_shared[h,d] KV_shared[k,d]` onto that seed, then `exp2(... - Lse)` in place,
|
||||
so a masked slot stays `-inf` and becomes exactly zero. This is `p`.
|
||||
3. `acc_dp[h,k] = dO_shared[h,d] KV_shared[k,d]`, then `p * (dp - Delta) * scale` in place: `ds`
|
||||
4. `acc_dq[h,d] += ds[h,k] KV_shared[k,d]`
|
||||
5. `acc_dkv[k,d] = ds[h,k] Q_shared[h,d] + p[h,k] dO_shared[h,d]`, two GEMMs into one tile
|
||||
6. scatter `acc_dkv` into `dKV`, in `split_store` passes through a staging buffer that holds
|
||||
`block_size // split_store` slots
|
||||
|
||||
`acc_dq` accumulates over every tile and is written once after the loop, while `acc_dkv` is cleared
|
||||
each tile because step 6 has already sent it to memory. Steps 2 and 3 leave float32 fragments,
|
||||
which are cast to bfloat16 and staged in shared memory before feeding the GEMMs of steps 4 and 5.
|
||||
|
||||
The TileLang scaffolding is vendored from tile-ai/tilelang (Apache 2.0) and modified for dynamic
|
||||
shapes. As in the forward there is no score-only channel tail, and `Delta` is exposed as an output
|
||||
rather than kept internal so the caller can form the per-head sink gradient from it.
|
||||
"""
|
||||
|
||||
# TileLang ships a libcudart stub that proxies to the real CUDA runtime via
|
||||
# dlsym(RTLD_DEFAULT, ...). If the stub's own symbols are the first ones found
|
||||
# (because nothing loaded the real libcudart globally yet), the self-check fails
|
||||
# and the stub calls abort(). Pre-loading the real library with RTLD_GLOBAL
|
||||
# ensures dlsym finds it before the stub's own exports.
|
||||
import ctypes as _ctypes
|
||||
|
||||
try:
|
||||
_ctypes.CDLL("libcudart.so", mode=_ctypes.RTLD_GLOBAL)
|
||||
except Exception:
|
||||
# This is expected on CPU-only machines
|
||||
pass
|
||||
|
||||
import tilelang
|
||||
from tilelang import language as T
|
||||
|
||||
|
||||
@tilelang.jit(out_idx=[-1])
|
||||
def preprocess(
|
||||
H,
|
||||
D,
|
||||
block_ND=32,
|
||||
num_stages=5,
|
||||
dtype=T.bfloat16,
|
||||
accum_dtype=T.float32,
|
||||
):
|
||||
assert dtype == T.bfloat16
|
||||
assert accum_dtype == T.float32
|
||||
B = T.dynamic("B")
|
||||
S = T.dynamic("S")
|
||||
shape = [B, S, H, D]
|
||||
|
||||
@T.prim_func
|
||||
def preprocess_kernel(
|
||||
O: T.Tensor(shape, dtype),
|
||||
dO: T.Tensor(shape, dtype),
|
||||
Delta: T.Tensor([B, S, H], accum_dtype),
|
||||
):
|
||||
with T.Kernel(H, T.ceildiv(S, block_ND), B) as (bx, by, bz):
|
||||
o = T.alloc_fragment([block_ND, block_ND], accum_dtype)
|
||||
do = T.alloc_fragment([block_ND, block_ND], accum_dtype)
|
||||
delta = T.alloc_fragment([block_ND], accum_dtype)
|
||||
acc = T.alloc_fragment([block_ND, block_ND], accum_dtype)
|
||||
T.clear(acc)
|
||||
for k in T.Pipelined(T.ceildiv(D, block_ND), num_stages=num_stages):
|
||||
T.copy(O[bz, by * block_ND : (by + 1) * block_ND, bx, k * block_ND : (k + 1) * block_ND], o)
|
||||
T.copy(dO[bz, by * block_ND : (by + 1) * block_ND, bx, k * block_ND : (k + 1) * block_ND], do)
|
||||
for i, j in T.Parallel(block_ND, block_ND):
|
||||
acc[i, j] += o[i, j] * do[i, j]
|
||||
T.reduce_sum(acc, delta, 1)
|
||||
T.copy(delta, Delta[bz, by * block_ND : (by + 1) * block_ND, bx])
|
||||
|
||||
return preprocess_kernel
|
||||
|
||||
|
||||
@tilelang.jit(out_idx=[-1])
|
||||
def postprocess(
|
||||
D,
|
||||
kv_group=1,
|
||||
block_N=64,
|
||||
threads=128,
|
||||
dtype=T.bfloat16,
|
||||
accum_dtype=T.float32,
|
||||
):
|
||||
assert dtype == T.bfloat16
|
||||
assert accum_dtype == T.float32
|
||||
B = T.dynamic("B")
|
||||
S_kv = T.dynamic("S_kv")
|
||||
dkv_shape = [B, S_kv, kv_group, D]
|
||||
|
||||
@T.prim_func
|
||||
def postprocess_kernel(
|
||||
dKV: T.Tensor(dkv_shape, accum_dtype),
|
||||
dKV_out: T.Tensor(dkv_shape, dtype),
|
||||
):
|
||||
with T.Kernel(T.ceildiv(S_kv, block_N), kv_group, B, threads=threads) as (bx, by, bz):
|
||||
T.copy(
|
||||
dKV[bz, bx * block_N : (bx + 1) * block_N, by, :],
|
||||
dKV_out[bz, bx * block_N : (bx + 1) * block_N, by, :],
|
||||
)
|
||||
|
||||
return postprocess_kernel
|
||||
|
||||
|
||||
@tilelang.jit(
|
||||
out_idx=[-2],
|
||||
pass_configs={
|
||||
tilelang.PassConfigKey.TL_DISABLE_TMA_LOWER: True,
|
||||
tilelang.PassConfigKey.TL_DISABLE_WARP_SPECIALIZED: True,
|
||||
# Avoid TileLang MLA backward NaNs: https://github.com/tile-ai/tilelang/issues/2199
|
||||
tilelang.PassConfigKey.TL_ENABLE_AGGRESSIVE_SHARED_MEMORY_MERGE: False,
|
||||
},
|
||||
)
|
||||
def bwd(
|
||||
H,
|
||||
D,
|
||||
topk,
|
||||
kv_group=1,
|
||||
sm_scale=None,
|
||||
is_causal=True,
|
||||
block_size=32,
|
||||
num_stages=0,
|
||||
threads=256,
|
||||
indices_dtype=T.int32,
|
||||
dtype=T.bfloat16,
|
||||
accum_dtype=T.float32,
|
||||
):
|
||||
assert is_causal is True, "non-casual is not supported now"
|
||||
assert topk % block_size == 0, "otherwise will load some index=0 thus causing wrong kv to be loaded"
|
||||
assert dtype == T.bfloat16
|
||||
assert accum_dtype == T.float32
|
||||
assert indices_dtype == T.int32
|
||||
|
||||
if sm_scale is None:
|
||||
sm_scale = D ** (-0.5)
|
||||
sm_scale_mul_reciprocal_log2 = sm_scale * 1.44269504 # log2(e)
|
||||
|
||||
B = T.dynamic("B")
|
||||
S = T.dynamic("S")
|
||||
S_kv = T.dynamic("S_kv")
|
||||
|
||||
H_kv = H // kv_group
|
||||
q_shape = [B, S, H, D]
|
||||
k_shape = [B, S_kv, kv_group, D]
|
||||
o_shape = [B, S, H, D]
|
||||
indices_shape = [B, S, kv_group, topk]
|
||||
delta_shape = [B, S, H]
|
||||
lse_shape = [B, S, H]
|
||||
|
||||
H = H_kv
|
||||
padded_H = max(tilelang.math.next_power_of_2(H_kv), 16)
|
||||
block_H = min(64, padded_H)
|
||||
assert padded_H % block_H == 0
|
||||
NH = padded_H // block_H
|
||||
BS = block_size
|
||||
NS = tilelang.cdiv(topk, block_size)
|
||||
|
||||
split_store = 2
|
||||
# The acc_dkv accumulator's per-thread layout (from the GEMMs that produce it) is only
|
||||
# injective at this chunk granularity. TileLang's LayoutInference pass would reject a smaller
|
||||
# chunk if the store loop below were written over its natural extent, but that loop instead
|
||||
# iterates the full BS extent and masks with `if bi_i < chunk`, which bypasses the check: an
|
||||
# invalid chunk silently emits an aliased address formula and corrupts dKV rather than
|
||||
# raising. Verified this holds independent of warp specialization/TMA.
|
||||
chunk = BS // split_store
|
||||
if chunk < 8 or chunk & (chunk - 1) != 0:
|
||||
raise ValueError(
|
||||
f"block_size // split_store must be a power of two >= 8, got block_size={BS}, "
|
||||
f"split_store={split_store} (chunk={chunk}); see comment above for why this silently "
|
||||
"corrupts dKV instead of failing loudly if violated."
|
||||
)
|
||||
|
||||
@T.prim_func
|
||||
def dsv4_sparse_attn_bwd_kernel(
|
||||
Q: T.Tensor(q_shape, dtype),
|
||||
KV: T.Tensor(k_shape, dtype),
|
||||
dO: T.Tensor(o_shape, dtype),
|
||||
Indices: T.Tensor(indices_shape, indices_dtype),
|
||||
Lse: T.Tensor(lse_shape, accum_dtype),
|
||||
Delta: T.Tensor(delta_shape, accum_dtype),
|
||||
dQ: T.Tensor(q_shape, dtype),
|
||||
dKV: T.Tensor(k_shape, accum_dtype),
|
||||
):
|
||||
with T.Kernel(S, B, kv_group * NH, threads=threads) as (s_i, by, bz):
|
||||
Q_shared = T.alloc_shared([block_H, D], dtype)
|
||||
KV_shared = T.alloc_shared([BS, D], dtype)
|
||||
dO_shared = T.alloc_shared([block_H, D], dtype)
|
||||
mask = T.alloc_fragment([BS], "bool")
|
||||
|
||||
P_shared_cast = T.alloc_shared([block_H, BS], dtype)
|
||||
dP_shared_cast = T.alloc_shared([block_H, BS], dtype)
|
||||
dQ_shared = T.alloc_shared([block_H, D], dtype)
|
||||
|
||||
acc_p = T.alloc_fragment([block_H, BS], accum_dtype)
|
||||
acc_dp = T.alloc_fragment([block_H, BS], accum_dtype)
|
||||
acc_dq = T.alloc_fragment([block_H, D], accum_dtype)
|
||||
acc_dkv = T.alloc_fragment([BS, D], accum_dtype)
|
||||
acc_dkv_shared = T.alloc_shared([BS // split_store, D], accum_dtype)
|
||||
|
||||
# See dsv4_sparse_attn_fwd: a negative index marks an absent key and is the only
|
||||
# thing masked on, which makes the kernel work for both full and CP-sharded Q
|
||||
# without needing a global Q offset. TileLang's guarded gather zero-fills the shared
|
||||
# tile for such a slot, so no clamp is needed here either.
|
||||
|
||||
T.copy(Q[by, s_i, bz * block_H : (bz + 1) * block_H, :], Q_shared)
|
||||
T.copy(dO[by, s_i, bz * block_H : (bz + 1) * block_H, :], dO_shared)
|
||||
|
||||
T.clear(acc_dq)
|
||||
|
||||
for i_i in T.Pipelined(NS, num_stages=num_stages):
|
||||
for bi_i in T.Parallel(BS):
|
||||
mask[bi_i] = Indices[by, s_i, bz // NH, i_i * BS + bi_i] >= 0
|
||||
|
||||
for h_i, bi_i in T.Parallel(block_H, BS):
|
||||
acc_p[h_i, bi_i] = T.if_then_else(mask[bi_i], 0, -T.infinity(acc_p.dtype))
|
||||
|
||||
for bi_i, d_i in T.Parallel(BS, D):
|
||||
KV_shared[bi_i, d_i] = KV[by, Indices[by, s_i, bz // NH, i_i * BS + bi_i], bz // NH, d_i]
|
||||
|
||||
T.gemm(Q_shared, KV_shared, acc_p, transpose_B=True, policy=T.GemmWarpPolicy.FullCol)
|
||||
|
||||
for h_i, bi_i in T.Parallel(block_H, BS):
|
||||
acc_p[h_i, bi_i] = T.exp2(
|
||||
acc_p[h_i, bi_i] * sm_scale_mul_reciprocal_log2 - Lse[by, s_i, bz * block_H + h_i]
|
||||
)
|
||||
|
||||
T.copy(acc_p, P_shared_cast)
|
||||
|
||||
T.gemm(
|
||||
dO_shared, KV_shared, acc_dp, transpose_B=True, policy=T.GemmWarpPolicy.FullCol, clear_accum=True
|
||||
)
|
||||
|
||||
for h_i, bi_i in T.Parallel(block_H, BS):
|
||||
acc_dp[h_i, bi_i] = (
|
||||
acc_p[h_i, bi_i] * (acc_dp[h_i, bi_i] - Delta[by, s_i, bz * block_H + h_i]) * sm_scale
|
||||
)
|
||||
|
||||
T.copy(acc_dp, dP_shared_cast)
|
||||
T.gemm(dP_shared_cast, KV_shared, acc_dq, policy=T.GemmWarpPolicy.FullCol)
|
||||
|
||||
T.gemm(
|
||||
dP_shared_cast,
|
||||
Q_shared,
|
||||
acc_dkv,
|
||||
transpose_A=True,
|
||||
policy=T.GemmWarpPolicy.FullCol,
|
||||
clear_accum=True,
|
||||
)
|
||||
T.gemm(P_shared_cast, dO_shared, acc_dkv, transpose_A=True, policy=T.GemmWarpPolicy.FullCol)
|
||||
|
||||
for s in range(split_store):
|
||||
for bi_i, d_i in T.Parallel(BS, D):
|
||||
if bi_i < BS // split_store:
|
||||
acc_dkv_shared[bi_i, d_i] = acc_dkv[bi_i + s * (BS // split_store), d_i]
|
||||
|
||||
# A masked slot accumulates exactly zero, and issuing its atomic would only
|
||||
# serialize the scatter. No predicate is written here because TileLang already
|
||||
# emits `if (0 <= idx)` and `if (idx < S_kv)` around the store, so a negative
|
||||
# index skips it for free and an out-of-range one cannot write past the end of
|
||||
# dKV. Do not add a predicate back: reading the `mask` fragment here compiles
|
||||
# cleanly but pins this loop to the four threads owning those elements.
|
||||
for bi_i, d_i in T.Parallel(BS // split_store, D // 4):
|
||||
slot_i = i_i * BS + bi_i + s * (BS // split_store)
|
||||
T.atomic_addx4(
|
||||
dKV[by, Indices[by, s_i, bz // NH, slot_i], bz // NH, d_i * 4],
|
||||
acc_dkv_shared[bi_i, d_i * 4],
|
||||
)
|
||||
|
||||
T.copy(acc_dq, dQ_shared)
|
||||
|
||||
T.copy(dQ_shared, dQ[by, s_i, bz * block_H : (bz + 1) * block_H, :])
|
||||
|
||||
return dsv4_sparse_attn_bwd_kernel
|
||||
@@ -0,0 +1,277 @@
|
||||
"""
|
||||
[DeepSeek V4 Sparse Attention: Forward]
|
||||
|
||||
Each query attends to an explicit list of `K` KV positions supplied by the caller, rather than to
|
||||
a contiguous causal span. This kernel only reads that list; it has no opinion on how the positions
|
||||
were chosen. Because every query carries a different list, the kernel runs one block per query
|
||||
position instead of tiling over a block of queries the way dense flash attention does.
|
||||
|
||||
Shapes, with the capital of an index letter naming that axis's size:
|
||||
|
||||
Q[b, s, h, d] (B, S, H, D) queries, bfloat16
|
||||
KV[b, n, g, d] (B, N, G, D) keys, bfloat16; V == K here, so one buffer is both
|
||||
Indices[b, s, g, k] (B, S, G, K) int32 positions into KV's `n` axis
|
||||
Sinks[h] (H,) float32, one learnable logit per query head
|
||||
Output[b, s, h, d] (B, S, H, D) bfloat16
|
||||
Lse[b, s, h] (B, S, H) float32
|
||||
|
||||
- `b` batch index
|
||||
- `s` query position
|
||||
- `n` KV position
|
||||
- `k` gather slot, one of the `K` a query reads
|
||||
- `d` head dimension
|
||||
- `h` query head index
|
||||
- `g` KV head index, always of size 1; see below
|
||||
|
||||
`G` is always 1: every query head reads the same single KV head. The axis survives from the
|
||||
vendored scaffolding, where `G > 1` would split the `H` query heads into `G` contiguous blocks of
|
||||
`H / G`, each reading its own KV head. Nothing exercises that path, and the head-padding case
|
||||
asserts `G == 1` outright, so the equations below fix `g = 0` and drop it. Note that the parameter
|
||||
is spelled `kv_group` but counts KV heads; the query heads per KV head are `H / G`, spelled
|
||||
`head_kv`.
|
||||
|
||||
[What it computes]
|
||||
|
||||
Write `key[b,s,k,d] = KV[b, Indices[b,s,0,k], 0, d]` for the gathered keys. Summing over repeated
|
||||
indices, and with `scale = D ** -0.5`:
|
||||
|
||||
logit[b,s,h,k] = scale * Q[b,s,h,d] key[b,s,k,d]
|
||||
Z[b,s,h] = exp(Sinks[h]) + sum_k exp(logit[b,s,h,k])
|
||||
p[b,s,h,k] = exp(logit[b,s,h,k]) / Z[b,s,h]
|
||||
Output[b,s,h,d] = p[b,s,h,k] key[b,s,k,d]
|
||||
Lse[b,s,h] = log2(Z[b,s,h])
|
||||
|
||||
Note: the sink logit is unscaled; `scale` multiplies the dot products and not `Sinks`. And `Lse`
|
||||
is a base-2 logarithm of a partition function built from natural exponentials, not `ln Z`; that is
|
||||
what lets the backward recover `p` as `exp2(logit * log2(e) - Lse)` with a single `exp2`.
|
||||
|
||||
The sink contributes to the denominator but owns no key, so `sum_k p[b,s,h,k] < 1` and `Output` is
|
||||
a shrunken combination of the gathered keys. That is how a head attends to nothing in particular.
|
||||
|
||||
[What the caller must guarantee]
|
||||
|
||||
`K` is fixed when the kernel compiles and is part of its compilation key, so it is sized for the
|
||||
most keys any query could need and a given query will often have fewer.
|
||||
|
||||
Every unused slot must hold a negative index, which is the masking condition:
|
||||
|
||||
Indices[b,s,0,k] < 0 .
|
||||
|
||||
This is the only masking the kernel performs. It applies no causality test and never compares
|
||||
`k` against `s`: whatever the caller means by a valid key is encoded entirely in the index values.
|
||||
That is also what keeps the kernel correct when `s` is a local index that does not correspond to a
|
||||
global KV position.
|
||||
|
||||
Every other entry must be a real position in `[0, N)`. Nothing checks that: a device-side check
|
||||
would cost a sync, so an out-of-range index silently corrupts that query's softmax.
|
||||
|
||||
[How the loop runs]
|
||||
|
||||
The grid is `(query position, batch, KV head)`, so with `G == 1` that is one block per query
|
||||
position per batch index, holding all `H` query heads of that query at once, or a 64-head chunk
|
||||
when `H > 64` (`REPLICATE_H`). The block walks the `K` slots in tiles of `block_I`,
|
||||
software-pipelined `num_stages` deep, and per tile:
|
||||
|
||||
1. gather `KV_shared[k,d] = KV[b, Indices[b,s,0,k], 0, d]` into one shared tile of keys
|
||||
2. `acc_s[h,k] = Q_shared[h,d] KV_shared[k,d]`, pre-seeded to `-inf` at masked slots
|
||||
3. rescale the running max, the denominator and `acc_o` (online softmax)
|
||||
4. `acc_o[h,d] += acc_s[h,k] KV_shared[k,d]`, reusing that same tile as values
|
||||
|
||||
Step 4 reusing step 1's tile is the `V == K` property: the gather is paid for once and feeds both
|
||||
GEMMs.
|
||||
|
||||
The online softmax is seeded from the sink rather than from an empty sum. `m_i` is carried in raw
|
||||
dot-product units, so seeding it with `Sinks[h] / scale` makes `m_i * scale * log2(e)` equal
|
||||
`Sinks[h] * log2(e)`, and seeding `sumexp` to `1` is exactly that term's own exponential relative
|
||||
to that max. `T.reduce_max(..., clear=False)` then keeps the sink as a floor on the running max. A
|
||||
query whose slots are all masked therefore emits `Output = 0` and a finite
|
||||
`Lse = Sinks[h] * log2(e)`, where a zero-seeded denominator would divide by zero.
|
||||
|
||||
The TileLang scaffolding is vendored from tile-ai/tilelang (Apache 2.0) and modified for dynamic
|
||||
shapes. The attention itself differs from tilelang's sparse MLA: there is no score-only channel
|
||||
tail (every channel feeds both the score and the output), and the per-head learnable sink logit is
|
||||
folded into the online softmax as described above.
|
||||
"""
|
||||
|
||||
# TileLang ships a libcudart stub that proxies to the real CUDA runtime via
|
||||
# dlsym(RTLD_DEFAULT, ...). If the stub's own symbols are the first ones found
|
||||
# (because nothing loaded the real libcudart globally yet), the self-check fails
|
||||
# and the stub calls abort(). Pre-loading the real library with RTLD_GLOBAL
|
||||
# ensures dlsym finds it before the stub's own exports.
|
||||
import ctypes as _ctypes
|
||||
|
||||
try:
|
||||
_ctypes.CDLL("libcudart.so", mode=_ctypes.RTLD_GLOBAL)
|
||||
except Exception:
|
||||
# This is expected on CPU-only machines
|
||||
pass
|
||||
|
||||
import tilelang
|
||||
from tilelang import language as T
|
||||
|
||||
LOG2E = 1.44269504
|
||||
|
||||
|
||||
@tilelang.jit(
|
||||
out_idx=[-2, -1],
|
||||
pass_configs={
|
||||
tilelang.PassConfigKey.TL_DISABLE_TMA_LOWER: True,
|
||||
tilelang.PassConfigKey.TL_DISABLE_WARP_SPECIALIZED: True,
|
||||
},
|
||||
)
|
||||
def dsv4_sparse_attn_fwd(
|
||||
heads,
|
||||
dim,
|
||||
topk,
|
||||
kv_group=1,
|
||||
sm_scale=None,
|
||||
is_causal=True,
|
||||
block_I=64,
|
||||
num_stages=2,
|
||||
threads=256,
|
||||
):
|
||||
assert dim == tilelang.math.next_power_of_2(dim), f"haven't check padding correctness yet, dim={dim}"
|
||||
assert is_causal is True, "non-casual is not supported"
|
||||
assert topk % block_I == 0, "otherwise will load some index=0 thus causing wrong kv to be loaded"
|
||||
if sm_scale is None:
|
||||
sm_scale = (1.0 / dim) ** 0.5
|
||||
# Both names are kept: the sink logit enters the softmax unscaled, so seeding the running max
|
||||
# with it means dividing by the raw scale that every `exp2` site below multiplies back in.
|
||||
sm_scale_mul_reciprocal_log2 = sm_scale * LOG2E
|
||||
|
||||
batch = T.dynamic("batch")
|
||||
seq_len = T.dynamic("seq_len")
|
||||
seq_len_kv = T.dynamic("seq_len_kv")
|
||||
|
||||
head_kv = heads // kv_group
|
||||
q_shape = [batch, seq_len, heads, dim]
|
||||
kv_shape = [batch, seq_len_kv, kv_group, dim]
|
||||
o_shape = [batch, seq_len, heads, dim]
|
||||
indices_shape = [batch, seq_len, kv_group, topk]
|
||||
sinks_shape = [heads]
|
||||
lse_shape = [batch, seq_len, heads]
|
||||
indices_dtype = T.int32
|
||||
dtype = T.bfloat16
|
||||
accum_dtype = T.float32
|
||||
|
||||
H = head_kv
|
||||
padded_H = max(tilelang.math.next_power_of_2(head_kv), 16)
|
||||
if padded_H != H:
|
||||
assert kv_group == 1, (
|
||||
"here we solve the H padding automatically, other wise you should handle Q copy and Output copy"
|
||||
" with your mask (when kv_group == 1, use g_i * padded_H:(g_i+1) * padded_H would be handled"
|
||||
" automatically)"
|
||||
)
|
||||
BI = block_I
|
||||
NI = tilelang.cdiv(topk, block_I)
|
||||
D = dim
|
||||
|
||||
if head_kv > 64:
|
||||
assert head_kv % 64 == 0, "head_kv should be a multiple of 64"
|
||||
REPLICATE_H = head_kv // 64
|
||||
else:
|
||||
REPLICATE_H = 1
|
||||
|
||||
H_per_block = padded_H if REPLICATE_H == 1 else 64
|
||||
|
||||
@T.prim_func
|
||||
def main(
|
||||
Q: T.Tensor(q_shape, dtype), # type: ignore
|
||||
KV: T.Tensor(kv_shape, dtype), # type: ignore
|
||||
Indices: T.Tensor(indices_shape, indices_dtype), # type: ignore
|
||||
Sinks: T.Tensor(sinks_shape, accum_dtype), # type: ignore
|
||||
Output: T.Tensor(o_shape, dtype), # type: ignore
|
||||
Lse: T.Tensor(lse_shape, accum_dtype), # type: ignore
|
||||
):
|
||||
with T.Kernel(seq_len * REPLICATE_H, batch, kv_group, threads=threads) as (
|
||||
bx,
|
||||
by,
|
||||
bz,
|
||||
):
|
||||
Q_shared = T.alloc_shared([H_per_block, D], dtype)
|
||||
KV_shared = T.alloc_shared([BI, D], dtype)
|
||||
mask = T.alloc_fragment([BI], "bool")
|
||||
|
||||
acc_o = T.alloc_fragment([H_per_block, D], accum_dtype)
|
||||
acc_s = T.alloc_fragment([H_per_block, BI], accum_dtype)
|
||||
S_shared = T.alloc_shared([H_per_block, BI], dtype)
|
||||
sumexp = T.alloc_fragment([H_per_block], accum_dtype)
|
||||
sumexp_i = T.alloc_fragment([H_per_block], accum_dtype)
|
||||
alpha = T.alloc_fragment([H_per_block], accum_dtype)
|
||||
m_i = T.alloc_fragment([H_per_block], accum_dtype)
|
||||
m_i_prev = T.alloc_fragment([H_per_block], accum_dtype)
|
||||
|
||||
b_i, g_i = by, bz
|
||||
s_i = bx if REPLICATE_H == 1 else (bx // REPLICATE_H)
|
||||
# A negative index marks an absent key, and it is the only thing this kernel masks
|
||||
# on. That preserves causality and varlen masking for both full and CP-sharded Q
|
||||
# (where local q_i no longer matches the global K position), because the caller has
|
||||
# already resolved all of it into the index values.
|
||||
#
|
||||
# No clamp guards the gather below. TileLang lowers it to `cp_async_gs_conditional`,
|
||||
# whose condition is `0 <= idx < seq_len_kv` and whose `cp.async` src-size operand is
|
||||
# 0 when that fails, so PTX zero-fills the shared tile. A masked slot therefore reads
|
||||
# as a zero key. The backward relies on the same guard; the sibling
|
||||
# `kernels/sparse_mla_{fwd,bwd}.py` still use a trailing zero sentinel row instead.
|
||||
|
||||
H0 = g_i * padded_H + (0 if REPLICATE_H == 1 else (bx % REPLICATE_H) * 64)
|
||||
H1 = H0 + H_per_block
|
||||
|
||||
T.fill(acc_o, 0)
|
||||
# The online softmax starts from the sink term alone rather than from an empty sum:
|
||||
# `m_i` carries raw dot-product units, so `m_i * sm_scale_mul_reciprocal_log2` equals
|
||||
# `sink * log2(e)` and the seed `sumexp` of 1 is exactly that term's own exponential.
|
||||
# `T.reduce_max(..., clear=False)` then keeps the sink as a floor on the running max.
|
||||
# A row whose slots are all masked therefore emits `out = 0` and a finite
|
||||
# `Lse = sink * log2(e)`, where a zero-seeded denominator would divide by zero.
|
||||
for h_i in T.Parallel(H_per_block):
|
||||
sumexp[h_i] = 1.0
|
||||
for h_i in T.Parallel(H_per_block):
|
||||
m_i[h_i] = Sinks[H0 + h_i] / sm_scale
|
||||
|
||||
T.copy(Q[b_i, s_i, H0:H1, :], Q_shared)
|
||||
|
||||
for i_i in T.Pipelined(NI, num_stages=num_stages):
|
||||
for bi_i in T.Parallel(BI):
|
||||
mask[bi_i] = Indices[b_i, s_i, g_i, i_i * BI + bi_i] >= 0
|
||||
|
||||
for bi_i, d_i in T.Parallel(BI, D):
|
||||
KV_shared[bi_i, d_i] = KV[b_i, Indices[b_i, s_i, g_i, i_i * BI + bi_i], g_i, d_i]
|
||||
|
||||
for h_i, bi_i in T.Parallel(H_per_block, BI):
|
||||
acc_s[h_i, bi_i] = T.if_then_else(mask[bi_i], 0, -T.infinity(acc_s.dtype))
|
||||
T.gemm(
|
||||
Q_shared,
|
||||
KV_shared,
|
||||
acc_s,
|
||||
transpose_B=True,
|
||||
policy=T.GemmWarpPolicy.FullRow,
|
||||
)
|
||||
T.copy(m_i, m_i_prev)
|
||||
T.reduce_max(acc_s, m_i, dim=1, clear=False)
|
||||
for h_i in T.Parallel(H_per_block):
|
||||
m_i[h_i] = T.max(m_i[h_i], m_i_prev[h_i])
|
||||
for h_i in T.Parallel(H_per_block):
|
||||
alpha[h_i] = T.exp2((m_i_prev[h_i] - m_i[h_i]) * sm_scale_mul_reciprocal_log2)
|
||||
for h_i, bi_i in T.Parallel(H_per_block, BI):
|
||||
acc_s[h_i, bi_i] = T.exp2(
|
||||
acc_s[h_i, bi_i] * sm_scale_mul_reciprocal_log2 - m_i[h_i] * sm_scale_mul_reciprocal_log2
|
||||
)
|
||||
T.reduce_sum(acc_s, sumexp_i, dim=1)
|
||||
for h_i in T.Parallel(H_per_block):
|
||||
sumexp[h_i] = sumexp[h_i] * alpha[h_i] + sumexp_i[h_i]
|
||||
for h_i, d_i in T.Parallel(H_per_block, D):
|
||||
acc_o[h_i, d_i] = acc_o[h_i, d_i] * alpha[h_i]
|
||||
|
||||
T.copy(acc_s, S_shared)
|
||||
T.gemm(S_shared, KV_shared, acc_o, policy=T.GemmWarpPolicy.FullRow)
|
||||
|
||||
for h_i, d_i in T.Parallel(H_per_block, D):
|
||||
acc_o[h_i, d_i] /= sumexp[h_i]
|
||||
for h_i in T.Parallel(H_per_block):
|
||||
sumexp[h_i] = T.log2(sumexp[h_i]) + m_i[h_i] * sm_scale_mul_reciprocal_log2
|
||||
|
||||
T.copy(acc_o, Output[b_i, s_i, H0:H1, :])
|
||||
T.copy(sumexp, Lse[b_i, s_i, H0:H1])
|
||||
|
||||
return main
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -333,7 +333,7 @@ def _patch_model_forward(model: nn.Module) -> None:
|
||||
is_multimodal = kwargs.get("pixel_values") is not None
|
||||
if position_ids is None and not is_multimodal:
|
||||
reference_tensor = input_ids if input_ids is not None else inputs_embeds
|
||||
position_ids = torch.arange(1, reference_tensor.shape[1] + 1, device=reference_tensor.device).unsqueeze(0)
|
||||
position_ids = torch.arange(reference_tensor.shape[1], device=reference_tensor.device).unsqueeze(0)
|
||||
model_kwargs = {"input_ids": input_ids, "position_ids": position_ids, **kwargs}
|
||||
if inputs_embeds is not None:
|
||||
model_kwargs["inputs_embeds"] = inputs_embeds
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -19,7 +19,7 @@ from transformers.modeling_outputs import BaseModelOutputWithPast
|
||||
from transformers.models.nemotron_h.modular_nemotron_h import NemotronHMamba2Mixer
|
||||
from transformers.utils import auto_docstring, logging
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.base import CPSupport, PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
|
||||
from prime_rl.trainer.models.layers.cp_mamba import mamba_cp_forward
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
@@ -377,6 +377,14 @@ class NemotronHPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
_supports_sdpa = False
|
||||
_can_compile_fullgraph = False
|
||||
|
||||
@classmethod
|
||||
def cp_support(cls, config) -> CPSupport:
|
||||
return CPSupport(
|
||||
frozenset({"ulysses"}),
|
||||
"ring CP is a softmax-attention algorithm and cannot run this model's Mamba layers, "
|
||||
"whereas ulysses' all-to-all on Q/K/V leaves the SSM kernel unchanged",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
|
||||
return name.endswith(("mamba.A_log", "mamba.D", "mlp.router.selection_bias"))
|
||||
|
||||
@@ -16,7 +16,7 @@ from transformers.models.qwen3_5.modeling_qwen3_5 import Qwen3_5VisionModel
|
||||
from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.base import ALL_CP_STYLES, CPSupport, PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
|
||||
@@ -137,6 +137,19 @@ class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
|
||||
"hidden_states": Qwen3_5DecoderLayer,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def cp_support(cls, config) -> CPSupport:
|
||||
# VLM configs nest the layer schedule under `text_config`.
|
||||
text_config = getattr(config, "text_config", config)
|
||||
if "linear_attention" in (getattr(text_config, "layer_types", None) or ()):
|
||||
return CPSupport(
|
||||
frozenset({"ulysses"}),
|
||||
"ring CP is a softmax-attention algorithm and cannot run this model's DeltaNet "
|
||||
"layers, whereas ulysses' all-to-all on Q/K/V leaves the linear-attention kernel "
|
||||
"unchanged",
|
||||
)
|
||||
return CPSupport(ALL_CP_STYLES)
|
||||
|
||||
@classmethod
|
||||
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
|
||||
return name.endswith(("linear_attn.A_log", "linear_attn.norm.weight"))
|
||||
|
||||
@@ -19,7 +19,7 @@ from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeVisio
|
||||
from transformers.processing_utils import Unpack
|
||||
from transformers.utils import TransformersKwargs, logging
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.base import ALL_CP_STYLES, CPSupport, PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.attn import (
|
||||
flash_attn_3_varlen_func,
|
||||
flash_attn_4_varlen_func,
|
||||
@@ -598,6 +598,19 @@ class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
"hidden_states": Qwen3_5MoeDecoderLayer,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def cp_support(cls, config) -> CPSupport:
|
||||
# VLM configs nest the layer schedule under `text_config`.
|
||||
text_config = getattr(config, "text_config", config)
|
||||
if "linear_attention" in (getattr(text_config, "layer_types", None) or ()):
|
||||
return CPSupport(
|
||||
frozenset({"ulysses"}),
|
||||
"ring CP is a softmax-attention algorithm and cannot run this model's DeltaNet "
|
||||
"layers, whereas ulysses' all-to-all on Q/K/V leaves the linear-attention kernel "
|
||||
"unchanged",
|
||||
)
|
||||
return CPSupport(ALL_CP_STYLES)
|
||||
|
||||
@classmethod
|
||||
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
|
||||
return name.endswith(("linear_attn.A_log", "linear_attn.norm.weight"))
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -15,14 +15,17 @@ class AnnotationWriter:
|
||||
"""Collects the trainer's per-token streams (recomputed logprobs, entropies) during
|
||||
a step and logs them as trace updates — one record per trained sequence, keyed by
|
||||
``(trace_id, branch_index)``. Streams are full-length over the sample's token prefix
|
||||
so readers can fold them onto trace nodes without knowing the trainer's loss mask.
|
||||
so readers can fold them onto trace nodes without knowing the trainer's loss mask;
|
||||
positions outside that mask hold null, since a fold keeps sampled tokens only and a
|
||||
run of nulls costs nothing once the stream is sealed.
|
||||
|
||||
``export`` accumulates locally per micro batch; ``flush`` gathers every rank's
|
||||
records to rank 0, the only rank running monitors. CP ranks past the first
|
||||
accumulate nothing since they share their micro batches."""
|
||||
|
||||
def __init__(self, parallel_dims: Any, world: Any) -> None:
|
||||
def __init__(self, parallel_dims: Any, world: Any, float_decimals: int | None) -> None:
|
||||
self.world = world
|
||||
self.float_decimals = float_decimals
|
||||
self.is_duplicate_rank = parallel_dims.cp_enabled and parallel_dims.world_mesh["cp"].get_local_rank() != 0
|
||||
self._pending: list[dict[str, Any]] = []
|
||||
|
||||
@@ -36,8 +39,8 @@ class AnnotationWriter:
|
||||
sequence_lengths = micro_batch["sequence_lengths"]
|
||||
loss_mask = [bool(v) for v in micro_batch["loss_mask"].detach().cpu().reshape(-1).tolist()]
|
||||
env_names = micro_batch["env_names"]
|
||||
trainer_logprobs = _tensor_to_floats(model_output["logprobs"])
|
||||
entropies = _tensor_to_floats(model_output["entropy"])
|
||||
trainer_logprobs = _tensor_to_floats(model_output["logprobs"], self.float_decimals)
|
||||
entropies = _tensor_to_floats(model_output["entropy"], self.float_decimals)
|
||||
|
||||
start = 0
|
||||
for trace_id, branch_index, length in zip(trace_ids, branch_indices, sequence_lengths):
|
||||
@@ -50,8 +53,9 @@ class AnnotationWriter:
|
||||
end -= 1
|
||||
if end <= span_start or not any(loss_mask[span_start:end]):
|
||||
continue
|
||||
logprob_span = trainer_logprobs[span_start:end]
|
||||
entropy_span = entropies[span_start:end]
|
||||
trained = loss_mask[span_start:end]
|
||||
logprob_span = [v if m else None for v, m in zip(trainer_logprobs[span_start:end], trained)]
|
||||
entropy_span = [v if m else None for v, m in zip(entropies[span_start:end], trained)]
|
||||
# After the right shift, a sample's first value crosses the packing boundary.
|
||||
logprob_span[0] = None
|
||||
entropy_span[0] = None
|
||||
@@ -77,6 +81,10 @@ class AnnotationWriter:
|
||||
asyncio.run(monitors.log_annotations(records))
|
||||
|
||||
|
||||
def _tensor_to_floats(tensor: Tensor) -> list[float | None]:
|
||||
def _tensor_to_floats(tensor: Tensor, decimals: int | None) -> list[float | None]:
|
||||
"""Rounded like the record's own logprobs: the streams only ever colour an overlay,
|
||||
and full-precision digits are the least compressible bytes a run writes."""
|
||||
values = tensor.detach().to(dtype=torch.float32, device="cpu").reshape(-1).tolist()
|
||||
return [float(value) if math.isfinite(value) else None for value in values]
|
||||
if decimals is None:
|
||||
return [value if math.isfinite(value) else None for value in values]
|
||||
return [round(value, decimals) if math.isfinite(value) else None for value in values]
|
||||
|
||||
@@ -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)
|
||||
@@ -204,17 +205,12 @@ def train(config: TrainerConfig):
|
||||
|
||||
substitute_hf_ulysses_attn(cp_group)
|
||||
substitute_ulysses_attn(cp_group, attn_impl=config.model.attn)
|
||||
from prime_rl.utils.cp import (
|
||||
assert_cp_style_supports_model,
|
||||
setup_model_cp,
|
||||
setup_sparse_mla_cp,
|
||||
)
|
||||
from prime_rl.utils.cp import setup_model_cp, setup_sparse_mla_cp
|
||||
|
||||
assert_cp_style_supports_model(config.model.cp_style, model)
|
||||
# sparse MLA is softmax (works with both ring and ulysses).
|
||||
setup_sparse_mla_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
# Linear-attn / Mamba layers are only configured under ulysses; with ring
|
||||
# we'd have already raised above.
|
||||
# Linear-attn / Mamba layers are only configured under ulysses; models that have them
|
||||
# declare ulysses-only in `cp_support`, so `get_model` already rejected ring.
|
||||
if config.model.cp_style == "ulysses":
|
||||
setup_model_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
|
||||
@@ -258,7 +254,9 @@ def train(config: TrainerConfig):
|
||||
)
|
||||
logger.debug(f"Initialized data loader in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
annotation_writer = AnnotationWriter(parallel_dims, world)
|
||||
annotation_writer = AnnotationWriter(
|
||||
parallel_dims, world, config.monitors.file.float_decimals if config.monitors.file else None
|
||||
)
|
||||
|
||||
gc_handler = GarbageCollection(config.gc.interval) if config.gc else None
|
||||
|
||||
@@ -763,6 +761,7 @@ def train(config: TrainerConfig):
|
||||
|
||||
logger.info(f"Peak memory: {max_peak_memory:.1f} GiB")
|
||||
logger.success("RL trainer finished")
|
||||
asyncio.run(monitors.finalize())
|
||||
|
||||
# Stop metrics/health server if configured
|
||||
if metrics_server is not None:
|
||||
|
||||
@@ -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)
|
||||
@@ -162,13 +163,10 @@ def train(config: SFTConfig):
|
||||
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later)
|
||||
|
||||
if parallel_dims.cp_enabled:
|
||||
from prime_rl.utils.cp import assert_cp_style_supports_model
|
||||
|
||||
assert_cp_style_supports_model(config.model.cp_style, model)
|
||||
# sparse MLA is softmax (works with both ring and ulysses).
|
||||
setup_sparse_mla_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
# Linear-attn / Mamba layers are only configured under ulysses; with ring
|
||||
# we'd have already raised above.
|
||||
# Linear-attn / Mamba layers are only configured under ulysses; models that have them
|
||||
# declare ulysses-only in `cp_support`, so `get_model` already rejected ring.
|
||||
if config.model.cp_style == "ulysses":
|
||||
setup_model_cp(model, cp_group, cp_rank, parallel_dims.cp)
|
||||
|
||||
|
||||
@@ -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}")
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -3,7 +3,7 @@ from __future__ import annotations
|
||||
# ruff: noqa: I001 — `prime_rl._compat` must run before `ring_flash_attn` imports below.
|
||||
import prime_rl._compat # noqa: F401
|
||||
|
||||
from typing import Literal
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
@@ -13,7 +13,10 @@ from ring_flash_attn import update_ring_flash_attn_params
|
||||
from prime_rl.trainer.distributed.collectives import all_gather
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
CPStyle = Literal["ring", "ulysses"]
|
||||
if TYPE_CHECKING:
|
||||
# `prime_rl.trainer.models` imports this module, so importing the model base eagerly would
|
||||
# cycle. `from __future__ import annotations` keeps CPStyle out of the runtime path.
|
||||
from prime_rl.trainer.models.base import CPStyle
|
||||
|
||||
|
||||
def _has_linear_attn_layer(model: nn.Module) -> bool:
|
||||
@@ -35,24 +38,6 @@ def _has_linear_attn_layer(model: nn.Module) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def assert_cp_style_supports_model(cp_style: CPStyle, model: nn.Module) -> None:
|
||||
"""Refuse `cp_style='ring'` on models that have linear/SSM attention layers.
|
||||
|
||||
Ring CP is a softmax-attention algorithm (sequence ring all-gather of K/V).
|
||||
For non-softmax layers (DeltaNet, Mamba) we'd need a fundamentally different
|
||||
CP scheme, which is not implemented. Use `cp_style='ulysses'` for those:
|
||||
ulysses' all-to-all is purely on Q/K/V tensors, so the linear/SSM kernel
|
||||
runs unchanged on a sequence shard.
|
||||
"""
|
||||
if cp_style == "ring" and _has_linear_attn_layer(model):
|
||||
raise ValueError(
|
||||
"cp_style='ring' is not supported for models with linear-attention "
|
||||
"or Mamba/SSM layers (e.g. Qwen3.5 hybrid, NemotronH). Use "
|
||||
"cp_style='ulysses' instead — its all-to-all on Q/K/V works "
|
||||
"out-of-the-box with non-softmax kernels."
|
||||
)
|
||||
|
||||
|
||||
def setup_model_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
"""Hand the CP topology to models whose layers need it (DeltaNet, Mamba).
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Shims for architectures newer than the pinned transformers version.
|
||||
|
||||
Kept free of heavy imports: this is loaded from a vLLM general plugin, in every vLLM
|
||||
process, before the engine parses a model config.
|
||||
"""
|
||||
|
||||
DEEPSEEK_V4_LAYER_TYPES = (
|
||||
"sliding_attention",
|
||||
"compressed_sparse_attention",
|
||||
"heavily_compressed_attention",
|
||||
)
|
||||
|
||||
|
||||
def allow_deepseek_v4_layer_types() -> None:
|
||||
"""Add V4's compressed attention names to the vocabulary transformers validates against.
|
||||
|
||||
`PretrainedConfig.validate_layer_type` checks `layer_types` entries against a module-level
|
||||
tuple, and transformers only added V4's two compressed names in 5.15. Below that, every
|
||||
DeepSeek V4 config raises on construction: prime-rl's own (whose `validate_layer_type`
|
||||
override cannot help, since the base one runs first, from `super().__init__()`) and vLLM's
|
||||
(`vllm/transformers_utils/configs/deepseek_v4.py`, which has no override at all). Extending
|
||||
the tuple is what lets the repo hold a transformers pin below 5.15 and still serve V4.
|
||||
"""
|
||||
from transformers import configuration_utils
|
||||
|
||||
unknown = tuple(
|
||||
layer_type
|
||||
for layer_type in DEEPSEEK_V4_LAYER_TYPES
|
||||
if layer_type not in configuration_utils.ALLOWED_LAYER_TYPES
|
||||
)
|
||||
if unknown:
|
||||
configuration_utils.ALLOWED_LAYER_TYPES += unknown
|
||||
@@ -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.
|
||||
|
||||
@@ -158,7 +167,15 @@ def gather_weights_parallel(model: nn.Module, dtype: torch.dtype = torch.bfloat1
|
||||
only the master keeping everything, each rank copies its owned slice to CPU —
|
||||
so the D2H traffic and the shard writes are split across ranks. The copies are
|
||||
plain blocking transfers; no stream-ordering assumptions.
|
||||
|
||||
Parameters the model reports via ``keep_in_fp32_for_weight_transfer`` skip the
|
||||
downcast. Those lists exist because the inference engine's kernels require fp32
|
||||
for them: vLLM's DeepSeek V4 hyper-connection kernels, for instance, assert
|
||||
``fn``/``base``/``scale`` are fp32, and its loader silently casts a bf16 tensor
|
||||
back up rather than failing, so a downcast here shows up as lost mantissa in a
|
||||
Sinkhorn normalization rather than as an error.
|
||||
"""
|
||||
keep_in_fp32 = getattr(model, "keep_in_fp32_for_weight_transfer", None)
|
||||
world = get_world()
|
||||
owners = partition_weights(model.state_dict(), world.world_size, dtype)
|
||||
partial: dict[str, Tensor] = {}
|
||||
@@ -169,7 +186,8 @@ 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
|
||||
value = cast(DTensor, value.to(dtype)).full_tensor()
|
||||
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
|
||||
partial[resolve_fqn(model, key)] = value.to("cpu")
|
||||
|
||||
@@ -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])
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -11,6 +11,9 @@ EXPECTED_PARSERS: list[tuple[str, str | None, str | None]] = [
|
||||
("arcee-ai/Trinity-Mini", "hermes", "deepseek_r1"),
|
||||
("arcee-ai/Trinity-Nano-Preview", "hermes", "deepseek_r1"),
|
||||
# DeepSeek
|
||||
("deepseek-ai/DeepSeek-V4-Flash-0731", "deepseek_v4", "deepseek_v4"),
|
||||
("deepseek-ai/DeepSeek-V4-Flash", "deepseek_v4", "deepseek_v4"),
|
||||
("deepseek-ai/DeepSeek-V4-Pro-0813", "deepseek_v4", "deepseek_v4"),
|
||||
("deepseek-ai/DeepSeek-V3.2", "deepseek_v32", "deepseek_r1"),
|
||||
("deepseek-ai/DeepSeek-V3.2-Exp", "deepseek_v32", "deepseek_r1"),
|
||||
("deepseek-ai/DeepSeek-V3.1", "deepseek_v31", "deepseek_r1"),
|
||||
|
||||
@@ -0,0 +1,899 @@
|
||||
import math
|
||||
import re
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.configs.trainer import ModelConfig
|
||||
from prime_rl.trainer.model import load_dcp_from_hf
|
||||
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config, DeepseekV4ForCausalLM
|
||||
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.rotary import DeepseekV4RotaryEmbedding
|
||||
from prime_rl.trainer.models.layers import norms
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.utils.utils import default_dtype
|
||||
|
||||
pytestmark = [pytest.mark.gpu]
|
||||
|
||||
# Deliberately heterogeneous: one layer of every attention type, hash-routed bootstrap
|
||||
# layers ahead of standard MoE ones, and a sliding window narrow enough that the compressed
|
||||
# branches are what carries any long-range signal.
|
||||
MODEL = dict(
|
||||
vocab_size=64,
|
||||
hidden_size=128,
|
||||
moe_intermediate_size=64,
|
||||
num_hidden_layers=5,
|
||||
num_attention_heads=4,
|
||||
num_key_value_heads=1,
|
||||
head_dim=32,
|
||||
q_lora_rank=64,
|
||||
partial_rotary_factor=0.5,
|
||||
rope_theta=10000.0,
|
||||
compress_rope_theta=160000.0,
|
||||
max_position_embeddings=256,
|
||||
sliding_window=6,
|
||||
o_groups=2,
|
||||
o_lora_rank=16,
|
||||
layer_types=[
|
||||
"sliding_attention",
|
||||
"compressed_sparse_attention",
|
||||
"heavily_compressed_attention",
|
||||
"compressed_sparse_attention",
|
||||
"sliding_attention",
|
||||
],
|
||||
compress_rates={"compressed_sparse_attention": 4, "heavily_compressed_attention": 8},
|
||||
index_n_heads=4,
|
||||
index_head_dim=24,
|
||||
# Smaller than the number of compressed entries the sequence yields, so the Lightning
|
||||
# Indexer's selection has to actually discard some of them.
|
||||
index_topk=2,
|
||||
n_routed_experts=8,
|
||||
num_experts_per_tok=3,
|
||||
n_shared_experts=1,
|
||||
scoring_func="sqrtsoftplus",
|
||||
routed_scaling_factor=1.5,
|
||||
swiglu_limit=10.0,
|
||||
num_hash_layers=2,
|
||||
hc_mult=4,
|
||||
hc_sinkhorn_iters=20,
|
||||
hc_eps=1e-6,
|
||||
rms_norm_eps=1e-6,
|
||||
)
|
||||
|
||||
MODEL_BATCH, MODEL_SEQ = 2, 32
|
||||
MODULE_BATCH = 2
|
||||
|
||||
SLIDING_LAYER, CSA_LAYER, HCA_LAYER = 0, 1, 2
|
||||
COMPRESS_RATE = MODEL["compress_rates"]["compressed_sparse_attention"]
|
||||
HCA_COMPRESS_RATE = MODEL["compress_rates"]["heavily_compressed_attention"]
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _seed_rng():
|
||||
torch.manual_seed(0)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def _torch_rms_norm(monkeypatch):
|
||||
"""Make the shared `RMSNorm` take its PyTorch path instead of the quack kernel.
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def _tid2eid(vocab_size: int, num_experts: int, top_k: int) -> torch.Tensor:
|
||||
"""A frozen token id -> expert ids table, distinct experts per row as a real one has."""
|
||||
rows = [torch.randperm(num_experts)[:top_k] for _ in range(vocab_size)]
|
||||
return torch.stack(rows).to(device="cuda", dtype=torch.long)
|
||||
|
||||
|
||||
def _randomize(module: nn.Module) -> None:
|
||||
"""Draw non-degenerate values for every parameter and routing buffer.
|
||||
|
||||
These modules allocate with `torch.empty`, and the values `init_weights` would write are
|
||||
themselves degenerate for testing: norm gains default to ones and the sinks, position biases,
|
||||
load-balancing bias and hash table all default to zeros, each of which leaves the path it
|
||||
controls indistinguishable from a no-op. The position bias is drawn wide because it is a
|
||||
softmax logit over a pooling window; at the projections' std the gate would stay near uniform.
|
||||
"""
|
||||
for name, param in module.named_parameters():
|
||||
with torch.no_grad():
|
||||
if name.endswith("scale"):
|
||||
param.uniform_(0.5, 1.5)
|
||||
elif name.endswith("base"):
|
||||
param.normal_(mean=0.0, std=0.5)
|
||||
elif name.endswith("norm.weight"):
|
||||
param.uniform_(0.5, 1.5)
|
||||
elif name.endswith("sinks") or name.endswith("position_bias"):
|
||||
param.normal_(mean=0.0, std=1.0)
|
||||
else:
|
||||
param.normal_(mean=0.0, std=0.02)
|
||||
|
||||
with torch.no_grad():
|
||||
for name, buffer in module.named_buffers():
|
||||
# HF and prime-rl both hang the aux-loss-free load-balancing bias off the router,
|
||||
# under different names. Draw whichever this module carries.
|
||||
if name.endswith("e_score_correction_bias") or name.endswith("selection_bias"):
|
||||
buffer.normal_(mean=0.0, std=0.1)
|
||||
elif name.endswith("tid2eid"):
|
||||
router = module.get_submodule(name.rsplit(".", 1)[0]) if "." in name else module
|
||||
buffer.copy_(_tid2eid(buffer.shape[0], router.num_experts, router.top_k))
|
||||
|
||||
|
||||
def _prime_config(attn_impl: str = "eager") -> DeepseekV4Config:
|
||||
"""The toy config. It defaults to eager because the kernel cannot tile 4 attention heads."""
|
||||
return DeepseekV4Config(**MODEL, _attn_impl=attn_impl)
|
||||
|
||||
|
||||
def get_prime_model(dtype: torch.dtype = torch.bfloat16, attn_impl: str = "eager") -> nn.Module:
|
||||
"""A prime-rl model with non-degenerate weights and the LM head training code wraps it in."""
|
||||
with torch.device("cuda"), default_dtype(dtype):
|
||||
model = DeepseekV4ForCausalLM._from_config(_prime_config(attn_impl))
|
||||
_randomize(model)
|
||||
inject_prime_lm_head(model, chunk_size=None)
|
||||
return model
|
||||
|
||||
|
||||
def prime_attention(layer_idx: int, dtype: torch.dtype = torch.bfloat16, attn_impl: str = "eager") -> nn.Module:
|
||||
"""One attention layer of the same config the whole-model tests use.
|
||||
|
||||
`DeepseekV4Attention` reads no MoE or hyper-connection field, so the layer this builds is
|
||||
bit-identical to one from a config carrying only the attention keys.
|
||||
"""
|
||||
with torch.device("cuda"), default_dtype(dtype):
|
||||
module = DeepseekV4Attention(_prime_config(attn_impl), layer_idx=layer_idx)
|
||||
_randomize(module)
|
||||
return module
|
||||
|
||||
|
||||
def _single_doc(input_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""`position_ids` and `seq_lens` for a row holding one document per batch entry."""
|
||||
batch, seq_len = input_ids.shape
|
||||
position_ids = torch.arange(seq_len, device=input_ids.device).unsqueeze(0).expand(batch, -1)
|
||||
return position_ids, torch.tensor([seq_len], device=input_ids.device)
|
||||
|
||||
|
||||
def _assert_relative(prime: torch.Tensor, reference: torch.Tensor, rtol: float, label: str) -> None:
|
||||
"""Bound the largest absolute deviation by `rtol` times the reference's own scale."""
|
||||
prime, reference = prime.float(), reference.float()
|
||||
deviation = (prime - reference).abs().max()
|
||||
scale = reference.abs().max()
|
||||
assert deviation <= rtol * scale, f"{label}: max deviation {deviation} exceeds {rtol} * scale {scale}"
|
||||
|
||||
|
||||
def _packed_context(doc_lens: tuple[int, ...], dtype: torch.dtype) -> PackedContext:
|
||||
"""The context `DeepseekV4Model` would hand its attention layers for a row of `doc_lens`.
|
||||
|
||||
A single-element `doc_lens` gives back the single-document context, which is what the unpacked
|
||||
half of a packing comparison runs at. `dtype` types the mask and the rotary tables, and has to
|
||||
be the one the caller runs at.
|
||||
"""
|
||||
with torch.device("cuda"), default_dtype(dtype):
|
||||
rotary = DeepseekV4RotaryEmbedding(_prime_config())
|
||||
return PackedContext.build(
|
||||
rotary_emb=rotary,
|
||||
seq_lens=torch.tensor(doc_lens, device="cuda"),
|
||||
dtype=dtype,
|
||||
device=torch.device("cuda"),
|
||||
)
|
||||
|
||||
|
||||
def test_deepseek_v4_hash_layers_route_on_token_ids():
|
||||
"""The bootstrap layers read `input_ids`, so identical hidden states still route apart."""
|
||||
prime_model = get_prime_model()
|
||||
hash_layers = prime_model.model.layers[: MODEL["num_hash_layers"]]
|
||||
assert hash_layers, "config must contain a hash-routed layer"
|
||||
|
||||
counts = []
|
||||
for token_id in (0, 1):
|
||||
input_ids = torch.full((MODEL_BATCH, MODEL_SEQ), token_id, device="cuda", dtype=torch.long)
|
||||
for layer in hash_layers:
|
||||
layer.mlp.tokens_per_expert.zero_()
|
||||
position_ids, seq_lens = _single_doc(input_ids)
|
||||
prime_model(input_ids, position_ids=position_ids, seq_lens=seq_lens)
|
||||
counts.append(torch.stack([layer.mlp.tokens_per_expert.clone() for layer in hash_layers]))
|
||||
|
||||
table = hash_layers[0].mlp.router.tid2eid
|
||||
assert set(table[0].tolist()) != set(table[1].tolist()), "the two table rows must differ for this to bite"
|
||||
assert not torch.equal(counts[0], counts[1]), "a hash layer must route the two token ids to different experts"
|
||||
expected = torch.zeros_like(counts[0][0])
|
||||
expected[table[0]] = MODEL_BATCH * MODEL_SEQ
|
||||
torch.testing.assert_close(counts[0][0], expected)
|
||||
|
||||
|
||||
def test_deepseek_v4_backward():
|
||||
"""Every parameter that can train does, and the Lightning Indexer's still cannot."""
|
||||
prime_config = _prime_config()
|
||||
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
||||
model = DeepseekV4ForCausalLM(prime_config)
|
||||
_randomize(model)
|
||||
inject_prime_lm_head(model)
|
||||
|
||||
input_ids = torch.randint(0, MODEL["vocab_size"], (MODEL_BATCH, MODEL_SEQ), device="cuda")
|
||||
position_ids, seq_lens = _single_doc(input_ids)
|
||||
output = model(input_ids, position_ids=position_ids, seq_lens=seq_lens)
|
||||
output["logits"].sum().backward()
|
||||
|
||||
dead, unexpectedly_alive = [], []
|
||||
for name, param in model.named_parameters():
|
||||
if param.numel() == 0:
|
||||
continue
|
||||
has_grad = param.grad is not None and param.grad.norm().item() > 0
|
||||
# The indexer reaches the loss only through integer top-k indices, so nothing
|
||||
# differentiates back into it. DeepSeek trains it with a separate auxiliary loss
|
||||
# that prime-rl does not implement.
|
||||
if ".indexer." in name:
|
||||
if has_grad:
|
||||
unexpectedly_alive.append(name)
|
||||
elif not has_grad:
|
||||
dead.append(name)
|
||||
|
||||
assert not dead, f"Parameters with zero/no gradients: {dead}"
|
||||
assert not unexpectedly_alive, f"Lightning Indexer parameters received a gradient: {unexpectedly_alive}"
|
||||
|
||||
|
||||
def test_deepseek_v4_weight_conversion_roundtrip():
|
||||
prime_config = _prime_config()
|
||||
model = DeepseekV4ForCausalLM(prime_config).to("cuda")
|
||||
original = {name: tensor.clone() for name, tensor in model.state_dict().items()}
|
||||
|
||||
state_dict = model.state_dict()
|
||||
model.convert_to_hf(state_dict)
|
||||
assert DeepseekV4ForCausalLM.is_hf_state_dict(state_dict)
|
||||
assert not DeepseekV4ForCausalLM.is_prime_state_dict(state_dict)
|
||||
model.convert_to_prime(state_dict)
|
||||
assert DeepseekV4ForCausalLM.is_prime_state_dict(state_dict)
|
||||
|
||||
assert set(state_dict) == set(original)
|
||||
for name, tensor in original.items():
|
||||
assert torch.equal(state_dict[name], tensor), f"Value mismatch for {name}"
|
||||
|
||||
|
||||
def _fill_hash_tables(model: nn.Module) -> dict[int, torch.Tensor]:
|
||||
"""Give every bootstrap layer its own non-degenerate table, and hand them back by layer."""
|
||||
tables = {}
|
||||
for layer_idx, layer in enumerate(model.model.layers):
|
||||
if not layer.mlp.is_hash:
|
||||
continue
|
||||
table = _tid2eid(MODEL["vocab_size"], MODEL["n_routed_experts"], MODEL["num_experts_per_tok"])
|
||||
with torch.no_grad():
|
||||
layer.mlp.router.tid2eid.copy_(table)
|
||||
tables[layer_idx] = table
|
||||
assert len(tables) == MODEL["num_hash_layers"], "config must contain hash-routed layers"
|
||||
return tables
|
||||
|
||||
|
||||
def test_deepseek_v4_hash_table_survives_the_load_path(tmp_path, monkeypatch):
|
||||
"""The frozen table has to reach `mlp.router.tid2eid` from the name a real checkpoint ships.
|
||||
|
||||
It is the one buffer no `init_weights` can reconstruct: an all-zero table is a valid tensor
|
||||
that routes every token to expert 0, so a rename anywhere along the loading path degrades the
|
||||
model in silence rather than raising. `test_deepseek_v4_weight_conversion_roundtrip` only ever
|
||||
roundtrips the zeros the constructor leaves behind, and `VLLM_MAPPED_NAMES` pins the on-disk
|
||||
name without saying where it lands, so this carries real values across the whole path.
|
||||
|
||||
Three things in sequence, because they are three links in one chain. The conversion emits only
|
||||
the bootstrap layers' tables, under the on-disk name; reversing it lands them back on
|
||||
`mlp.router.tid2eid`; and nothing between `dcp_load` and the end of loading resets what the
|
||||
checkpoint supplied. `init_buffers_post_meta` walks every MoE and runs just before the load,
|
||||
so getting it to reset one buffer too many is an easy mistake with no symptom other than every
|
||||
bootstrap token routing to expert 0.
|
||||
"""
|
||||
prime_config = _prime_config()
|
||||
model = DeepseekV4ForCausalLM(prime_config).to("cuda")
|
||||
tables = _fill_hash_tables(model)
|
||||
|
||||
state_dict = model.convert_to_hf(dict(model.state_dict()))
|
||||
|
||||
assert {key for key in state_dict if key.endswith("tid2eid")} == {
|
||||
f"layers.{layer_idx}.ffn.gate.tid2eid" for layer_idx in tables
|
||||
}, "only the bootstrap layers carry a table, under the name the real checkpoint ships"
|
||||
for layer_idx, table in tables.items():
|
||||
assert torch.equal(state_dict[f"layers.{layer_idx}.ffn.gate.tid2eid"], table)
|
||||
|
||||
model.convert_to_prime(state_dict)
|
||||
reloaded = DeepseekV4ForCausalLM(prime_config).to("cuda")
|
||||
reloaded.load_state_dict(state_dict)
|
||||
for layer_idx, table in tables.items():
|
||||
assert torch.equal(reloaded.model.layers[layer_idx].mlp.router.tid2eid, table)
|
||||
|
||||
# And now the loading path itself, on a meta-device model, with the name `load_dcp_from_hf`
|
||||
# asks the checkpoint for raising a `KeyError` in the stub below if the buffer ever moves.
|
||||
with torch.device("meta"):
|
||||
meta_model = DeepseekV4ForCausalLM(prime_config)
|
||||
expected = tables[0]
|
||||
|
||||
def fake_dcp_load(state_dict, storage_reader=None):
|
||||
buffer = state_dict["model.layers.0.mlp.router.tid2eid"]
|
||||
buffer.copy_(expected.to(device=buffer.device))
|
||||
|
||||
monkeypatch.setattr("prime_rl.trainer.model.dcp_load", fake_dcp_load)
|
||||
monkeypatch.setattr("prime_rl.trainer.model.load_state_dict_keys", lambda path: meta_model.state_dict().keys())
|
||||
monkeypatch.setattr("torch.distributed.barrier", lambda *args, **kwargs: None)
|
||||
|
||||
load_dcp_from_hf(meta_model, ModelConfig(name=str(tmp_path)), parallel_dims=MagicMock())
|
||||
|
||||
torch.testing.assert_close(meta_model.model.layers[0].mlp.router.tid2eid, expected)
|
||||
|
||||
|
||||
# What vLLM's DeepSeek V4 loader sees, with the layer and expert indices folded away. Written
|
||||
# out rather than derived: this file has no independent implementation to derive it from, and a
|
||||
# rename on either side of the boundary is exactly what it exists to catch.
|
||||
VLLM_MAPPED_NAMES = {
|
||||
"lm_head.weight",
|
||||
"model.embed_tokens.weight",
|
||||
"model.hc_head_base",
|
||||
"model.hc_head_fn",
|
||||
"model.hc_head_scale",
|
||||
"model.layers.{i}.attn.attn_sink",
|
||||
"model.layers.{i}.attn.compressor.ape",
|
||||
"model.layers.{i}.attn.compressor.norm.weight",
|
||||
"model.layers.{i}.attn.compressor.wgate.weight",
|
||||
"model.layers.{i}.attn.compressor.wkv.weight",
|
||||
"model.layers.{i}.attn.indexer.compressor.ape",
|
||||
"model.layers.{i}.attn.indexer.compressor.norm.weight",
|
||||
"model.layers.{i}.attn.indexer.compressor.wgate.weight",
|
||||
"model.layers.{i}.attn.indexer.compressor.wkv.weight",
|
||||
"model.layers.{i}.attn.indexer.weights_proj.weight",
|
||||
"model.layers.{i}.attn.indexer.wq_b.weight",
|
||||
"model.layers.{i}.attn.kv_norm.weight",
|
||||
"model.layers.{i}.attn.q_norm.weight",
|
||||
"model.layers.{i}.attn.wkv.weight",
|
||||
"model.layers.{i}.attn.wo_a.weight",
|
||||
"model.layers.{i}.attn.wo_b.weight",
|
||||
"model.layers.{i}.attn.wq_a.weight",
|
||||
"model.layers.{i}.attn.wq_b.weight",
|
||||
"model.layers.{i}.attn_norm.weight",
|
||||
"model.layers.{i}.ffn.experts.{i}.w1.weight",
|
||||
"model.layers.{i}.ffn.experts.{i}.w2.weight",
|
||||
"model.layers.{i}.ffn.experts.{i}.w3.weight",
|
||||
"model.layers.{i}.ffn.gate.e_score_correction_bias",
|
||||
"model.layers.{i}.ffn.gate.tid2eid",
|
||||
"model.layers.{i}.ffn.gate.weight",
|
||||
"model.layers.{i}.ffn.shared_experts.down_proj.weight",
|
||||
"model.layers.{i}.ffn.shared_experts.w1.weight",
|
||||
"model.layers.{i}.ffn.shared_experts.w3.weight",
|
||||
"model.layers.{i}.ffn_norm.weight",
|
||||
"model.layers.{i}.hc_attn_base",
|
||||
"model.layers.{i}.hc_attn_fn",
|
||||
"model.layers.{i}.hc_attn_scale",
|
||||
"model.layers.{i}.hc_ffn_base",
|
||||
"model.layers.{i}.hc_ffn_fn",
|
||||
"model.layers.{i}.hc_ffn_scale",
|
||||
"model.norm.weight",
|
||||
}
|
||||
|
||||
|
||||
def test_deepseek_v4_on_disk_keys_map_to_the_names_vllm_expects():
|
||||
"""Pin the names prime-rl's checkpoint arrives under on vLLM's side of the boundary.
|
||||
|
||||
`convert_to_hf` emits the compact DeepSeek-native naming a real checkpoint ships (the
|
||||
conversion chain runs on-disk -> prime, so reversing it lands back on the on-disk names).
|
||||
That is what `utils/weights.py` broadcasts during a run and what `scripts/mini_moe.py`
|
||||
writes, and `_make_deepseek_v4_weights_mapper` is what vLLM puts it through on the way in.
|
||||
|
||||
Asserted against a written-out set because the mapper cannot serve as its own oracle: it
|
||||
returns unrecognized keys unchanged rather than `None`, so "every key maps to something" is
|
||||
true for any input whatsoever, including a misspelling. Pinning the mapped names instead
|
||||
fails on a rename on either side: prime-rl renaming a weight, or vLLM's mapper moving under
|
||||
a bump. It does not prove vLLM's loader has a parameter of that name, which would take
|
||||
instantiating vLLM's model; only a real serving run covers that end to end.
|
||||
|
||||
`_make_deepseek_v4_weights_mapper` is private API in a URL-pinned wheel (`vllm==0.28.0`).
|
||||
Imported inside the test because importing vLLM at module scope would run during collection,
|
||||
including in the CPU CI job that deselects this file.
|
||||
"""
|
||||
from vllm.models.deepseek_v4.nvidia.model import _make_deepseek_v4_weights_mapper
|
||||
|
||||
with torch.device("meta"):
|
||||
model = DeepseekV4ForCausalLM._from_config(_prime_config())
|
||||
on_disk_state_dict = model.convert_to_hf(dict(model.state_dict()))
|
||||
assert on_disk_state_dict, "vacuous probe: the model produced no weights to map"
|
||||
|
||||
# Both expert dtypes, since the mapper is built per dtype and only one of them ships fp4.
|
||||
for expert_dtype in ("fp8", "fp4"):
|
||||
mapper = _make_deepseek_v4_weights_mapper(expert_dtype)
|
||||
mapped = {re.sub(r"\.\d+\.", ".{i}.", mapper._map_name(key)) for key in on_disk_state_dict}
|
||||
assert mapped == VLLM_MAPPED_NAMES, (
|
||||
f"{expert_dtype}: unexpected {sorted(mapped - VLLM_MAPPED_NAMES)}, "
|
||||
f"missing {sorted(VLLM_MAPPED_NAMES - mapped)}"
|
||||
)
|
||||
|
||||
|
||||
def test_deepseek_v4_init_buffers_post_meta_restores_every_rotary():
|
||||
"""Rotary tables are non-persistent and computed eagerly, so meta loading loses them."""
|
||||
prime_config = _prime_config()
|
||||
with torch.device("meta"):
|
||||
model = DeepseekV4ForCausalLM(prime_config)
|
||||
model.to_empty(device="cuda")
|
||||
|
||||
model.init_buffers_post_meta()
|
||||
|
||||
reference = 1.0 / (prime_config.rope_theta ** (torch.arange(0, 16, 2, device="cuda", dtype=torch.float) / 16))
|
||||
torch.testing.assert_close(model.model.rotary_emb.main_inv_freq, reference)
|
||||
compressors = [layer.self_attn.compressor for layer in model.model.layers if layer.self_attn.compressor]
|
||||
assert compressors, "config must contain a compressed attention layer"
|
||||
for compressor in compressors:
|
||||
assert torch.isfinite(compressor.rotary_emb.compress_inv_freq).all()
|
||||
# The compress branch runs a different base, so it must not collapse onto `main`.
|
||||
assert not torch.equal(compressor.rotary_emb.compress_inv_freq, reference)
|
||||
|
||||
|
||||
# DeepSeek ships its own inference code inside the checkpoint, at
|
||||
# https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-0731/tree/main/inference. Its
|
||||
# `model.py:481-485` is what decides which frequencies each layer gets:
|
||||
#
|
||||
# if self.compress_ratio:
|
||||
# original_seq_len, rope_theta = args.original_seq_len, args.compress_rope_theta
|
||||
# else:
|
||||
# # disable YaRN and use base rope_theta in pure sliding-window attention
|
||||
# original_seq_len, rope_theta = 0, args.rope_theta
|
||||
#
|
||||
# `precompute_freqs_cis` (`model.py:206-235`) applies the NTK-by-parts ramp only when
|
||||
# `original_seq_len > 0`, so a pure sliding-window layer gets plain RoPE at `rope_theta` and every
|
||||
# compressed layer gets YaRN at `compress_rope_theta`. vLLM's `build_deepseek_v4_rope` branches the
|
||||
# base but not the scaling, which `monkey_patch_deepseek_v4_per_layer_rope` corrects.
|
||||
#
|
||||
# The real checkpoint's beta range and factor, but a reduced `original_max_position_embeddings`:
|
||||
# the cos/sin cache is `original_max * factor` rows of fp32, which at the checkpoint's 65536 would
|
||||
# allocate 268 MB per rope. 4096 still places the correction range at channels 10 to 23, well
|
||||
# inside the 32 channel pairs, so the ramp is exercised.
|
||||
ROPE_FACTOR = 16
|
||||
ROPE_ORIGINAL_MAX_POSITION = 4096
|
||||
ROPE_BETA_FAST, ROPE_BETA_SLOW = 32, 1
|
||||
ROPE_THETA, COMPRESS_ROPE_THETA = 10000.0, 160000.0
|
||||
ROPE_HEAD_DIM, ROPE_ROTARY_DIM = 512, 64
|
||||
ROPE_MAX_POSITION = ROPE_ORIGINAL_MAX_POSITION * ROPE_FACTOR
|
||||
|
||||
ROPE_SCALING = {
|
||||
"type": "yarn",
|
||||
"factor": ROPE_FACTOR,
|
||||
"beta_fast": ROPE_BETA_FAST,
|
||||
"beta_slow": ROPE_BETA_SLOW,
|
||||
"original_max_position_embeddings": ROPE_ORIGINAL_MAX_POSITION,
|
||||
}
|
||||
|
||||
# The nested `main`/`compress` schema, which HF's own `DeepseekV4Config` and this repo's port both
|
||||
# write and which vLLM's config shim cannot read. A config.json can also carry the flat legacy
|
||||
# `rope_scaling` the real checkpoint ships, or no YaRN parameters at all; the nested scaled form
|
||||
# is asserted here because it is the one the patch has the most normalization to do on.
|
||||
ROPE_NESTED_PLAIN = {"rope_type": "default", "partial_rotary_factor": 0.125}
|
||||
ROPE_PARAMETERS = {
|
||||
"main": dict(ROPE_NESTED_PLAIN),
|
||||
"compress": {**ROPE_SCALING, "partial_rotary_factor": 0.125},
|
||||
}
|
||||
|
||||
|
||||
def _reference_rope_freqs(original_seq_len: int, base: float) -> torch.Tensor:
|
||||
"""Verbatim from the checkpoint's `inference/model.py:206-231`, minus the unused `t` outer.
|
||||
|
||||
Only the frequency vector is kept; the reference then does `torch.polar(ones, outer(t, freqs))`,
|
||||
whose magnitude is 1, i.e. no mscale on cos/sin.
|
||||
"""
|
||||
|
||||
def find_correction_dim(num_rotations, dim, base, max_seq_len):
|
||||
return dim * math.log(max_seq_len / (num_rotations * 2 * math.pi)) / (2 * math.log(base))
|
||||
|
||||
def find_correction_range(low_rot, high_rot, dim, base, max_seq_len):
|
||||
low = math.floor(find_correction_dim(low_rot, dim, base, max_seq_len))
|
||||
high = math.ceil(find_correction_dim(high_rot, dim, base, max_seq_len))
|
||||
return max(low, 0), min(high, dim - 1)
|
||||
|
||||
def linear_ramp_factor(min, max, dim):
|
||||
if min == max:
|
||||
max += 0.001
|
||||
linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
|
||||
return torch.clamp(linear_func, 0, 1)
|
||||
|
||||
dim = ROPE_ROTARY_DIM
|
||||
freqs = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
|
||||
if original_seq_len > 0:
|
||||
low, high = find_correction_range(ROPE_BETA_FAST, ROPE_BETA_SLOW, dim, base, original_seq_len)
|
||||
smooth = 1 - linear_ramp_factor(low, high, dim // 2)
|
||||
freqs = freqs / ROPE_FACTOR * (1 - smooth) + freqs * smooth
|
||||
return freqs
|
||||
|
||||
|
||||
def _vllm_rope_freqs(rotary_emb) -> torch.Tensor:
|
||||
"""Recover inv_freq from row 1 of vLLM's `[position, rotary_dim]` cos-then-sin cache."""
|
||||
cos, sin = rotary_emb.cos_sin_cache[1].chunk(2)
|
||||
return torch.atan2(sin, cos)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def vllm_rope_builder():
|
||||
"""`build_deepseek_v4_rope`, patched, under the live vLLM config its `CustomOp` base asserts on.
|
||||
|
||||
The builder is resolved off the module at call time rather than bound at import, because the
|
||||
patch rebinds that attribute. The config goes through vLLM's own `patch_rope_parameters`, the
|
||||
same normalization the engine runs: it renames the legacy `type` key and, for the nested
|
||||
schema, injects a top-level `rope_type="default"` beside the sub-dicts.
|
||||
"""
|
||||
from vllm.config import VllmConfig, set_current_vllm_config
|
||||
from vllm.model_executor.layers import rotary_embedding
|
||||
from vllm.models.deepseek_v4.common import rope as dsv4_rope
|
||||
from vllm.transformers_utils.config import patch_rope_parameters
|
||||
from vllm.transformers_utils.configs.deepseek_v4 import DeepseekV4Config as VllmDeepseekV4Config
|
||||
from vllm.utils.torch_utils import set_default_torch_dtype
|
||||
|
||||
from prime_rl.inference.patches import monkey_patch_deepseek_v4_per_layer_rope
|
||||
|
||||
monkey_patch_deepseek_v4_per_layer_rope()
|
||||
rotary_embedding._ROPE_DICT.clear()
|
||||
|
||||
def build(compress_ratio: int):
|
||||
config = VllmDeepseekV4Config(
|
||||
rope_theta=ROPE_THETA,
|
||||
compress_rope_theta=COMPRESS_ROPE_THETA,
|
||||
max_position_embeddings=ROPE_MAX_POSITION,
|
||||
rope_parameters={key: dict(value) for key, value in ROPE_PARAMETERS.items()},
|
||||
)
|
||||
patch_rope_parameters(config)
|
||||
# Model init runs under the model dtype (`vllm/model_executor/model_loader/base_loader.py`),
|
||||
# which is what would leave an unscaled config with a bf16 cache.
|
||||
with set_default_torch_dtype(torch.bfloat16), set_current_vllm_config(VllmConfig()):
|
||||
return dsv4_rope.build_deepseek_v4_rope(
|
||||
config,
|
||||
head_dim=ROPE_HEAD_DIM,
|
||||
rope_head_dim=ROPE_ROTARY_DIM,
|
||||
max_position_embeddings=ROPE_MAX_POSITION,
|
||||
compress_ratio=compress_ratio,
|
||||
)
|
||||
|
||||
return build
|
||||
|
||||
|
||||
def test_deepseek_v4_vllm_rope_matches_the_reference(vllm_rope_builder):
|
||||
"""Sliding-window layers take plain RoPE at `rope_theta`, compressed layers YaRN at theirs.
|
||||
|
||||
Both are asserted together: neutralizing YaRN on the sliding layers must not disturb the
|
||||
compressed layers, which vLLM already gets right.
|
||||
"""
|
||||
from vllm.model_executor.layers import rotary_embedding
|
||||
|
||||
sliding = vllm_rope_builder(compress_ratio=1)
|
||||
compressed = vllm_rope_builder(compress_ratio=4)
|
||||
|
||||
# `vllm/models/deepseek_v4/common/ops/fused_inv_rope_fp8_quant.py` asserts fp32.
|
||||
assert sliding.cos_sin_cache.dtype is torch.float32
|
||||
assert compressed.cos_sin_cache.dtype is torch.float32
|
||||
|
||||
torch.testing.assert_close(_vllm_rope_freqs(sliding), _reference_rope_freqs(0, ROPE_THETA), atol=1e-6, rtol=0)
|
||||
torch.testing.assert_close(
|
||||
_vllm_rope_freqs(compressed),
|
||||
_reference_rope_freqs(ROPE_ORIGINAL_MAX_POSITION, COMPRESS_ROPE_THETA),
|
||||
atol=1e-6,
|
||||
rtol=0,
|
||||
)
|
||||
|
||||
# One rope per distinct `rope_theta`, and no more: `get_rope`'s cache key has to stay
|
||||
# hashable. An unhashable key silently defeats memoization, which costs one 256 MB fp32
|
||||
# cos/sin cache per attention layer on the real checkpoint instead of two in total.
|
||||
assert len(rotary_embedding._ROPE_DICT) == 2
|
||||
assert vllm_rope_builder(compress_ratio=1) is sliding
|
||||
|
||||
|
||||
# Everything below exercises a *packed* batch: rollouts concatenated into one row, `position_ids`
|
||||
# restarting per document, per-document lengths handed over as `seq_lens`, exactly as
|
||||
# `trainer/batch.py` builds them. A packed row must equal running each document alone, because
|
||||
# that is how vLLM serves them.
|
||||
|
||||
# Neither length is a multiple of a compress rate, so both compressors have to drop a trailing
|
||||
# partial window instead of pooling across the boundary.
|
||||
DOC_LENS = (14, 18)
|
||||
|
||||
# The bf16 expert floor, which four hyper-connected layers amplify into every gradient. A document
|
||||
# reading its neighbour moves the gradients far past that floor.
|
||||
MODEL_GRAD_RTOL = 1e-1
|
||||
|
||||
# The per-mechanism cases run in float32. `kv_proj` sees a different number of rows packed than
|
||||
# alone and cuBLAS may tile the two differently, so they never match bit for bit, and in bfloat16
|
||||
# that floor would swallow the cross-document leakage these tests exist to catch.
|
||||
PACKED_RTOL, PACKED_ATOL = 1e-5, 1e-6
|
||||
# Gradients are bounded against the tensor's own scale instead: they are sums over the whole row,
|
||||
# so their near-zero entries are the ones whose summands cancelled, and an element-wise relative
|
||||
# bound would read out that cancellation noise rather than a document leak.
|
||||
PACKED_GRAD_RTOL = 1e-5
|
||||
|
||||
# One row folding together every length regime the per-document layout has to get right: 3
|
||||
# compresses to nothing, 8 is a whole number of windows at both rates, and 13 ends mid-window at
|
||||
# both. At both rates the per-document entry count lands below the row-global one, so neither
|
||||
# case is vacuous.
|
||||
MIXED_DOCS = (3, 8, 13)
|
||||
|
||||
# The boundary falls inside a window of both rates, so both drop tokens at it.
|
||||
MID_WINDOW_DOCS = (7, 9)
|
||||
# Whole windows everywhere, so only the numbering, and with it the RoPE position, moves.
|
||||
EXACT_MULTIPLE_DOCS = (8, 8)
|
||||
|
||||
|
||||
def _packed_inputs(doc_lens: tuple[int, ...]) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""One packed row: token ids, `position_ids` restarting per document, and flat `seq_lens`."""
|
||||
total = sum(doc_lens)
|
||||
input_ids = torch.randint(0, MODEL["vocab_size"], (1, total), device="cuda")
|
||||
position_ids = torch.cat([torch.arange(length, device="cuda") for length in doc_lens]).unsqueeze(0)
|
||||
return input_ids, position_ids, torch.tensor(doc_lens, device="cuda")
|
||||
|
||||
|
||||
def _doc_ids(doc_lens: tuple[int, ...]) -> torch.Tensor:
|
||||
return torch.cat([torch.full((length,), index, device="cuda") for index, length in enumerate(doc_lens)])
|
||||
|
||||
|
||||
def _doc_slice(doc_lens: tuple[int, ...], index: int) -> slice:
|
||||
start = sum(doc_lens[:index])
|
||||
return slice(start, start + doc_lens[index])
|
||||
|
||||
|
||||
def _entry_counts(doc_lens: tuple[int, ...], compress_rate: int) -> list[int]:
|
||||
return [length // compress_rate for length in doc_lens]
|
||||
|
||||
|
||||
def _fp32_hidden_states(seq_len: int) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Two leaves carrying identical values, one for the packed run and one for the lone runs."""
|
||||
with torch.device("cuda"):
|
||||
hidden = torch.randn(MODULE_BATCH, seq_len, MODEL["hidden_size"])
|
||||
return hidden.clone().requires_grad_(True), hidden.clone().requires_grad_(True)
|
||||
|
||||
|
||||
def _take_grads(module: nn.Module) -> dict[str, torch.Tensor | None]:
|
||||
"""Detach whatever gradients have accumulated and clear them for the next run."""
|
||||
grads = {name: None if param.grad is None else param.grad.clone() for name, param in module.named_parameters()}
|
||||
module.zero_grad(set_to_none=True)
|
||||
return grads
|
||||
|
||||
|
||||
def _compare_accumulated_grads(
|
||||
module: nn.Module, expected: dict[str, torch.Tensor | None], rtol: float = PACKED_GRAD_RTOL
|
||||
) -> None:
|
||||
"""Compare the gradients now on `module` against a snapshot taken from an earlier backward.
|
||||
|
||||
Allows for a parameter that legitimately receives nothing: the Lightning Indexer reaches the
|
||||
loss only through integer top-k indices, so neither run may hand its parameters a gradient.
|
||||
"""
|
||||
for name, param in module.named_parameters():
|
||||
if expected[name] is None:
|
||||
assert param.grad is None, f"{name} received a gradient per document but not packed"
|
||||
continue
|
||||
assert param.grad is not None, f"{name} received no gradient per document"
|
||||
_assert_relative(param.grad, expected[name], rtol, name)
|
||||
|
||||
|
||||
def test_packed_sliding_window_mask_respects_documents(_torch_rms_norm, monkeypatch): # noqa: F811
|
||||
"""The local window stops at document boundaries, on every layer.
|
||||
|
||||
Guards the `cu_seqlens` term in `build_sliding_window_mask`: without it the distances come
|
||||
from `torch.arange(seq_len)` over the whole packed row and a query reaches the previous
|
||||
`sliding_window` packed positions whatever document they belong to, which at the production
|
||||
`sliding_window = 128` against 77-token rollouts spans roughly two neighbours on all 43 layers.
|
||||
|
||||
Captured from the mask the model actually applies rather than by calling the builder, so it
|
||||
keeps holding if the masking ever moves.
|
||||
"""
|
||||
recorded = []
|
||||
real_attention = dsv4_attention.eager_attention_with_sinks
|
||||
|
||||
def record(query, key, value, sinks, attention_mask, **kwargs):
|
||||
recorded.append(attention_mask)
|
||||
return real_attention(query, key, value, sinks, attention_mask, **kwargs)
|
||||
|
||||
monkeypatch.setattr(dsv4_attention, "eager_attention_with_sinks", record)
|
||||
|
||||
# The dense mask is an eager-path artifact; the count below is one call per layer.
|
||||
prime_model = get_prime_model(torch.float32)
|
||||
input_ids, position_ids, seq_lens = _packed_inputs(DOC_LENS)
|
||||
prime_model(input_ids, position_ids=position_ids, seq_lens=seq_lens)
|
||||
|
||||
assert len(recorded) == MODEL["num_hidden_layers"]
|
||||
total = sum(DOC_LENS)
|
||||
doc_ids = _doc_ids(DOC_LENS)
|
||||
positions = position_ids[0]
|
||||
distance = positions[:, None] - positions[None, :]
|
||||
expected = (doc_ids[:, None] == doc_ids[None, :]) & (distance >= 0) & (distance < MODEL["sliding_window"])
|
||||
for layer_idx, mask in enumerate(recorded):
|
||||
# Compressed layers append their own entries as extra columns; those are covered
|
||||
# separately, so only the local window is compared here.
|
||||
local = mask[0, 0, :, :total] == 0
|
||||
assert torch.equal(local, expected), f"layer {layer_idx}: the local window crosses a document boundary"
|
||||
|
||||
|
||||
def test_model_packed_matches_unpacked(_torch_rms_norm): # noqa: F811
|
||||
"""The invariant that makes the trainer agree with vLLM, which serves each rollout alone.
|
||||
|
||||
End to end over every pathway at once: the local sliding window, the CSA compressor with its
|
||||
indexer, and HCA. Each document's logits have to come out the same whether it is packed beside
|
||||
another rollout or served on its own. Gradients are compared too, since a leak that barely
|
||||
moves the logits can still move the update.
|
||||
|
||||
This is the whole-model test, and it stands in for the HF-parity test the other models in this
|
||||
directory get: with no reference implementation available, packing is the only oracle that
|
||||
covers the assembled stack.
|
||||
"""
|
||||
prime_model = get_prime_model(torch.float32)
|
||||
input_ids, position_ids, seq_lens = _packed_inputs(DOC_LENS)
|
||||
|
||||
packed = prime_model(input_ids, position_ids=position_ids, seq_lens=seq_lens)["logits"]
|
||||
# One random weight drawn over the packed logits and sliced per document, so the packed loss
|
||||
# and the summed per-document losses are the same function of the same numbers.
|
||||
with torch.device("cuda"):
|
||||
weight = torch.randn_like(packed)
|
||||
(packed * weight).sum().backward()
|
||||
packed_grads = _take_grads(prime_model)
|
||||
|
||||
for index, length in enumerate(DOC_LENS):
|
||||
span = _doc_slice(DOC_LENS, index)
|
||||
alone = prime_model(
|
||||
input_ids[:, span],
|
||||
position_ids=torch.arange(length, device="cuda").unsqueeze(0),
|
||||
seq_lens=torch.tensor([length], device="cuda"),
|
||||
)["logits"]
|
||||
# `GroupedExperts` runs the routed experts through `torch._grouped_mm` in bfloat16 whatever
|
||||
# dtype the model runs in, and packing changes which tokens share an expert matmul, so the two
|
||||
# runs agree only to the bf16 floor. A document actually reading its neighbour moves the logits
|
||||
# by a fraction of their own scale, orders of magnitude above this.
|
||||
_assert_relative(packed[:, span], alone, 1e-2, f"document {index}")
|
||||
(alone * weight[:, span]).sum().backward()
|
||||
|
||||
_compare_accumulated_grads(prime_model, packed_grads, rtol=MODEL_GRAD_RTOL)
|
||||
|
||||
|
||||
def _assert_layout_is_consistent(packed: PackedContext, doc_lens: tuple[int, ...], compress_rate: int) -> None:
|
||||
"""Pin the layout against the per-document construction it claims to describe.
|
||||
|
||||
Document `d` of length `L_d` gets `L_d // compress_rate` entries; entry `j` covers that
|
||||
document's local tokens `j * compress_rate` through `(j + 1) * compress_rate - 1` and is
|
||||
rotated at local position `j * compress_rate`. The entries are ordered document by document,
|
||||
which is what lets every comparison below slice them per document.
|
||||
"""
|
||||
counts = _entry_counts(doc_lens, compress_rate)
|
||||
starts = [sum(doc_lens[:index]) for index in range(len(doc_lens))]
|
||||
expected_doc = [index for index, count in enumerate(counts) for _ in range(count)]
|
||||
expected_local = [entry for count in counts for entry in range(count)]
|
||||
expected_src = [
|
||||
[starts[doc] + local * compress_rate + offset for offset in range(compress_rate)]
|
||||
for doc, local in zip(expected_doc, expected_local)
|
||||
]
|
||||
|
||||
def as_tensor(values: list, dtype: torch.dtype = torch.long) -> torch.Tensor:
|
||||
return torch.tensor(values, dtype=dtype, device="cuda")
|
||||
|
||||
layout = packed.compression_layouts[compress_rate]
|
||||
assert torch.equal(layout.entry_doc_idx, as_tensor(expected_doc)), "entries are not ordered document by document"
|
||||
assert torch.equal(layout.entry_local_idx, as_tensor(expected_local)), "entries are not numbered within a document"
|
||||
assert torch.equal(layout.entry_tok_idx, as_tensor(expected_src).reshape(-1, compress_rate)), (
|
||||
"an entry pools source tokens outside its own document's window"
|
||||
)
|
||||
assert torch.equal(packed.tok_doc_idx, _doc_ids(doc_lens)), "tok_doc_idx must follow the document lengths"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("layer_idx", "compress_rate", "expected_counts"),
|
||||
[(CSA_LAYER, COMPRESS_RATE, [0, 2, 3]), (HCA_LAYER, HCA_COMPRESS_RATE, [0, 1, 1])],
|
||||
ids=["csa", "hca"],
|
||||
)
|
||||
def test_compressor_packed_matches_per_document(layer_idx, compress_rate, expected_counts):
|
||||
"""Compressing a packed row must equal compressing each of its documents on its own.
|
||||
|
||||
Forward and backward both: entry `n` of the packed run must pool the same source tokens, at
|
||||
the same compress-RoPE position, as the corresponding entry of its own document's run, and
|
||||
the gradient the packed run sends into the weights must equal the one the per-document runs
|
||||
accumulate. One random weight tensor is drawn over the packed entries and sliced per
|
||||
document, so the packed loss and the summed per-document losses are literally the same
|
||||
function of the same numbers.
|
||||
|
||||
`MIXED_DOCS` folds every length regime that matters into one row; see its definition.
|
||||
"""
|
||||
module = prime_attention(layer_idx, dtype=torch.float32)
|
||||
compressor = module.compressor
|
||||
doc_lens = MIXED_DOCS
|
||||
packed = _packed_context(doc_lens, torch.float32)
|
||||
|
||||
counts = _entry_counts(doc_lens, compress_rate)
|
||||
assert counts == expected_counts
|
||||
assert (
|
||||
packed.compression_layouts[compress_rate].entry_tok_idx.shape[0]
|
||||
== sum(counts)
|
||||
< (sum(doc_lens) // compress_rate)
|
||||
), "a row-global compression would emit more entries than this, so the probe is not vacuous"
|
||||
|
||||
_assert_layout_is_consistent(packed, doc_lens, compress_rate)
|
||||
packed_input, alone_input = _fp32_hidden_states(sum(doc_lens))
|
||||
|
||||
packed_entries = compressor.compress(packed_input, packed)
|
||||
assert packed_entries.shape == (MODULE_BATCH, sum(counts), compressor.head_dim)
|
||||
|
||||
with torch.device("cuda"):
|
||||
weight = torch.randn_like(packed_entries)
|
||||
(packed_entries * weight).sum().backward()
|
||||
packed_grads = _take_grads(compressor)
|
||||
|
||||
for index, count in enumerate(counts):
|
||||
# The entry axis is laid out document by document exactly as the token axis is.
|
||||
entries = _doc_slice(tuple(counts), index)
|
||||
alone = compressor.compress(
|
||||
alone_input[:, _doc_slice(doc_lens, index)], _packed_context((doc_lens[index],), torch.float32)
|
||||
)
|
||||
assert alone.shape == (MODULE_BATCH, count, compressor.head_dim), (
|
||||
f"document {index} compressed to the wrong count"
|
||||
)
|
||||
torch.testing.assert_close(
|
||||
packed_entries[:, entries],
|
||||
alone,
|
||||
rtol=PACKED_RTOL,
|
||||
atol=PACKED_ATOL,
|
||||
msg=lambda m, i=index: f"document {i} compresses differently packed than alone: {m}",
|
||||
)
|
||||
(alone * weight[:, entries]).sum().backward()
|
||||
|
||||
_compare_accumulated_grads(compressor, packed_grads)
|
||||
torch.testing.assert_close(alone_input.grad, packed_input.grad, rtol=PACKED_RTOL, atol=PACKED_ATOL)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("layer_idx", "doc_lens"),
|
||||
[
|
||||
(CSA_LAYER, MID_WINDOW_DOCS),
|
||||
(HCA_LAYER, EXACT_MULTIPLE_DOCS),
|
||||
(SLIDING_LAYER, MID_WINDOW_DOCS),
|
||||
],
|
||||
ids=["csa", "hca", "sliding"],
|
||||
)
|
||||
def test_attention_packed_matches_unpacked(layer_idx, doc_lens, _torch_rms_norm): # noqa: F811
|
||||
"""The same invariant, one whole attention layer at a time rather than one compressor.
|
||||
|
||||
Everything the layer reads past its local window comes through the compressor, so a leaking
|
||||
entry, a misnumbered pick and a misrotated entry all show up here at once. The HCA case has no
|
||||
indexer to narrow the damage, and at rate 8 both documents own an entry, so the second one's
|
||||
has to be rotated at its own position rather than at its packed one.
|
||||
|
||||
Sharper than `test_deepseek_v4`, which asserts the same property through the logits at a bf16
|
||||
floor: this runs in float32 and compares the layer's own output, forward and backward.
|
||||
|
||||
A sliding layer has no compressor and so no entry selection at all; it reads nothing but its
|
||||
own clipped window, which makes it the case where the boundary handling stands alone.
|
||||
"""
|
||||
# The kernel's own packing invariant is asserted at the Flash shapes in
|
||||
# `test_deepseek_v4_kernels.py`.
|
||||
module = prime_attention(layer_idx, dtype=torch.float32)
|
||||
packed_input, alone_input = _fp32_hidden_states(sum(doc_lens))
|
||||
packed = _packed_context(doc_lens, torch.float32)
|
||||
|
||||
if module.compressor is None:
|
||||
# The second document opens inside a window, so an unclipped one would reach back into
|
||||
# the first. Without that the comparison below would hold under no clipping at all.
|
||||
readable = packed.window_indices[doc_lens[0]] >= 0
|
||||
assert readable.sum() < module.config.sliding_window, (
|
||||
"vacuous probe: the second document's first query is not window-clipped at the boundary"
|
||||
)
|
||||
else:
|
||||
q_residual = module.q_a_norm(module.q_a_proj(packed_input.detach()))
|
||||
_, picks = module.compressor(packed_input.detach(), q_residual, packed)
|
||||
# (batch, seq_len, n_picks), with `IGNORE_SLOT` (-1) where the query had no entry left to pick.
|
||||
assert (picks[:, _doc_slice(doc_lens, 1)] >= 0).any(), (
|
||||
"vacuous probe: no query of the second document picks a compressed entry"
|
||||
)
|
||||
|
||||
packed_output, _ = module(packed_input, packed=packed)
|
||||
with torch.device("cuda"):
|
||||
weight = torch.randn_like(packed_output)
|
||||
(packed_output * weight).sum().backward()
|
||||
packed_grads = _take_grads(module)
|
||||
|
||||
for index, length in enumerate(doc_lens):
|
||||
span = _doc_slice(doc_lens, index)
|
||||
alone_output, _ = module(alone_input[:, span], packed=_packed_context((length,), torch.float32))
|
||||
torch.testing.assert_close(
|
||||
packed_output[:, span],
|
||||
alone_output,
|
||||
rtol=PACKED_RTOL,
|
||||
atol=PACKED_ATOL,
|
||||
msg=lambda m, i=index: f"document {i} attends differently packed than alone: {m}",
|
||||
)
|
||||
(alone_output * weight[:, span]).sum().backward()
|
||||
|
||||
_compare_accumulated_grads(module, packed_grads)
|
||||
torch.testing.assert_close(alone_input.grad, packed_input.grad, rtol=PACKED_RTOL, atol=PACKED_ATOL)
|
||||
@@ -0,0 +1,55 @@
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.models.deepseek_v4 import DeepseekV4Config
|
||||
from prime_rl.trainer.models.deepseek_v4.dequantize import dequantize_weight
|
||||
|
||||
|
||||
def test_deepseek_v4_config_translates_legacy_compress_ratios():
|
||||
"""Real checkpoints ship the V3-flavoured legacy `compress_ratios`/`num_hash_layers` schema
|
||||
instead of `layer_types`/`mlp_layer_types`, which is what prime-rl's model code reads, so the
|
||||
config has to translate between them. Loading the real checkpoint without this built the
|
||||
wrong per-layer attention schedule outright.
|
||||
"""
|
||||
config = DeepseekV4Config(num_hidden_layers=6, compress_ratios=[0, 0, 4, 128, 4, 128], num_hash_layers=2)
|
||||
|
||||
assert config.layer_types == [
|
||||
"sliding_attention",
|
||||
"sliding_attention",
|
||||
"compressed_sparse_attention",
|
||||
"heavily_compressed_attention",
|
||||
"compressed_sparse_attention",
|
||||
"heavily_compressed_attention",
|
||||
]
|
||||
assert config.mlp_layer_types == ["hash_moe", "hash_moe", "moe", "moe", "moe", "moe"]
|
||||
|
||||
|
||||
def test_dequantize_weight_dense_fp8():
|
||||
"""Dense fp8 case: one `float8_e8m0fnu` scale block covers the whole weight."""
|
||||
weight = torch.tensor([[1.0, 2.0], [-1.0, 0.5]], dtype=torch.float32).to(torch.float8_e4m3fn)
|
||||
scale = torch.tensor([[128]], dtype=torch.uint8).view(torch.float8_e8m0fnu) # byte 128 -> 2**(128-127) = 2.0
|
||||
|
||||
result = dequantize_weight(weight, scale)
|
||||
|
||||
assert result.dtype == torch.bfloat16
|
||||
assert torch.equal(result, torch.tensor([[2.0, 4.0], [-2.0, 1.0]], dtype=torch.bfloat16))
|
||||
|
||||
|
||||
def test_dequantize_weight_packed_mxfp4():
|
||||
"""Packed MXFP4 expert case: unpack two e2m1 nibbles per byte, then a per-block scale."""
|
||||
# Nibble layout per byte is (high << 4) | low; e2m1 LUT indices used here:
|
||||
# 2->1.0, 4->2.0, 10->-1.0, 6->4.0, 0->0.0, 7->6.0, 9->-0.5, 3->1.5.
|
||||
packed = torch.tensor(
|
||||
[
|
||||
[(4 << 4) | 2, (6 << 4) | 10], # row 0 -> unpacks to [1.0, 2.0, -1.0, 4.0]
|
||||
[(7 << 4) | 0, (3 << 4) | 9], # row 1 -> unpacks to [0.0, 6.0, -0.5, 1.5]
|
||||
],
|
||||
dtype=torch.int8,
|
||||
)
|
||||
# [2, 2] scale grid over the unpacked [2, 4] weight -> block_rows=1, block_cols=2.
|
||||
scale = torch.tensor([[127, 128], [129, 126]], dtype=torch.uint8).view(torch.float8_e8m0fnu)
|
||||
|
||||
result = dequantize_weight(packed, scale)
|
||||
|
||||
expected = torch.tensor([[1.0, 2.0, -2.0, 8.0], [0.0, 24.0, -0.25, 0.75]], dtype=torch.bfloat16)
|
||||
assert result.dtype == torch.bfloat16
|
||||
assert torch.equal(result, expected)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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"])
|
||||
@@ -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
|
||||
@@ -17,25 +17,27 @@ exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for
|
||||
exclude-newer-span = "P7D"
|
||||
|
||||
[options.exclude-newer-package]
|
||||
vllm = false
|
||||
verifiers = false
|
||||
harbor = "2026-08-11T00:00:00Z"
|
||||
prime-pydantic-config = false
|
||||
vllm-router = false
|
||||
deep-ep = false
|
||||
deep-gemm = false
|
||||
dion = false
|
||||
fastokens = false
|
||||
flash-attn-3 = false
|
||||
prime-tunnel = false
|
||||
deep-gemm = false
|
||||
prime-evals = false
|
||||
torchao = false
|
||||
tokenspeed-mla = false
|
||||
harbor = "2026-08-11T00:00:00Z"
|
||||
nixl-cu13 = false
|
||||
deep-ep = false
|
||||
prime-sandboxes = false
|
||||
renderers = false
|
||||
prime-kernels = false
|
||||
prime = false
|
||||
prime-evals = false
|
||||
prime-kernels = false
|
||||
prime-pydantic-config = false
|
||||
prime-runs = false
|
||||
prime-sandboxes = false
|
||||
prime-traces = false
|
||||
prime-tunnel = false
|
||||
renderers = false
|
||||
tokenspeed-mla = false
|
||||
torchao = false
|
||||
verifiers = false
|
||||
vllm = false
|
||||
vllm-router = false
|
||||
|
||||
[manifest]
|
||||
members = [
|
||||
@@ -448,6 +450,19 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/df/73/b6e24bd22e6720ca8ee9a85a0c4a2971af8497d8f3193fa05390cbd46e09/backoff-2.2.1-py3-none-any.whl", hash = "sha256:63579f9a0628e06278f7e47b7d7d5b6ce20dc65c5e96a6f3ca99a6adca0396e8", size = 15148, upload-time = "2022-10-05T19:19:30.546Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "backports-zstd"
|
||||
version = "1.7.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/75/f0/9ba1b05811aa5f5434f69768253129460a5744e1814f359efba39a01ce20/backports_zstd-1.7.0.tar.gz", hash = "sha256:1a967189c1822b6e85a2e550fdfc88a3272c17633ea0a4732dac5911a8034f2b", size = 1003722, upload-time = "2026-08-15T17:26:43.96Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/6d/24/5556959c7d03bfee5ff14d7f07dd9bf8de737c69f81d823a32784ab39c34/backports_zstd-1.7.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:bab192b934fdf5a03df4752556d9c8af2d058163fdfbafd4a253cdfe25449a6f", size = 367666, upload-time = "2026-08-15T17:25:39.233Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/40/4b/820acbc2c1d1d945aedca0c0d22546a948630ffb186df523098fbd669a95/backports_zstd-1.7.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1c55e55e1e9dee312bc5e186386e6aa5207482a6d2242bd7c14709ded254f87f", size = 478240, upload-time = "2026-08-15T17:25:41.806Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1e/40/121917bd2671bc3f1507c25503c0554f0b52483edcca4e6210e6d22228df/backports_zstd-1.7.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:470895d0bcddc850766e593d1b26764fb138c2feed149f515a2627ef9587d54c", size = 496195, upload-time = "2026-08-15T17:25:45.503Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7a/a4/372c3dd3017c3f93cda0acbc282f8073b70efdc1b56d1fdeebe023660725/backports_zstd-1.7.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:132ba81fad59d44958b7d10da31545e7128c469cfbc2e268d0eaab96daa64175", size = 484276, upload-time = "2026-08-15T17:25:48.129Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6a/d0/e36c18c87a74421954502d123ff7027e0a63a7624dffa99ec0f7474deff9/backports_zstd-1.7.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:468b636ed365627b364c94be1c35a52858e13b5bc1fa3f068bbc71b1af65f3d7", size = 500735, upload-time = "2026-08-15T17:25:56.064Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bashlex"
|
||||
version = "0.18"
|
||||
@@ -1420,7 +1435,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" } },
|
||||
@@ -4950,10 +4965,12 @@ dependencies = [
|
||||
{ name = "prime" },
|
||||
{ name = "prime-pydantic-config" },
|
||||
{ name = "prime-rl-configs" },
|
||||
{ name = "prime-runs", extra = ["train"] },
|
||||
{ name = "psutil" },
|
||||
{ name = "pyarrow" },
|
||||
{ name = "pybase64" },
|
||||
{ name = "pyzmq" },
|
||||
{ name = "pyzstd" },
|
||||
{ name = "renderers", extra = ["multimodal"] },
|
||||
{ name = "rich" },
|
||||
{ name = "setproctitle" },
|
||||
@@ -5078,7 +5095,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" },
|
||||
@@ -5112,10 +5129,12 @@ requires-dist = [
|
||||
{ name = "prime-rl", extras = ["gpu"], marker = "extra == 'all'" },
|
||||
{ name = "prime-rl", extras = ["quack"], marker = "extra == 'all'" },
|
||||
{ name = "prime-rl-configs", editable = "packages/prime-rl-configs" },
|
||||
{ name = "prime-runs", extras = ["train"], specifier = ">=0.1.1" },
|
||||
{ name = "psutil", specifier = ">=7.0.0" },
|
||||
{ name = "pyarrow", specifier = ">=21.0.0" },
|
||||
{ name = "pybase64", specifier = ">=1.4.2" },
|
||||
{ name = "pyzmq", specifier = ">=27.1.0" },
|
||||
{ name = "pyzstd", specifier = ">=0.16.2" },
|
||||
{ name = "quack-kernels", marker = "sys_platform == 'linux' and extra == 'quack'", specifier = ">=0.4.1" },
|
||||
{ name = "renderers", extras = ["multimodal"], editable = "deps/renderers" },
|
||||
{ name = "rich", specifier = ">=14.0.0" },
|
||||
@@ -5181,6 +5200,24 @@ requires-dist = [
|
||||
{ name = "verifiers", specifier = ">=0.3.0" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prime-runs"
|
||||
version = "0.1.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "httpx" },
|
||||
{ name = "prime-traces" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/85/db/3d5a9362f0d373d10145eaee3ac255cf227bf4164b36d04119b18e226607/prime_runs-0.1.1.tar.gz", hash = "sha256:0be97dcc95b3f1648ca25475efa45a5892fb12a775bf1f61728baec73a0088bb", size = 61110, upload-time = "2026-09-04T17:01:33.379Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/84/52/3fa41ac5e3c8bfa8eb33520f86634ae56474228f85c59b16aa04875efd7d/prime_runs-0.1.1-py3-none-any.whl", hash = "sha256:d512753ff84159a1234d1ea93091857f0a59fba12ef7ab2f69bfb579deb5ce75", size = 43006, upload-time = "2026-09-04T17:01:31.821Z" },
|
||||
]
|
||||
|
||||
[package.optional-dependencies]
|
||||
train = [
|
||||
{ name = "pyarrow" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prime-sandboxes"
|
||||
version = "0.2.39"
|
||||
@@ -5200,6 +5237,19 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/db/a5/8a2a1aefecfc58ca926d6b21e8302a127884bf2a45952ed390b5f702eeda/prime_sandboxes-0.2.39-py3-none-any.whl", hash = "sha256:3ea355158473c1697f9ef6ec2a07f3189e9a2555c80d1c88e1f7e22979772e0a", size = 58161, upload-time = "2026-08-19T23:09:26.69Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prime-traces"
|
||||
version = "0.0.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "httpx" },
|
||||
{ name = "pydantic" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/8c/77/13fa99c0fb71909f2f35d048d9724efb9ae432484e47f12386b1542815e8/prime_traces-0.0.3.tar.gz", hash = "sha256:4071833db77a606ccbb718e5c73f2dfaf63982fe801aa096daed0bc605da554f", size = 50874, upload-time = "2026-08-27T19:46:44.672Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ce/9a/5a917de29a3a839c0ba36d445e3af562f744d9716b509571be643a01476c/prime_traces-0.0.3-py3-none-any.whl", hash = "sha256:0838f60651f1ed38371e383bd88b954e461d20ac424874e694bc83358934f5f3", size = 38345, upload-time = "2026-08-27T19:46:43.396Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prime-tunnel"
|
||||
version = "0.1.10"
|
||||
@@ -5846,6 +5896,19 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/46/bd/2d45ad24f5f5ae7e8d01525eb76786fa7557136555cac7d929880519e33a/pyzmq-27.1.0-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:f30f395a9e6fbca195400ce833c731e7b64c3919aa481af4d88c3759e0cb7496", size = 1878550, upload-time = "2025-09-08T23:08:13.513Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pyzstd"
|
||||
version = "0.19.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "backports-zstd" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/4c/66/59fed71d0d2065e02974b40296f836a237c364c8bbe07295f2d0dc33c278/pyzstd-0.19.1.tar.gz", hash = "sha256:36723d3c915b3981de9198d0a2c82b2f5fe3eaa36e4d8d586937830a8afc7d72", size = 69531, upload-time = "2025-12-13T08:15:33.455Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/4d/62/f55d1363512d1b1cc122af6ca5951008e42605b63675c7d6781affc7c475/pyzstd-0.19.1-py3-none-any.whl", hash = "sha256:267e2eb0de0291dfcb7ccfebc4ffe75b2f9d84e7007ac38844f6ccafc6dce081", size = 23779, upload-time = "2025-12-13T08:15:31.979Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quack-kernels"
|
||||
version = "0.6.4"
|
||||
@@ -7620,16 +7683,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]
|
||||
@@ -7677,7 +7740,9 @@ dependencies = [
|
||||
{ name = "aiohttp" },
|
||||
{ name = "anthropic" },
|
||||
{ name = "gepa" },
|
||||
{ name = "h11" },
|
||||
{ name = "httpx" },
|
||||
{ name = "httpx2" },
|
||||
{ name = "loguru" },
|
||||
{ name = "math-verify" },
|
||||
{ name = "mcp" },
|
||||
@@ -7685,6 +7750,7 @@ dependencies = [
|
||||
{ name = "numpy" },
|
||||
{ name = "openai" },
|
||||
{ name = "prime-pydantic-config", extra = ["toml"] },
|
||||
{ name = "prime-runs" },
|
||||
{ name = "prime-sandboxes" },
|
||||
{ name = "prime-tunnel" },
|
||||
{ name = "pydantic" },
|
||||
@@ -7694,6 +7760,7 @@ dependencies = [
|
||||
{ name = "tenacity" },
|
||||
{ name = "tomli-w" },
|
||||
{ name = "typing-extensions" },
|
||||
{ name = "uvicorn" },
|
||||
]
|
||||
|
||||
[package.optional-dependencies]
|
||||
@@ -7711,8 +7778,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" },
|
||||
@@ -7723,6 +7792,7 @@ requires-dist = [
|
||||
{ name = "openai", specifier = ">=2.54.0,<3.0.0" },
|
||||
{ name = "openenv", marker = "extra == 'openenv'", specifier = ">=0.4.1" },
|
||||
{ name = "prime-pydantic-config", extras = ["toml"], specifier = ">=0.4.3" },
|
||||
{ name = "prime-runs", specifier = ">=0.1.1" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.2.39" },
|
||||
{ name = "prime-tunnel", specifier = ">=0.1.8" },
|
||||
{ name = "pydantic", specifier = ">=2.12.3" },
|
||||
@@ -7733,6 +7803,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"]
|
||||
|
||||
|
||||
Reference in New Issue
Block a user