Compare commits

...
Author SHA1 Message Date
eligottsandGitHub be5855cfe3 Harden dashboard cited-report guidance (#3393) 2026-08-25 15:35:55 -07:00
Mika SenghaasandGitHub 43365ec52f feat: model converter scripts (#3348)
## Summary

- Add `tools/convert_dcp_to_bf16.py`: convert a DCP trainer checkpoint
to HF sharded safetensors offline. Recovers the converter deferred out
of #3316 and adapts it: required positional `ckpt_dir` (accepts
`<run>/checkpoints/step_{n}` or `.../step_{n}/trainer`), output defaults
to `<ckpt_dir>/weights` (or a second positional arg), model/tokenizer
configs read from the run's resolved `configs/trainer.json` / `sft.json`
(the single source of truth — the checkpoint must live in its run
directory), single-process (`uv run python`) and multi-rank (`torchrun`)
invocations. Local `trust_remote_code` models get their custom code
files copied next to the weights. Full fine-tunes only — LoRA
checkpoints are rejected up front. Export replaces training-only
attention, fused-MoE, and DeepEP settings with portable
model-construction values.
- Add `tools/convert_bf16_to_fp8.py`: quantize an HF safetensors dir to
blockwise FP8 (DeepSeek/GLM format: e4m3 weights + `weight_scale_inv`
per-128×128-block scales, `quantization_config` block vLLM loads
natively). Streams shard-by-shard; norms, embeddings, lm_head, router
gates, GatedDeltaNet low-rank projections, MTP projection, and vision
towers stay bf16. Reuses `quantize_to_fp8_blockwise` from
`prime_rl.trainer.models.fp8`. Inspired by slime/miles
`tools/convert_hf_to_fp8.py`.
- Add `tools/convert_dcp_to_fp8.py`: DCP straight to fp8 — same gather
as `dcp_to_bf16`, but each rank quantizes its slice on GPU and only fp8
shards are written to `<ckpt_dir>/weights-FP8` (no intermediate bf16
export on disk).
- Add `tools/convert_fp8_to_bf16.py`: the inverse (dequantize
blockwise-fp8 releases like GLM-5-FP8 to bf16 for training). Inspired by
slime/miles `tools/fp8_cast_bf16.py`.
- Fold converter e2e checks into the existing reverse-text CI runs (no
new CI matrix entries): both the SFT and RL integration tests convert
their final DCP checkpoint to bf16 and fp8 and assert the exports reload
in HF with a clean loading report; the RL test additionally asserts
direct `dcp_to_fp8` output is byte-identical to chained `bf16_to_fp8` on
a real trainer checkpoint. Shared helpers
`convert_checkpoint`/`check_hf_load` in `tests/utils.py`. (A standalone
per-arch byte-exactness matrix over the mini_moe archs — glm4_moe,
laguna, minimax_m2, qwen3.5-MoE VLM; bf16 exports byte-identical to
their random-init sources, both fp8 paths byte-identical — was validated
during development and dropped from CI in favor of these hooks.) Also
fixes the mini_moe VLM preset `mrope_section` for its shrunken head_dim.
- Read the run config from the `configs/resolved/` layout via
`get_config_dir` (adapted after merging main).
- Document the export flow in `docs/training.md` and
`skills/training/start-run/SKILL.md`, and note the CLI convention in
`AGENTS.md`: `tools/` scripts use plain argparse, `[project.scripts]`
entrypoints use pydantic-config.

## Verification

All run on 2× RTX PRO 6000 Blackwell (SM120), vLLM 0.26.

**dcp→hf, real RL run (qwen3 dense)** — 20-step reverse-text RL run with
`--ckpt.interval 10 --weight-broadcast.type filesystem`:
- step 10 converted single-process, step 20 with `torchrun
--nproc-per-node 2`.
- Both exports are **bit-identical** (all 310 tensors) to the trainer's
own filesystem-broadcast weights at the same step; tied `lm_head.weight`
is dropped per HF convention and verified equal to `embed_tokens`.
- `uv run inference --vllm.model .../step_10/weights` serves the export;
reverse-text eval (`uv run eval`, n=64 r=4) scores **0.754** vs 0.744
training reward at step 10. Step 20 export scores **0.801** vs ~0.80 at
end of training.

**dcp→hf, architecture matrix** — per arch: tiny random model
(`scripts/mini_moe.py`) → 3-step fake-data SFT → convert (exercises
`configs/sft.json` auto-detection) → verify:

| arch | strict HF load | prime reload + forward | notes |
|---|---|---|---|
| glm4_moe (MoE) | ✓ | ✓ | plus direct HF→DCP→HF round trip: 889/889
tensors bit-exact (expert stack/unstack) |
| laguna | ✓ (`trust_remote_code=True`) | ✓ | HF→DCP→HF round trip
433/433 tensors bit-exact modulo the conversion chain's canonical
per-expert layout (the same layout the live broadcast path emits;
poolside's HF class stores fused `experts.gate_up_proj` and re-inits
experts it doesn't recognize — see `converting_laguna.py` docstring) |
| minimax_m2 (MoE) | ✓ | ✓ | mini built via prime impl (MiniMax remote
code incompatible with transformers v5) |
| qwen3_5_moe VLM | ✓ (`Qwen3_5MoeForConditionalGeneration`) | key-set
identity vs source | vision tower + linear attention round-trip |


**bf16→fp8 + fp8→bf16** — on the real step-20 Qwen3-0.6B export and all
four minis: dequant error bounded (worst median relative error ~2.2%,
e4m3-consistent), skip-list modules bit-identical,
index/`quantization_config` consistent; fp8→bf16 round trip drops all
`*_scale_inv` keys and `quantization_config`. Structure matches the
official `Qwen/Qwen3-0.6B-FP8` release (same scale shapes/names).
Serving the fp8→bf16 round-tripped weights scores **0.798** (vs 0.801
bf16 baseline), confirming the stored values.

**fp8 serving on SM120 (vLLM kernel bug, not the script)**: serving the
fp8 checkpoint scores **0.31** with vLLM's default
`CutlassFp8BlockScaledMMKernel` on this box, but **0.790** with the same
checkpoint after forcing the Triton kernel
(`VLLM_DISABLED_KERNELS=...CutlassFp8BlockScaledMMKernel,MarlinFP8ScaledMMLinearKernel`
→ `TritonFp8BlockScaledMMKernel`), and vLLM's *online* fp8 of the same
weights scores 0.79. vLLM's CUTLASS blockwise-fp8 GEMM silently degrades
on SM120 (RTX PRO 6000); upstream already tracks other SM120
blockwise-fp8 breakage (vllm-project/vllm#47990, #47436). Noted the
workaround in `skills/training/start-run/SKILL.md`; H100/H200/B200
(SM90/SM100) use different kernels.

## Not ported from slime/miles

Megatron converters (`convert_torch_dist_to_hf*`,
`convert_hf_to_torch_dist`) — prime-rl is FSDP/DCP; int4 converters
(Kimi-K2-specific); mxfp8/nvfp4 (no checkpoint-level use case yet);
`param_name_remap.py` (covered by prime conversion chains); profiling
tools (prime-rl has its own monitors).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Converters touch distributed gather, HF weight layout, and
quantization paths that must match live training/broadcast behavior;
mistakes could ship broken checkpoints, though integration tests and
LoRA rejection reduce exposure.
> 
> **Overview**
> Adds offline **checkpoint export and FP8 conversion** tooling under
`tools/convert_*.py`, plus docs/skills updates and integration-test
coverage.
> 
> **DCP → Hugging Face:** `convert_dcp_to_bf16.py` loads FSDP DCP
trainer checkpoints using the run’s resolved
`configs/resolved/trainer.json` or `sft.json`, gathers weights in
parallel (single GPU or `torchrun`), writes sharded bf16 safetensors and
tokenizer/config assets to `<ckpt_dir>/weights`, and **rejects LoRA**
checkpoints.
> 
> **FP8 round-trip:** `convert_bf16_to_fp8.py` blockwise-quantizes HF
safetensors (e4m3 + `weight_scale_inv`, vLLM-native
`quantization_config`); `convert_dcp_to_fp8.py` quantizes each rank’s
gathered slice straight to `<ckpt_dir>/weights-FP8` without a bf16
export on disk; `convert_fp8_to_bf16.py` dequantizes fp8-only releases
for training.
> 
> **CI:** Reverse-text RL and SFT integration tests convert the final
checkpoint, assert clean `AutoModelForCausalLM` loads, and (RL)
byte-identity between direct `dcp_to_fp8` and chained `bf16_to_fp8`.
Shared helpers `convert_checkpoint` / `check_hf_load` live in
`tests/utils.py`. `scripts/mini_moe.py` fixes `mrope_section` for the
shrunk VLM preset.
> 
> **Docs:** `docs/training.md` and training skills document the export
flow; `AGENTS.md` notes `tools/` scripts use plain argparse vs
pydantic-config entrypoints. Run artifact paths use `step_{n}`
consistently.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fe1241dec3e1369cc930ffa6b736fe6baf4e5200. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-25 14:30:07 -07:00
Mika SenghaasandGitHub ab5de8fff4 chore: release v0.9.0 (#3379)
Tag and Release / kernels-from-auto-tag (push) Canceled after 0s
Tag and Release / auto-tag-on-main (push) Canceled after 0s
Tag and Release / release-from-auto-tag (push) Canceled after 0s
Tag and Release / resolve-release (push) Canceled after 0s
Tag and Release / kernels-from-tag (push) Canceled after 0s
Tag and Release / publish-release (push) Canceled after 0s
## Summary

- bump the prime-rl project version from 0.8.0 to 0.9.0
- update the matching prime-rl entry in uv.lock
- prepare the [draft v0.9.0 GitHub
release](https://github.com/PrimeIntellect-ai/prime-rl/releases/tag/untagged-6fdfe34d2c7a47da166a)
with notes for 105 commits since v0.8.0
- include the latest dashboard, SLURM teardown, weight synchronization,
and eval policy fixes in the release notes

## Verification

- uv lock --check
- git diff --check origin/main...HEAD
2026-08-25 13:11:39 -07:00
97d32d947f fix(orchestrator): pre-seed datasets' tqdm lock to avoid concurrent-load crash (#3391)
## Problem

`Envs.start()` starts every source concurrently
(`asyncio.gather(env.start() for env in self)`), and each `env.start()`
materializes its taskset via `load_dataset()` in a worker thread
(`asyncio.to_thread(lambda: list(taskset))`). HuggingFace `datasets`
reads cached arrow shards through
`tqdm.contrib.concurrent.thread_map(tqdm_class=hf_tqdm)`, whose
`ensure_lock()` is:

```python
old_lock = getattr(tqdm_class, "_lock", None)
lock = old_lock or tqdm_class.get_lock()
...
yield lock                       # the (slow) arrow read happens here
if old_lock is None:
    del tqdm_class._lock         # <-- racing line
else:
    tqdm_class.set_lock(old_lock)
```

When two of these run concurrently with the class lock unset, both
observe `old_lock is None`, both reach `del tqdm_class._lock` on exit,
and the second raises:

```
AttributeError: type object 'tqdm' has no attribute '_lock'
```

That kills the orchestrator during `setup()` ("Fatal error in
run_orchestrator"), and the trainer then hangs waiting for rollouts that
never come.

**When it triggers:** ≥2 sources load datasets concurrently at startup
(e.g. multiple train sources over the same taskset). The race window is
the arrow read, so more sources / colder caches make it more likely — 3
concurrent loads hit it essentially every run, 2 intermittently, 1
never. It is **not** caught by `--dry-run`, which never calls
`load_dataset()`.

Root cause is a tqdm thread-safety gap (`ensure_lock` isn't safe for
concurrent use on a single class), exposed by `datasets`' `thread_map`
plus concurrent taskset loading here.

## Fix

Pre-seed the `datasets` tqdm class lock once, before the concurrent
gather, so `old_lock` is never `None` and every `ensure_lock` takes the
non-deleting `else` branch — the same state tqdm is in whenever a
progress bar is active:

```python
from datasets.utils import tqdm as _hf_tqdm
_hf_tqdm.set_lock(_hf_tqdm.get_lock())
```

This targets the exact class `datasets` passes to `thread_map`
(`datasets.utils.tqdm.tqdm`, the same object `arrow_reader` imports). It
only stops the lock object from being created-and-deleted per call; no
change to progress-bar display, dataset contents, or ordering.

## Reproduction

Hammering the failing primitive directly (16 threads, window widened to
mimic the slow arrow read):

- **without** the fix: consistent `AttributeError: type object 'tqdm'
has no attribute '_lock'`
- **with** the fix: clean, 0 failures

Also observed live: a 3-train-source run crashed here every time; after
the fix all three arms load cleanly.

## Alternative considered

Loading sources sequentially in `Envs.start()` also avoids the race, at
the cost of startup parallelism. The pre-seed keeps the parallel load.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Single-line lock initialization before existing parallel env startup;
no auth, data, or algorithm changes.
> 
> **Overview**
> **Fixes a startup crash** when multiple train/eval sources load
HuggingFace datasets in parallel during `Envs.start()`.
> 
> Concurrent `load_dataset()` paths use `datasets`' `thread_map` with
tqdm's `ensure_lock()`, which can race on `del tqdm_class._lock` and
raise `AttributeError`—fatal during orchestrator `setup()` and leaving
the trainer waiting on rollouts.
> 
> Before `asyncio.gather` on `env.start()`, the change **pre-seeds** the
lock on `datasets.utils.tqdm` via `set_lock(get_lock())` so concurrent
readers never hit the delete branch. Parallel startup is preserved; no
change to dataset contents or progress display.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
a1007d2d9cc0b8e15a2df959cec54cf3b366fce3. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-25 13:09:20 -07:00
16 changed files with 647 additions and 13 deletions
+1
View File
@@ -31,6 +31,7 @@ Namespaces are one honking great idea -- let's do more of those!
## Running code
- **Always use uv**: run code with `uv run` or `uv run <command>`, never raw `python`.
- **Tools vs entrypoints**: standalone scripts in `tools/` use plain argparse with positional args; `[project.scripts]` entrypoints use pydantic-config (`@ file.toml` + dotted CLI overrides).
- **Adding dependencies**: add to `pyproject.toml` and run `uv sync --all-extras` to install and lock them.
- **Git dependency pins**: when pinning git dependencies in `pyproject.toml`, always use a small (7-char) commit hash for the `rev` field.
- **Never edit `.venv/`**: the local virtual env is read-only. Edits there are silently overwritten by the next `uv sync` and don't propagate to teammates or CI. Reading files under `.venv/` to understand library behavior is fine; writing is not. To fix a dependency issue, update `pyproject.toml` (pin a fork via 7-char commit hash if needed), vendor the code into `src/`, or patch upstream.
+16 -2
View File
@@ -263,8 +263,8 @@ Checkpointing is split across processes because the orchestrator and trainer can
| Process | What's saved | Where |
|---|---|---|
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<run_dir>/checkpoints/step_N/trainer/` |
| Orchestrator | Progress, per-env data state | `<run_dir>/checkpoints/step_N/orchestrator/` |
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<run_dir>/checkpoints/step_{n}/trainer/` |
| Orchestrator | Progress, per-env data state | `<run_dir>/checkpoints/step_{n}/orchestrator/` |
| Inference | _nothing_ — re-pushed from the latest checkpoint on restart | n/a |
### Enabling Checkpoints
@@ -297,6 +297,20 @@ uv run rl @ rl.toml --max-steps 20 --ckpt --run.name my-fork \
--resume.dir outputs/my-run/checkpoints/step_10
```
### Exporting Checkpoints
Trainer checkpoints are DCP-sharded; export them to HF-format safetensors with `tools/convert_dcp_to_bf16.py`. The script reads the model config from the run's resolved config and writes sharded safetensors plus config/tokenizer assets to `<ckpt_dir>/weights` (or a second positional arg). It exports full fine-tunes only — LoRA checkpoints are rejected.
```bash
# single process (1 GPU)
uv run python tools/convert_dcp_to_bf16.py outputs/my-run/checkpoints/step_10
# multi-rank for faster gathers and models that don't fit one GPU
uv run torchrun --nproc-per-node 8 tools/convert_dcp_to_bf16.py outputs/my-run/checkpoints/step_10
```
The exported directory loads directly into `uv run inference --vllm.model <dir>` or any HF consumer. Quantize it to blockwise FP8 (DeepSeek/GLM format, loads natively in vLLM) with `tools/convert_bf16_to_fp8.py <dir>`, or go straight from the checkpoint with `tools/convert_dcp_to_fp8.py <ckpt_dir>` (each rank quantizes its gathered slice, writes only `<ckpt_dir>/weights-FP8` — no intermediate bf16 export); dequantize an fp8-only release (e.g. GLM-5-FP8) for training with `tools/convert_fp8_to_bf16.py <dir>`.
## Observability
### Log Files
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "prime-rl"
version = "0.8.0"
version = "0.9.0"
description = "Async RL Training at Scale"
readme = "README.md"
requires-python = "~=3.12.0"
+2
View File
@@ -47,6 +47,8 @@ def _qwen3_5_moe_vlm_config():
tc.num_attention_heads = 4
tc.num_key_value_heads = 2
tc.head_dim = 64
# mrope_section must sum to rotary_dim // 2 for the shrunken head_dim
tc.rope_parameters["mrope_section"] = [3, 3, 2]
tc.moe_intermediate_size = 128
tc.shared_expert_intermediate_size = 128
tc.num_experts = 4
+19 -3
View File
@@ -93,10 +93,21 @@ The dip is provider errors, not policy regression [^err].
[^err]: {"step": 4, "kind": "train", "subset": "all", "episode": "ep-...", "node": 0, "quote": "engine overloaded", "note": "The failed call that emptied this step's batch."}
```
The frontmatter `title` is rendered as the report H1; do not repeat it with a
Markdown `#` heading. The inline renderer supports only HTTP(S) and anchor
links. Relative Markdown links render as literal text, so identify local source
files with inline code paths or link to a supported HTTP endpoint.
Each citation requires `step`, `kind`, `subset`, `episode`, `quote`, and `note`.
Use the episode `id`, never `line`. Copy a short, distinctive quote exactly;
matching is case-sensitive and whitespace-insensitive. Keep `note` to 1–2
sentences explaining why the quote supports the claim.
Use the top-level rollout record `id` returned by the dashboard episode-list
API—not a nested `traces[*].id`, and never `line`. Copy a short, distinctive
quote exactly; matching is case-sensitive and whitespace-insensitive. Keep
`note` to 1–2 sentences explaining why the quote supports the claim.
Cite major empirical, comparative, and diagnostic conclusions, but not routine
explanation. Use exact trace citations for trajectory-level claims. For
aggregate statistics, identify the run and source file; do not imply that one
example trajectory proves the aggregate.
Use adjacent markers (`[^a] [^b]`) only when one claim genuinely depends on
distinct passages, such as a comparison or corroboration. Use one citation
@@ -108,3 +119,8 @@ parts. Use verbatim adjacent `prefix`/`suffix` only when a quote repeats.
Ambiguous or mismatched citations remain broken and do not navigate.
Use Markdown; raw HTML is escaped.
Before handoff, reload the report and verify through the dashboard API that
every referenced citation resolves uniquely to its episode, node, and quote.
Confirm zero broken citations, one rendered title, and no unsupported relative
links.
+4 -4
View File
@@ -50,7 +50,7 @@ In W&B, each project auto-gets an **"overview" saved view** (train / eval / stab
- `{run_dir}/configs/` — the launch TOML copied verbatim (`rl.toml`/`sft.toml`), plus `resolved/` with the per-component resolved configs, written as JSON so explicit None settings round-trip.
- `{run_dir}/logs/latest/` — the current attempt's logs (each launch gets `logs/attempt_<n>/`; resumes never overwrite earlier attempts). See below.
- `{run_dir}/rollouts/step_N/{train,eval}/` — saved episodes (see Episodes below).
- `{run_dir}/rollouts/step_{n}/{train,eval}/` — saved episodes (see Episodes below).
### Dashboard
@@ -162,8 +162,8 @@ curl -s http://localhost:8100/metrics | grep -E "num_requests|gpu_cache_usage"
### Episodes
```
{run_dir}/rollouts/step_N/{train,eval}/all/traces.jsonl # appended per episode as it completes
{run_dir}/rollouts/step_N/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
{run_dir}/rollouts/step_{n}/{train,eval}/all/traces.jsonl # appended per episode as it completes
{run_dir}/rollouts/step_{n}/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
```
JSONL files of native `vf.Episode` records (training tensors excluded), one line per episode.
@@ -182,7 +182,7 @@ jq '.traces[].rewards' {run_dir}/rollouts/step_42/train/effective/traces.jsonl
jq 'select(.ok | not) | {id, env: .env.id, errors}' {run_dir}/rollouts/step_*/train/all/traces.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}/rollouts/step_N/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the episode subtrees.
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}/rollouts/step_{n}/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the episode subtrees.
### Common failure modes
+4 -1
View File
@@ -127,6 +127,10 @@ env.agent.runtime.type = "subprocess"
- Config: `EvalsConfig` (`packages/prime-rl-configs/src/prime_rl/configs/evals.py`)
- Entrypoint: `src/prime_rl/entrypoints/evals.py` (implementation: `src/prime_rl/evals/evals.py`)
## Exporting checkpoints
Trainer checkpoints are DCP-sharded (`<run_dir>/checkpoints/step_{n}/trainer`). Convert to HF safetensors with `uv run python tools/convert_dcp_to_bf16.py <run_dir>/checkpoints/step_{n}` (writes `<ckpt_dir>/weights`, serveable via `uv run inference --vllm.model <dir>`; model config auto-read from the run’s `configs/resolved/trainer.json`/`sft.json`; multi-rank via `torchrun --nproc-per-node N`; full fine-tunes only, LoRA rejected). Quantize a bf16 HF dir to blockwise FP8 with `tools/convert_bf16_to_fp8.py <dir>` (vLLM-native format), or straight from a checkpoint with `tools/convert_dcp_to_fp8.py <ckpt_dir>` (rank-parallel, writes only `<ckpt_dir>/weights-FP8`, no bf16 on disk); dequantize fp8-only releases with `tools/convert_fp8_to_bf16.py <dir>`. Caveat: on SM120 GPUs (RTX PRO 6000) vLLM 0.26 picks `CutlassFp8BlockScaledMMKernel` for blockwise-fp8 checkpoints and it silently degrades outputs — serve with `VLLM_DISABLED_KERNELS=CutlassFp8BlockScaledMMKernel,MarlinFP8ScaledMMLinearKernel` to fall back to the Triton kernel.
## Summary
| Command | Purpose | Typical use |
@@ -150,4 +154,3 @@ Interactive launches auto-start one shared dashboard daemon per user (process ti
that URL to the researcher. Discovery: `~/.cache/prime-rl/dashboard/daemon.json` holds
the live `url` (the port can differ from 7788 when it was taken). `--no-dashboard`
opts a run out.
+7
View File
@@ -179,6 +179,13 @@ class Envs(Generic[EnvT]):
async def start(self) -> None:
"""Connect to all env servers in parallel — every address is known up front,
so there's nothing to serialize on."""
# When several env.start()s load_dataset() concurrently, datasets' parallel arrow read
# (tqdm thread_map) races in ensure_lock's `del tqdm_class._lock` and crashes with
# `AttributeError: type object 'tqdm' has no attribute '_lock'`. Pre-seed the lock so it
# isn't created-and-deleted per call.
from datasets.utils import tqdm as hf_tqdm
hf_tqdm.set_lock(hf_tqdm.get_lock())
await asyncio.gather(*(env.start() for env in self))
+24
View File
@@ -2,14 +2,18 @@ from pathlib import Path
from typing import Callable
import pytest
import torch
from prime_rl.utils.weights import load_state_dict
from tests.conftest import ProcessResult
from tests.integration.dashboard_smoke import make_dashboard_test
from tests.utils import (
check_avg_mismatch_kl_in_range,
check_hf_load,
check_no_error,
check_reward_goes_up,
check_reward_in_range,
convert_checkpoint,
strip_escape_codes,
)
@@ -129,4 +133,24 @@ def test_reward_in_range_resume(rl_resume_process: ProcessResult, test_no_error_
check_reward_in_range(orchestrator_stdout, min_threshold=0.6)
def test_convert_final_checkpoint(rl_resume_process: ProcessResult, run_dir: Path, tmp_path: Path):
"""The final DCP checkpoint converts to bf16 and fp8 (direct == chained), and the exports reload in HF."""
assert rl_resume_process.returncode == 0
step_dir = run_dir / "checkpoints" / "step_20"
convert_checkpoint("dcp_to_bf16", step_dir)
convert_checkpoint("dcp_to_fp8", step_dir)
check_hf_load(step_dir / "weights")
# Quantizing the bf16 export reproduces the direct dcp->fp8 export byte-for-byte.
convert_checkpoint("bf16_to_fp8", step_dir / "weights", tmp_path / "fp8-chained")
direct = load_state_dict(step_dir / "weights-FP8")
chained = load_state_dict(tmp_path / "fp8-chained")
assert set(direct) == set(chained)
for key in direct:
assert torch.equal(direct[key].view(torch.uint8), chained[key].view(torch.uint8)), key
convert_checkpoint("fp8_to_bf16", step_dir / "weights-FP8", tmp_path / "dequant")
check_hf_load(tmp_path / "dequant")
test_dashboard = make_dashboard_test("rl_process", RUN_NAME)
+12 -1
View File
@@ -7,7 +7,7 @@ from torch.distributed.checkpoint.format_utils import dcp_to_torch_save
from tests.conftest import ProcessResult
from tests.integration.dashboard_smoke import make_dashboard_test
from tests.utils import check_loss_goes_down, strip_escape_codes
from tests.utils import check_hf_load, check_loss_goes_down, convert_checkpoint, strip_escape_codes
pytestmark = [pytest.mark.slow, pytest.mark.gpu]
@@ -173,4 +173,15 @@ def test_full_offload_model_only_resume_preserves_weights(
)
def test_convert_final_checkpoint(sft_resume_process: ProcessResult, run_dir: Path, tmp_path: Path):
"""The final DCP checkpoint converts to bf16 and fp8, and the exports reload in HF."""
assert sft_resume_process.returncode == 0
step_dir = run_dir / "checkpoints" / "step_10"
convert_checkpoint("dcp_to_bf16", step_dir)
convert_checkpoint("dcp_to_fp8", step_dir)
check_hf_load(step_dir / "weights")
convert_checkpoint("fp8_to_bf16", step_dir / "weights-FP8", tmp_path / "dequant")
check_hf_load(tmp_path / "dequant")
test_dashboard = make_dashboard_test("sft_process", RUN_NAME)
+20
View File
@@ -223,3 +223,23 @@ def check_mismatch_kl_in_range(
min_threshold=min_threshold,
max_threshold=max_threshold,
)
def convert_checkpoint(converter: str, *args: Path) -> None:
"""Run ``tools/convert_<converter>.py`` on a checkpoint."""
import subprocess
cmd = ["uv", "run", "python", f"tools/convert_{converter}.py", *[str(arg) for arg in args]]
subprocess.run(cmd, check=True, timeout=600)
def check_hf_load(weights_dir: Path) -> None:
"""Helper to assert that an exported checkpoint loads as an HF model with no missing/unexpected tensors"""
import torch
from transformers import AutoModelForCausalLM
model, loading_info = AutoModelForCausalLM.from_pretrained(weights_dir, output_loading_info=True)
assert not loading_info["missing_keys"], f"missing keys: {loading_info['missing_keys'][:5]}"
assert not loading_info["unexpected_keys"], f"unexpected keys: {loading_info['unexpected_keys'][:5]}"
assert not loading_info["mismatched_keys"], f"mismatched keys: {loading_info['mismatched_keys'][:5]}"
assert all(torch.isfinite(param).all() for param in model.parameters())
+153
View File
@@ -0,0 +1,153 @@
"""Quantize a bf16 HF safetensors checkpoint to blockwise FP8 (DeepSeek/GLM format).
2D linear weights are quantized to e4m3 with per-128x128-block fp32 scales
stored under ``<name>.weight_scale_inv``; norms, embeddings, lm_head, router
gates and other sensitive modules stay in the source dtype. The output dir gets
the quantized shards, a rewritten index, all non-weight assets, and a
``quantization_config`` block in ``config.json`` that vLLM loads natively.
Usage (from the prime-rl repo):
uv run python tools/convert_bf16_to_fp8.py <model_dir> [output_dir] [--block-size 128]
Writes to ``<model_dir>-FP8`` by default.
"""
import argparse
import json
import shutil
from pathlib import Path
import torch
from safetensors import safe_open
from safetensors.torch import save_file
from prime_rl.trainer.models.fp8 import quantize_to_fp8_blockwise
# Module-name substrings that stay unquantized: norms, embeddings, output head,
# MoE router gates, GatedDeltaNet low-rank projections, MTP/indexer projections,
# vision tower. Mirrors the trainer's _DEFAULT_FP8_IGNORE_PATTERNS
# (configs/trainer.py), adapted to HF checkpoint names.
SKIP_SUBSTRINGS = (
"norm",
"embed",
"lm_head",
"shared_expert_gate",
"in_proj_a",
"in_proj_b",
"eh_proj",
"weights_proj",
"visual.",
"router",
)
def should_quantize(name: str, tensor: torch.Tensor) -> bool:
return (
name.endswith(".weight")
and tensor.ndim == 2
and tensor.is_floating_point()
and tensor.element_size() > 1
and not name.endswith(".gate.weight")
and not any(substring in name for substring in SKIP_SUBSTRINGS)
)
def quantize_state_dict(
tensors: dict[str, torch.Tensor], block_size: int, device: str
) -> tuple[dict[str, torch.Tensor], list[str]]:
"""Quantize the quantizable tensors of one CPU state-dict slice; returns (out, modules kept in bf16).
Tensors move to ``device`` one at a time (and are popped from the input as they
are consumed), so peak device memory stays near the largest single weight.
"""
out: dict[str, torch.Tensor] = {}
modules_to_not_convert: list[str] = []
for name in list(tensors):
tensor = tensors.pop(name)
if should_quantize(name, tensor):
quantized, scales = quantize_to_fp8_blockwise(tensor.to(device), block_size)
out[name] = quantized.cpu()
out[name + "_scale_inv"] = scales.cpu()
else:
if name.endswith(".weight") and tensor.ndim == 2 and tensor.is_floating_point():
modules_to_not_convert.append(name.removesuffix(".weight"))
if name.endswith(".weight") and tensor.ndim > 2 and tensor.numel() > 1_000_000:
print(f"Warning: leaving large {tensor.ndim}D tensor unquantized: {name} {tuple(tensor.shape)}")
out[name] = tensor.cpu()
return out, modules_to_not_convert
def quantization_config(modules_to_not_convert: list[str], block_size: int) -> dict:
return {
"quant_method": "fp8",
"fmt": "e4m3",
"activation_scheme": "dynamic",
"weight_block_size": [block_size, block_size],
"modules_to_not_convert": sorted(set(modules_to_not_convert)),
}
def list_shards(model_dir: Path) -> list[str]:
index_path = model_dir / "model.safetensors.index.json"
if index_path.exists():
weight_map = json.loads(index_path.read_text())["weight_map"]
return sorted(set(weight_map.values()))
if (model_dir / "model.safetensors").exists():
return ["model.safetensors"]
raise FileNotFoundError(f"No safetensors checkpoint found in {model_dir}")
def convert(input_dir: Path, output_dir: Path | None = None, block_size: int = 128) -> Path:
input_dir = input_dir.resolve()
output_dir = output_dir or input_dir.with_name(input_dir.name + "-FP8")
output_dir.mkdir(parents=True, exist_ok=True)
device = "cuda" if torch.cuda.is_available() else "cpu"
weight_map: dict[str, str] = {}
total_size = 0
modules_to_not_convert: list[str] = []
num_quantized = 0
for shard_name in list_shards(input_dir):
# Shards land in host memory; quantize_state_dict streams them through the
# device tensor-by-tensor so a whole shard never sits on the GPU at once.
with safe_open(input_dir / shard_name, framework="pt", device="cpu") as f:
tensors = {name: f.get_tensor(name) for name in f.keys()}
out_shard, shard_modules = quantize_state_dict(tensors, block_size, device)
modules_to_not_convert.extend(shard_modules)
num_quantized += sum(1 for name in out_shard if name.endswith("_scale_inv"))
for name, tensor in out_shard.items():
weight_map[name] = shard_name
total_size += tensor.nbytes
save_file(out_shard, output_dir / shard_name, metadata={"format": "pt"})
print(f"Quantized {shard_name} ({num_quantized} tensors so far)")
if num_quantized == 0:
raise ValueError(f"No quantizable weights found in {input_dir} - is this a bf16 checkpoint?")
index = {"metadata": {"total_size": total_size}, "weight_map": weight_map}
(output_dir / "model.safetensors.index.json").write_text(json.dumps(index, indent=2, sort_keys=True) + "\n")
for path in input_dir.iterdir():
if path.is_file() and path.suffix != ".safetensors" and path.name != "model.safetensors.index.json":
shutil.copyfile(path, output_dir / path.name)
config_path = input_dir / "config.json"
config = json.loads(config_path.read_text())
config["quantization_config"] = quantization_config(modules_to_not_convert, block_size)
(output_dir / "config.json").write_text(json.dumps(config, indent=2) + "\n")
print(f"Done: {num_quantized} weights quantized -> {output_dir}")
return output_dir
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("input_dir", type=Path, help="HF safetensors model dir (bf16/fp16/fp32)")
parser.add_argument("output_dir", type=Path, nargs="?", default=None, help="default: <input_dir>-FP8")
parser.add_argument("--block-size", type=int, default=128)
args = parser.parse_args()
convert(args.input_dir, args.output_dir, args.block_size)
if __name__ == "__main__":
main()
+201
View File
@@ -0,0 +1,201 @@
"""Convert a DCP trainer checkpoint into bf16 HF-format weights offline.
The trainer saves only DCP checkpoints; every HF export goes through this
script. It mirrors the trainer's broadcast save path: build the model, DCP-load
the checkpoint's model state, gather rank-parallel, convert to HF format, and
write sharded safetensors plus config/tokenizer assets.
The model and tokenizer configs are read from the run's resolved config
(``<run>/configs/resolved/trainer.json`` or ``sft.json``). LoRA checkpoints are not
supported — the script exports full fine-tunes only.
Usage (from the prime-rl repo; more ranks = faster gathers and writes, and
models too big for one GPU need enough ranks to shard across):
uv run python tools/convert_dcp_to_bf16.py <run>/checkpoints/step_{n} [output_dir]
uv run torchrun --nproc-per-node 8 tools/convert_dcp_to_bf16.py \
<run>/checkpoints/step_{n} [output_dir]
Writes to ``<ckpt_dir>/weights`` by default.
"""
import argparse
import json
import os
import shutil
import socket
from copy import deepcopy
from pathlib import Path
import torch
import torch.distributed as dist
from torch.distributed.checkpoint import FileSystemReader
from torch.distributed.checkpoint.state_dict_loader import load as dcp_load
from prime_rl.configs.trainer import ModelConfig, TokenizerConfig
from prime_rl.trainer.ckpt import AppState
from prime_rl.trainer.model import setup_model, setup_processor, setup_tokenizer
from prime_rl.trainer.parallel_dims import get_parallel_dims, resolve_ep
from prime_rl.trainer.utils import setup_torch_distributed
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger, setup_logger
from prime_rl.utils.pathing import get_config_dir
from prime_rl.utils.weights import (
convert_state_dict_to_hf,
gather_weights_parallel,
save_state_dict_parallel,
)
# Training kernels and parallelism settings do not apply to an offline export.
# Resolve parallelism for the converter's world size and use portable kernels.
CONVERSION_OVERRIDES = {
"compile": None,
"ac": None,
"dp_replicate": 1,
"cp": 1,
"ep": "auto",
"ep_comm_backend": "torch",
"attn": "flash_attention_2",
"moe_fused_kernel": False,
}
RUN_CONFIG_NAMES = ("trainer.json", "sft.json")
def resolve_dcp_dir(ckpt_dir: Path) -> Path:
"""The DCP checkpoint id for a step dir (``step_{n}``) or its ``trainer`` subdir."""
if (ckpt_dir / "trainer" / ".metadata").exists():
return ckpt_dir / "trainer"
if (ckpt_dir / ".metadata").exists():
return ckpt_dir
raise FileNotFoundError(f"No DCP checkpoint found at {ckpt_dir} (expected {ckpt_dir}/trainer/.metadata)")
def resolve_run_configs(step_dir: Path) -> tuple[ModelConfig, TokenizerConfig]:
"""Model/tokenizer configs from the run's resolved config."""
logger = get_logger()
config_dir = get_config_dir(step_dir.parent.parent)
for name in RUN_CONFIG_NAMES:
path = config_dir / name
if path.exists():
logger.info(f"Reading model config from {path}")
run_config = json.loads(path.read_text())
break
else:
raise FileNotFoundError(
f"No resolved run config ({' or '.join(RUN_CONFIG_NAMES)}) found under {config_dir} "
"- the checkpoint must live in its run directory"
)
model = ModelConfig(**run_config["model"])
tokenizer = TokenizerConfig(**run_config["tokenizer"])
return model.model_copy(update=CONVERSION_OVERRIDES), tokenizer
def check_not_lora(model_config: ModelConfig, dcp_dir: Path) -> None:
if model_config.lora is not None:
raise ValueError("LoRA checkpoints are not supported - dcp_to_bf16 exports full fine-tunes only")
metadata = FileSystemReader(dcp_dir).read_metadata()
lora_keys = [k for k in metadata.state_dict_metadata if "lora_A" in k or "lora_B" in k or ".base_layer." in k]
if lora_keys:
raise ValueError(
f"Checkpoint contains LoRA keys (e.g. {lora_keys[0]}) - dcp_to_bf16 exports full fine-tunes only"
)
def setup_single_process_env() -> None:
"""Default the torchrun env vars so the script also runs under plain ``python``."""
if "RANK" in os.environ:
return
with socket.socket() as sock:
sock.bind(("localhost", 0))
free_port = sock.getsockname()[1]
os.environ["MASTER_ADDR"] = "localhost"
os.environ["MASTER_PORT"] = str(free_port)
os.environ["RANK"] = "0"
os.environ["WORLD_SIZE"] = "1"
os.environ["LOCAL_RANK"] = "0"
os.environ["LOCAL_WORLD_SIZE"] = "1"
def save_model_assets(model, model_config: ModelConfig, tokenizer_config: TokenizerConfig, output_dir: Path) -> None:
"""Save model config, generation config, processor and tokenizer next to the weights."""
model.config.save_pretrained(output_dir)
if model.generation_config:
# training sets use_cache=False which can conflict with cache_implementation —
# save with use_cache=True without mutating the model's config
gen_config = deepcopy(model.generation_config)
gen_config.use_cache = True
gen_config.save_pretrained(output_dir)
# Processor first: it saves its own (unmodified) tokenizer, which the configured
# tokenizer (pad token, custom chat template) must override.
processor = setup_processor(model_config)
if processor is not None:
processor.save_pretrained(output_dir)
if tokenizer_config.name is None:
tokenizer_config = tokenizer_config.model_copy(update={"name": model_config.name})
setup_tokenizer(tokenizer_config).save_pretrained(output_dir)
# Local trust_remote_code models localize auto_map to plain module names, so the
# custom code files must travel with the weights.
source_dir = Path(model_config.name)
if source_dir.is_dir():
for path in source_dir.glob("*.py"):
shutil.copyfile(path, output_dir / path.name)
def load_and_convert(ckpt_dir: Path):
"""DCP-load a checkpoint and gather it as a rank-partial HF-format bf16 state dict.
Returns ``(model, model_config, tokenizer_config, state_dict, step_dir)``.
"""
logger = setup_logger("info")
dcp_dir = resolve_dcp_dir(ckpt_dir)
step_dir = dcp_dir.parent
model_config, tokenizer_config = resolve_run_configs(step_dir)
check_not_lora(model_config, dcp_dir)
setup_single_process_env()
setup_torch_distributed()
resolve_ep(model_config)
parallel_dims = get_parallel_dims(model_config)
model = setup_model(model_config, parallel_dims, loading_from_checkpoint_later=True)
logger.info(f"Loading DCP checkpoint from {dcp_dir}")
dcp_load(state_dict={"app": AppState(model, [], None, None)}, checkpoint_id=dcp_dir)
logger.info("Gathering and converting weights")
state_dict = gather_weights_parallel(model, dtype=torch.bfloat16)
if getattr(model.config, "tie_word_embeddings", False):
for key in getattr(model, "_tied_weights_keys", []):
state_dict.pop(key, None)
state_dict = convert_state_dict_to_hf(model, state_dict)
return model, model_config, tokenizer_config, state_dict, step_dir
def convert(ckpt_dir: Path, output_dir: Path | None = None) -> Path:
logger = get_logger()
model, model_config, tokenizer_config, state_dict, step_dir = load_and_convert(ckpt_dir)
output_dir = output_dir if output_dir is not None else step_dir / "weights"
logger.info(f"Writing HF weights to {output_dir}")
save_state_dict_parallel(state_dict, output_dir)
if get_world().is_master:
save_model_assets(model, model_config, tokenizer_config, output_dir)
logger.info(f"Done: {output_dir}")
return output_dir
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument(
"ckpt_dir", type=Path, help="the DCP checkpoint (<run>/checkpoints/step_{n} or .../step_{n}/trainer)"
)
parser.add_argument("output_dir", type=Path, nargs="?", default=None, help="default: <ckpt_dir>/weights")
args = parser.parse_args()
convert(args.ckpt_dir, args.output_dir)
dist.destroy_process_group()
if __name__ == "__main__":
main()
+65
View File
@@ -0,0 +1,65 @@
"""Convert a DCP trainer checkpoint into blockwise-FP8 HF weights.
Same gather as ``dcp_to_bf16``, but each rank quantizes its slice on GPU and
only the fp8 shards are written — no intermediate bf16 export on disk.
Usage (from the prime-rl repo; more ranks = faster gathers, quantization and writes):
uv run python tools/convert_dcp_to_fp8.py <run>/checkpoints/step_{n} [output_dir]
uv run torchrun --nproc-per-node 8 tools/convert_dcp_to_fp8.py \
<run>/checkpoints/step_{n} [output_dir]
Writes to ``<ckpt_dir>/weights-FP8`` by default.
"""
import argparse
import json
from pathlib import Path
import torch
import torch.distributed as dist
from convert_bf16_to_fp8 import quantization_config, quantize_state_dict
from convert_dcp_to_bf16 import load_and_convert, save_model_assets
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.weights import save_state_dict_parallel
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument(
"ckpt_dir", type=Path, help="the DCP checkpoint (<run>/checkpoints/step_{n} or .../step_{n}/trainer)"
)
parser.add_argument("output_dir", type=Path, nargs="?", default=None, help="default: <ckpt_dir>/weights-FP8")
parser.add_argument("--block-size", type=int, default=128)
args = parser.parse_args()
model, model_config, tokenizer_config, state_dict, step_dir = load_and_convert(args.ckpt_dir)
output_dir = args.output_dir if args.output_dir is not None else step_dir / "weights-FP8"
logger = get_logger()
world = get_world()
logger.info("Quantizing weights to blockwise fp8")
device = "cuda" if torch.cuda.is_available() else "cpu"
state_dict, modules_to_not_convert = quantize_state_dict(state_dict, args.block_size, device)
logger.info(f"Writing fp8 weights to {output_dir}")
save_state_dict_parallel(state_dict, output_dir)
all_modules: list[list[str] | None] = [None] * world.world_size
dist.all_gather_object(all_modules, modules_to_not_convert)
dist.destroy_process_group()
if world.is_master:
save_model_assets(model, model_config, tokenizer_config, output_dir)
config_path = output_dir / "config.json"
config = json.loads(config_path.read_text())
config["quantization_config"] = quantization_config(
[module for modules in all_modules for module in modules or []], args.block_size
)
config_path.write_text(json.dumps(config, indent=2) + "\n")
logger.info(f"Done: {output_dir}")
if __name__ == "__main__":
main()
+117
View File
@@ -0,0 +1,117 @@
"""Dequantize a blockwise-FP8 HF checkpoint (DeepSeek/GLM format) to bf16.
The inverse of ``tools/convert_bf16_to_fp8.py``, and works on official fp8-only
releases (e.g. GLM-5-FP8): every e4m3 tensor is multiplied by its
``<name>_scale_inv`` per-block scales and stored as bf16, scale tensors are
dropped, and ``quantization_config`` is stripped from ``config.json``.
Usage (from the prime-rl repo):
uv run python tools/convert_fp8_to_bf16.py <model_dir> [output_dir]
Writes to ``<model_dir>-BF16`` by default.
"""
import argparse
import json
import shutil
from pathlib import Path
import torch
from safetensors import safe_open
from safetensors.torch import save_file
def dequantize_blockwise(weight: torch.Tensor, scales: torch.Tensor, block_size: tuple[int, int]) -> torch.Tensor:
rows, cols = weight.shape
block_rows, block_cols = block_size
expanded = scales.repeat_interleave(block_rows, dim=0)[:rows].repeat_interleave(block_cols, dim=1)[:, :cols]
return (weight.to(torch.float32) * expanded).to(torch.bfloat16)
def list_shards(model_dir: Path) -> list[str]:
index_path = model_dir / "model.safetensors.index.json"
if index_path.exists():
weight_map = json.loads(index_path.read_text())["weight_map"]
return sorted(set(weight_map.values()))
if (model_dir / "model.safetensors").exists():
return ["model.safetensors"]
raise FileNotFoundError(f"No safetensors checkpoint found in {model_dir}")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("input_dir", type=Path, help="HF safetensors model dir with blockwise-fp8 weights")
parser.add_argument("output_dir", type=Path, nargs="?", default=None, help="default: <input_dir>-BF16")
args = parser.parse_args()
input_dir = args.input_dir.resolve()
output_dir = args.output_dir or input_dir.with_name(input_dir.name + "-BF16")
output_dir.mkdir(parents=True, exist_ok=True)
device = "cuda" if torch.cuda.is_available() else "cpu"
config = json.loads((input_dir / "config.json").read_text())
quantization_config = config.pop("quantization_config", {})
if quantization_config.get("scale_fmt") == "ue8m0":
raise ValueError("ue8m0 scales are not supported - only plain float weight_scale_inv checkpoints")
block_size = tuple(quantization_config.get("weight_block_size", [128, 128]))
index_path = input_dir / "model.safetensors.index.json"
scale_to_shard = json.loads(index_path.read_text())["weight_map"] if index_path.exists() else {}
# Scales can live in a different shard than their weight; cache the most
# recently opened shards to avoid re-reading them per tensor.
shard_cache: dict[str, dict[str, torch.Tensor]] = {}
def get_scales(name: str, current_shard: str) -> torch.Tensor:
shard_name = scale_to_shard.get(name, current_shard)
if shard_name not in shard_cache:
with safe_open(input_dir / shard_name, framework="pt", device=device) as f:
shard_cache[shard_name] = {key: f.get_tensor(key) for key in f.keys()}
while len(shard_cache) > 2:
shard_cache.pop(next(iter(shard_cache)))
if name not in shard_cache[shard_name]:
raise KeyError(f"Missing {name} for fp8 tensor {name.removesuffix('_scale_inv')}")
return shard_cache[shard_name][name]
weight_map: dict[str, str] = {}
total_size = 0
num_dequantized = 0
for shard_name in list_shards(input_dir):
out_shard: dict[str, torch.Tensor] = {}
with safe_open(input_dir / shard_name, framework="pt", device=device) as f:
for name in f.keys():
if name.endswith("_scale_inv"):
continue
tensor = f.get_tensor(name)
if tensor.element_size() == 1:
scales = get_scales(name + "_scale_inv", shard_name)
out_shard[name] = dequantize_blockwise(tensor, scales, block_size).cpu()
num_dequantized += 1
else:
out_shard[name] = tensor.cpu()
for name, tensor in out_shard.items():
weight_map[name] = shard_name
total_size += tensor.nbytes
save_file(out_shard, output_dir / shard_name, metadata={"format": "pt"})
print(f"Dequantized {shard_name} ({num_dequantized} tensors so far)")
if num_dequantized == 0:
raise ValueError(f"No fp8 weights found in {input_dir} - is this an fp8 checkpoint?")
index = {"metadata": {"total_size": total_size}, "weight_map": weight_map}
(output_dir / "model.safetensors.index.json").write_text(json.dumps(index, indent=2, sort_keys=True) + "\n")
for path in input_dir.iterdir():
if (
path.is_file()
and path.suffix != ".safetensors"
and path.name not in ("model.safetensors.index.json", "config.json")
):
shutil.copyfile(path, output_dir / path.name)
(output_dir / "config.json").write_text(json.dumps(config, indent=2) + "\n")
print(f"Done: {num_dequantized} weights dequantized -> {output_dir}")
if __name__ == "__main__":
main()
Generated
+1 -1
View File
@@ -4964,7 +4964,7 @@ dev = [
[[package]]
name = "prime-rl"
version = "0.8.0"
version = "0.9.0"
source = { editable = "." }
dependencies = [
{ name = "aiolimiter" },