Compare commits

...
Author SHA1 Message Date
S1ro1 6f7f8c0b2a ci: derive the NVFP4 experiment image 2026-07-22 16:26:16 -07:00
S1ro1 560cf1a86b experiment: add NVFP4 RL validation image 2026-07-22 16:17:39 -07:00
440b3afaa8 fix(trainer): use UE8M0 FP8 scales only on SM100 (#3112)
#3022 flipped use_ue8m0 to True unconditionally to support DeepGEMM on
SM100, which also switched SM90 to power-of-2-rounded scale factors —
a pure precision loss on Hopper. On a GLM-5.2 RL prod run this doubled
trainer/inference mismatch KL (0.0038 -> 0.0059 at step 1, verified
A/B on an identical batch: same tokens and inference logprobs read
0.0059 with UE8M0 and 0.0038 with float scales).

Derive use_ue8m0 from the device (compute capability >= 10) so SM100
keeps the required UE8M0 recipe and SM90 returns to exact float scales.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 23:06:35 +02:00
f5946b098e feat: orchestrator owns v1 tasksets, ships task data to env servers (#3043)
* feat: orchestrator owns v1 tasksets, ships task data to env servers

Companion to PrimeIntellect-ai/verifiers#2039. A v1 env's taskset is loaded once,
in the orchestrator: finite tasksets become the train source's shuffled example
table (real tasks, not index ranges); an infinite taskset's generator is pulled
per example — no server-side materialization, no idx-addressed cache, no
requirement that every pool worker regenerate the same sequence. Each dispatched
rollout ships its task's data (task.data.full_dump()) and the env server
pydantic-validates and runs it.

The legacy (v0) bridge keeps its server-side dataset and task_idx addressing.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers to client-side-tasksets tip

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers to client-side-tasksets tip

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers to client-side-tasksets tip

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: plain model_dump task payload; bump deps/verifiers (full_dump removed)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: re-land client-side tasksets on the episode wire

Companion to the rebased PrimeIntellect-ai/verifiers#2039. A v1 env's taskset is
loaded once, in the orchestrator: finite tasksets become the train source's
shuffled example table (real tasks, not index ranges); an infinite taskset's
generator is pulled per example. Each dispatched env-rollout ships its task's
data (task.data.model_dump()) and the env server validates and runs it. The
legacy (v0) bridge keeps its server-side dataset, task_idx addressing, and the
run_group route.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers (non-optional taskset); drop redundant assert

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: actually drop the redundant taskset assert

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers (content-identity resume)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers (simplified task_key)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers to main (client-side tasksets merged, vf#2039)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: one Env.tasks iterator instead of tasks/task_iter

Finite tasksets still materialize at start() (num_tasks needs the count and the
train source shuffles epochs), but the field is a single iterator either way —
consumers pull it uniformly and branch on num_tasks alone. Consumed once, by
TrainSource or EvalEnv.start.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 13:45:15 -07:00
cd00986f71 feat(monitor): add local file monitor (#3111)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 21:59:47 +02:00
208ea64308 chore: bump research-environments submodule to latest main (#3106)
* chore: bump research-environments submodule to latest main

Picks up the registry ref-cleanup wave: platform image naming convention
(openswe/tmax/terminal-lego/openthoughts-tblite/senior-swe-bench switched to
org-less platform refs, multiswe REGISTRY mapping removed) and the tmax Harbor
registry pointer bump.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: relock env versions for research-environments bump

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 10:22:17 +02:00
34 changed files with 3242 additions and 1807 deletions
+4 -1
View File
@@ -157,7 +157,10 @@ jobs:
uses: docker/build-push-action@v7
with:
context: .
file: ./Dockerfile.cuda
# This experiment tag derives from the immutable current-main arm64
# image and only bakes the pinned NVFP4 runtime. Main still uses
# Dockerfile.cuda; this workflow change exists solely on the tag.
file: ./Dockerfile.nvfp4-e2e
push: true
platforms: ${{ matrix.platform }}
tags: |
+4 -1
View File
@@ -88,6 +88,7 @@ COPY examples /app/examples
COPY k8s /app/k8s
COPY benchmarks/scripts /app/benchmarks/scripts
COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pretend-versions.sh
COPY scripts/patch-vllm-nvfp4-writable-scales.py /app/scripts/patch-vllm-nvfp4-writable-scales.py
# Use submodule git metadata from the build context when present. Docker copies
# only the submodule .git pointer files into /app/deps, so we temporarily link
@@ -108,7 +109,9 @@ RUN --mount=type=cache,target=/app/.cache/uv \
&& \
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
&& \
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "quack-kernels", "vllm", "vllm-router")]'
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "quack-kernels", "vllm", "vllm-router")]' \
&& \
/app/.venv/bin/python /app/scripts/patch-vllm-nvfp4-writable-scales.py
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
+21
View File
@@ -0,0 +1,21 @@
ARG BASE_IMAGE=ghcr.io/primeintellect-ai/prime-rl@sha256:a86004b9b44d43c8018633283ec0267c3339c0dac0e35a9957f48f0a6b56153c
FROM ${BASE_IMAGE}
USER root
COPY pyproject.toml /app/pyproject.toml
COPY uv.lock /app/uv.lock
COPY scripts/patch-vllm-nvfp4-writable-scales.py /app/scripts/patch-vllm-nvfp4-writable-scales.py
COPY k8s/experiments/run_nvfp4_inference.sh /app/k8s/experiments/run_nvfp4_inference.sh
RUN uv --no-config pip install \
--python /app/.venv/bin/python \
--upgrade \
--no-deps \
'https://wheels.vllm.ai/910cc8543a6907c9cc87c417f8f2420969278bf5/vllm-0.23.1rc1.dev1392%2Bg910cc8543-cp38-abi3-manylinux_2_28_aarch64.whl' \
'https://github.com/flashinfer-ai/flashinfer/releases/download/v0.6.15.post1/flashinfer_python-0.6.15.post1-py3-none-any.whl' \
'https://github.com/flashinfer-ai/flashinfer/releases/download/v0.6.15.post1/flashinfer_cubin-0.6.15.post1-py3-none-any.whl' \
&& /app/.venv/bin/python /app/scripts/patch-vllm-nvfp4-writable-scales.py \
&& /app/.venv/bin/python -c 'from importlib.metadata import version; expected={"vllm":"0.23.1rc1.dev1392+g910cc8543","flashinfer-python":"0.6.15.post1","flashinfer-cubin":"0.6.15.post1"}; actual={name:version(name) for name in expected}; assert actual == expected, (actual, expected)'
USER appuser
@@ -0,0 +1,507 @@
#!/usr/bin/env python3
"""Exercise Prime's layerwise reload path with vLLM online NVFP4 weights."""
from __future__ import annotations
import argparse
import hashlib
import importlib.metadata
import json
import math
import os
import time
from functools import partial
from pathlib import Path
from typing import Any, Iterable
DEFAULT_MODEL = "Qwen/Qwen3-30B-A3B-Instruct-2507"
EXPERT_WEIGHT_SUFFIXES = (
".gate_proj.weight",
".up_proj.weight",
".down_proj.weight",
)
KERNEL_WEIGHT_NAMES = {"w13_weight", "w2_weight"}
KERNEL_DERIVED_NAMES = {
"g1_scale_c",
"gemm1_alpha",
"gemm1_beta",
"gemm1_clamp_limit",
}
def _package_version(name: str) -> str:
try:
return importlib.metadata.version(name)
except importlib.metadata.PackageNotFoundError:
return "not-installed"
def environment_probe() -> dict[str, Any]:
import torch
import vllm
from vllm._custom_ops import scaled_fp4_quant
from vllm.model_executor.layers.quantization.online.nvfp4 import (
Nvfp4OnlineMoEMethod,
)
from vllm.utils.flashinfer import has_flashinfer_trtllm_fused_moe
from prime_rl.inference.vllm.worker.weight_transfer import (
load_weights_checkpoint_layerwise,
)
if not torch.cuda.is_available():
raise RuntimeError("CUDA is unavailable")
capability = torch.cuda.get_device_capability()
if capability[0] != 10:
raise RuntimeError(f"online NVFP4 requires SM100, found SM{capability[0]}{capability[1]}")
if not has_flashinfer_trtllm_fused_moe():
raise RuntimeError("FlashInfer TRTLLM fused MoE is unavailable")
source = torch.arange(256, device="cuda", dtype=torch.bfloat16).reshape(16, 16)
scale = torch.ones((), device="cuda", dtype=torch.float32)
packed, block_scales = scaled_fp4_quant(
source,
scale,
is_sf_swizzled_layout=False,
)
torch.cuda.synchronize()
return {
"torch": _package_version("torch"),
"torch_cuda": torch.version.cuda,
"vllm": _package_version("vllm"),
"vllm_module": str(Path(vllm.__file__).resolve()),
"flashinfer_python": _package_version("flashinfer-python"),
"flashinfer_cubin": _package_version("flashinfer-cubin"),
"gpu": torch.cuda.get_device_name(),
"compute_capability": list(capability),
"nvfp4_method": f"{Nvfp4OnlineMoEMethod.__module__}.{Nvfp4OnlineMoEMethod.__name__}",
"prime_reload_helper": (
f"{load_weights_checkpoint_layerwise.__module__}.{load_weights_checkpoint_layerwise.__name__}"
),
"scaled_fp4_quant": {
"packed_shape": list(packed.shape),
"packed_dtype": str(packed.dtype),
"block_scale_shape": list(block_scales.shape),
"block_scale_dtype": str(block_scales.dtype),
},
"persistent_cache": {
"hit": os.environ.get("NVFP4_CACHE_HIT") == "1",
"key": os.environ.get("NVFP4_CACHE_KEY"),
"marker": os.environ.get("NVFP4_CACHE_READY_MARKER"),
},
}
def _mark_persistent_cache_ready() -> None:
"""Mark the versioned JIT cache reusable after engine warmup succeeds."""
marker_value = os.environ.get("NVFP4_CACHE_READY_MARKER")
cache_key = os.environ.get("NVFP4_CACHE_KEY")
if not marker_value or not cache_key:
return
marker = Path(marker_value)
marker.parent.mkdir(parents=True, exist_ok=True)
temporary = marker.with_name(f".{marker.name}.{os.getpid()}.tmp")
temporary.write_text(cache_key + "\n")
os.replace(temporary, marker)
def _get_worker_model(worker: Any):
model_runner = worker.model_runner
get_model = getattr(model_runner, "get_model", None)
model = get_model() if callable(get_model) else model_runner.model
return getattr(model, "runnable", model)
def _is_expert_weight(name: str, layer_index: int) -> bool:
marker = f"model.layers.{layer_index}.mlp.experts."
return name.startswith(marker) and name.endswith(EXPERT_WEIGHT_SUFFIXES)
def _reload_checkpoint(
worker: Any,
*,
model_path: str,
mutation_layer: int | None,
) -> dict[str, Any]:
"""Worker-side reload through Prime's production checkpoint-format helper."""
import torch
from torch.nn import Module
from vllm.model_executor.model_loader import DefaultModelLoader, get_model_loader
from prime_rl.inference.vllm.worker.weight_transfer import (
load_weights_checkpoint_layerwise,
)
model = _get_worker_model(worker)
if not isinstance(model, Module):
raise TypeError(f"expected torch Module, got {type(model)!r}")
model_loader = get_model_loader(worker.load_config)
if not isinstance(model_loader, DefaultModelLoader):
raise TypeError(f"expected DefaultModelLoader, got {type(model_loader)!r}")
source = DefaultModelLoader.Source(
model_path,
revision=None,
prefix="",
fall_back_to_pt=getattr(model, "fall_back_to_pt_during_load", True),
allow_patterns_overrides=getattr(model, "allow_patterns_overrides", None),
)
source_iterator = model_loader._get_weights_iterator(source)
stats: dict[str, Any] = {
"mutated_tensors": 0,
"mutated_numel": 0,
"mutated_names": [],
}
def transformed_weights() -> Iterable[tuple[str, torch.Tensor]]:
for name, tensor in source_iterator:
if mutation_layer is not None and _is_expert_weight(name, mutation_layer):
stats["mutated_tensors"] += 1
stats["mutated_numel"] += tensor.numel()
if len(stats["mutated_names"]) < 12:
stats["mutated_names"].append(name)
# Negation changes every non-zero packed FP4 value without
# creating the degenerate all-zero activation path. That
# keeps this test focused on reload/restore correctness.
yield name, tensor.neg()
else:
yield name, tensor
started = time.perf_counter()
load_weights_checkpoint_layerwise(
model,
transformed_weights(),
worker.model_runner.model_config,
worker.vllm_config,
)
torch.cuda.synchronize()
stats["elapsed_seconds"] = time.perf_counter() - started
if mutation_layer is not None:
num_experts = int(worker.model_runner.model_config.hf_text_config.num_experts)
expected_tensors = num_experts * len(EXPERT_WEIGHT_SUFFIXES)
if stats["mutated_tensors"] != expected_tensors:
raise RuntimeError(f"mutated {stats['mutated_tensors']} expert tensors, expected {expected_tensors}")
return stats
def _sample_tensor(tensor: Any, sample_size: int = 8192) -> dict[str, Any]:
import torch
value = tensor.detach()
if not value.is_contiguous():
value = value.contiguous()
raw = value.view(torch.uint8).reshape(-1)
count = min(sample_size, raw.numel())
if count:
indices = torch.linspace(
0,
raw.numel() - 1,
steps=count,
device=raw.device,
dtype=torch.float64,
).to(torch.long)
sample = raw[indices].to(device="cpu", dtype=torch.uint8)
payload = bytes(sample.tolist())
else:
payload = b""
return {
"shape": list(tensor.shape),
"dtype": str(tensor.dtype),
"device": str(tensor.device),
"nbytes": tensor.numel() * tensor.element_size(),
"data_ptr": tensor.data_ptr(),
"sample_bytes": len(payload),
"sample_nonzero": sum(byte != 0 for byte in payload),
"sample_sha256": hashlib.sha256(payload).hexdigest(),
"sample_prefix": list(payload[:16]),
}
def _probe_model(model: Any, *, layer_index: int) -> dict[str, Any]:
import torch
model = getattr(model, "runnable", model)
marker = f"model.layers.{layer_index}.mlp.experts"
tensors: dict[str, Any] = {}
for name, tensor in model.named_parameters():
leaf = name.rsplit(".", 1)[-1]
if marker in name and (
leaf.startswith(("w13_", "w2_")) or leaf in KERNEL_DERIVED_NAMES
):
tensors[name] = tensor
for name, tensor in model.named_buffers():
leaf = name.rsplit(".", 1)[-1]
if marker in name and (
leaf.startswith(("w13_", "w2_")) or leaf in KERNEL_DERIVED_NAMES
):
tensors.setdefault(name, tensor)
if not tensors:
nearby = [name for name, _ in model.named_parameters() if marker in name]
raise RuntimeError(f"found no NVFP4 kernel tensors under {marker}; nearby={nearby[:20]}")
quant_methods: dict[str, str] = {}
kernel_references: dict[str, Any] = {}
for name, module in model.named_modules():
if marker not in name:
continue
method = getattr(module, "_quant_method", None)
if method is None:
method = getattr(module, "quant_method", None)
if method is not None:
quant_methods[name] = f"{type(method).__module__}.{type(method).__name__}"
quant_config = getattr(method, "moe_quant_config", None)
for attr in (
"g1_alphas",
"g2_alphas",
"a1_gscale",
"a2_gscale",
"w1_scale",
"w2_scale",
):
value = getattr(quant_config, attr, None)
if isinstance(value, torch.Tensor):
kernel_references[f"{name}.moe_quant_config.{attr}"] = _sample_tensor(value)
moe_kernel = getattr(method, "moe_kernel", None)
fused_experts = getattr(moe_kernel, "fused_experts", None)
for attr in KERNEL_DERIVED_NAMES:
value = getattr(fused_experts, attr, None)
if isinstance(value, torch.Tensor):
kernel_references[f"{name}.moe_kernel.fused_experts.{attr}"] = _sample_tensor(value)
if not any(value.endswith(".Nvfp4OnlineMoEMethod") for value in quant_methods.values()):
raise RuntimeError(f"layer {layer_index} is not using Nvfp4OnlineMoEMethod: {quant_methods}")
return {
"quant_methods": quant_methods,
"tensors": {name: _sample_tensor(tensor) for name, tensor in sorted(tensors.items())},
"kernel_references": dict(sorted(kernel_references.items())),
"cuda_memory": {
"allocated": torch.cuda.memory_allocated(),
"reserved": torch.cuda.memory_reserved(),
"max_allocated": torch.cuda.max_memory_allocated(),
"max_reserved": torch.cuda.max_memory_reserved(),
},
}
def _generation_signature(llm: Any, prompt: str) -> dict[str, Any]:
from vllm import SamplingParams
params = SamplingParams(
temperature=0.0,
max_tokens=4,
logprobs=5,
seed=0,
)
request = llm.generate([prompt], params, use_tqdm=False)[0]
sequence = request.outputs[0]
chosen_logprobs: list[float | None] = []
for token_id, candidates in zip(sequence.token_ids, sequence.logprobs or []):
candidate = candidates.get(token_id)
chosen_logprobs.append(None if candidate is None else float(candidate.logprob))
return {
"token_ids": list(sequence.token_ids),
"text": sequence.text,
"cumulative_logprob": (None if sequence.cumulative_logprob is None else float(sequence.cumulative_logprob)),
"chosen_logprobs": chosen_logprobs,
}
def _kernel_leaf(name: str) -> str:
return name.rsplit(".", 1)[-1]
def _compare_phases(
baseline: dict[str, Any],
mutated: dict[str, Any],
restored: dict[str, Any],
baseline_generation: dict[str, Any],
mutated_generation: dict[str, Any],
restored_generation: dict[str, Any],
) -> dict[str, Any]:
baseline_tensors = baseline["tensors"]
mutated_tensors = mutated["tensors"]
restored_tensors = restored["tensors"]
if baseline_tensors.keys() != mutated_tensors.keys() or baseline_tensors.keys() != restored_tensors.keys():
raise RuntimeError("kernel tensor names changed across reload phases")
pointer_mismatches = [
name
for name in baseline_tensors
if not (
baseline_tensors[name]["data_ptr"]
== mutated_tensors[name]["data_ptr"]
== restored_tensors[name]["data_ptr"]
)
]
restore_hash_mismatches = [
name
for name in baseline_tensors
if baseline_tensors[name]["sample_sha256"] != restored_tensors[name]["sample_sha256"]
]
changed_kernel_weights = [
name
for name in baseline_tensors
if _kernel_leaf(name) in KERNEL_WEIGHT_NAMES
and baseline_tensors[name]["sample_sha256"] != mutated_tensors[name]["sample_sha256"]
]
kernel_weights = [name for name in baseline_tensors if _kernel_leaf(name) in KERNEL_WEIGHT_NAMES]
baseline_logprob = baseline_generation["cumulative_logprob"]
mutated_logprob = mutated_generation["cumulative_logprob"]
restored_logprob = restored_generation["cumulative_logprob"]
mutation_changed_output = baseline_generation["token_ids"] != mutated_generation["token_ids"] or (
baseline_logprob is not None
and mutated_logprob is not None
and not math.isclose(baseline_logprob, mutated_logprob, abs_tol=1e-5)
)
restored_output_matches = baseline_generation["token_ids"] == restored_generation["token_ids"]
if baseline_logprob is not None and restored_logprob is not None:
restored_output_matches = restored_output_matches and math.isclose(
baseline_logprob,
restored_logprob,
abs_tol=1e-5,
)
checks = {
"kernel_tensor_names_stable": True,
"kernel_storage_pointers_preserved": not pointer_mismatches,
"mutated_kernel_weights_changed": bool(kernel_weights) and len(changed_kernel_weights) == len(kernel_weights),
"restored_kernel_fingerprints_match": not restore_hash_mismatches,
"mutation_changed_generation": mutation_changed_output,
"restored_generation_matches": restored_output_matches,
}
return {
"passed": all(checks.values()),
"checks": checks,
"pointer_mismatches": pointer_mismatches,
"restore_hash_mismatches": restore_hash_mismatches,
"changed_kernel_weights": changed_kernel_weights,
}
def run_experiment(args: argparse.Namespace) -> dict[str, Any]:
from vllm import LLM
probe = environment_probe()
started = time.perf_counter()
llm = LLM(
model=args.model,
quantization="nvfp4_per_token",
dtype="bfloat16",
tensor_parallel_size=1,
enforce_eager=args.enforce_eager,
enable_prefix_caching=False,
max_model_len=args.max_model_len,
max_num_seqs=1,
gpu_memory_utilization=args.gpu_memory_utilization,
trust_remote_code=False,
disable_log_stats=True,
)
load_seconds = time.perf_counter() - started
_mark_persistent_cache_ready()
try:
baseline = llm.apply_model(partial(_probe_model, layer_index=args.layer))[0]
baseline_generation = _generation_signature(llm, args.prompt)
mutated_reload = llm.collective_rpc(
_reload_checkpoint,
timeout=args.reload_timeout,
kwargs={"model_path": args.model, "mutation_layer": args.layer},
)[0]
mutated = llm.apply_model(partial(_probe_model, layer_index=args.layer))[0]
mutated_generation = _generation_signature(llm, args.prompt)
restored_reload = llm.collective_rpc(
_reload_checkpoint,
timeout=args.reload_timeout,
kwargs={"model_path": args.model, "mutation_layer": None},
)[0]
restored = llm.apply_model(partial(_probe_model, layer_index=args.layer))[0]
restored_generation = _generation_signature(llm, args.prompt)
comparison = _compare_phases(
baseline,
mutated,
restored,
baseline_generation,
mutated_generation,
restored_generation,
)
return {
"status": "passed" if comparison["passed"] else "failed",
"environment": probe,
"configuration": {
"model": args.model,
"layer": args.layer,
"quantization": "nvfp4_per_token",
"enforce_eager": args.enforce_eager,
"max_model_len": args.max_model_len,
"gpu_memory_utilization": args.gpu_memory_utilization,
},
"initial_load_seconds": load_seconds,
"reloads": {
"mutated": mutated_reload,
"restored": restored_reload,
},
"generations": {
"baseline": baseline_generation,
"mutated": mutated_generation,
"restored": restored_generation,
},
"kernel_probes": {
"baseline": baseline,
"mutated": mutated,
"restored": restored,
},
"comparison": comparison,
}
finally:
shutdown = getattr(llm, "shutdown", None)
if callable(shutdown):
shutdown()
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--model", default=DEFAULT_MODEL)
parser.add_argument("--layer", type=int, default=0)
parser.add_argument("--prompt", default="The capital of France is")
parser.add_argument("--max-model-len", type=int, default=256)
parser.add_argument("--gpu-memory-utilization", type=float, default=0.5)
parser.add_argument("--reload-timeout", type=float, default=1800)
parser.add_argument("--enforce-eager", action=argparse.BooleanOptionalAction, default=True)
parser.add_argument("--environment-only", action="store_true")
parser.add_argument("--output", type=Path)
return parser.parse_args()
def main() -> None:
os.environ.setdefault("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
args = parse_args()
if args.environment_only:
result: dict[str, Any] = {"status": "passed", "environment": environment_probe()}
else:
result = run_experiment(args)
rendered = json.dumps(result, indent=2, sort_keys=True)
print(rendered, flush=True)
if args.output is not None:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(rendered + "\n")
if result["status"] != "passed":
raise RuntimeError("NVFP4 layerwise reload verification failed")
if __name__ == "__main__":
main()
+1 -1
+144
View File
@@ -0,0 +1,144 @@
apiVersion: batch/v1
kind: Job
metadata:
generateName: nvfp4-layerwise-
labels:
app.kubernetes.io/name: nvfp4-layerwise-reload
spec:
backoffLimit: 0
activeDeadlineSeconds: 10800
ttlSecondsAfterFinished: 86400
template:
metadata:
labels:
app.kubernetes.io/name: nvfp4-layerwise-reload
spec:
restartPolicy: Never
automountServiceAccountToken: false
imagePullSecrets:
- name: ghcr-secret
nodeSelector:
kubernetes.io/arch: arm64
nvidia.com/gpu.product: NVIDIA-GB200
containers:
- name: experiment
image: ghcr.io/primeintellect-ai/hosted-rl/prime-rl:v0.7.1.dev2-13-g91292f812-feat-convert-entrypoint
imagePullPolicy: IfNotPresent
securityContext:
runAsUser: 0
command: ["/bin/bash", "-lc"]
args:
- |
set -euo pipefail
vllm_wheel='https://wheels.vllm.ai/910cc8543a6907c9cc87c417f8f2420969278bf5/vllm-0.23.1rc1.dev1392%2Bg910cc8543-cp38-abi3-manylinux_2_28_aarch64.whl'
uv --no-config pip install \
--python /app/.venv/bin/python \
--upgrade \
--no-deps \
"$vllm_wheel" \
'https://github.com/flashinfer-ai/flashinfer/releases/download/v0.6.15.post1/flashinfer_python-0.6.15.post1-py3-none-any.whl' \
'https://github.com/flashinfer-ai/flashinfer/releases/download/v0.6.15.post1/flashinfer_cubin-0.6.15.post1-py3-none-any.whl'
if [[ -n "${PRIME_RL_VLLM_PYTHON_OVERLAY:-}" ]]; then
site_packages=$(/app/.venv/bin/python -c 'import site; print(site.getsitepackages()[0])')
cp -a "${PRIME_RL_VLLM_PYTHON_OVERLAY}/vllm/." "${site_packages}/vllm/"
fi
export NVFP4_CACHE_HIT=0
if [[ -f "${NVFP4_CACHE_READY_MARKER}" ]] && \
[[ "$(<"${NVFP4_CACHE_READY_MARKER}")" == "${NVFP4_CACHE_KEY}" ]]; then
# The image recreates /app/.venv for every pod. Its wheel sources
# are byte-identical for this exact cache key, but receive fresh
# mtimes, which otherwise makes Ninja rebuild cached objects.
find "${FLASHINFER_WORKSPACE_BASE}" \
-type f \( -name '*.so' -o -name '*.o' -o -name '*.a' \) \
-exec touch {} +
export NVFP4_CACHE_HIT=1
echo "Reusing persistent NVFP4 JIT cache: ${NVFP4_CACHE_KEY}"
fi
export PYTHONPATH="${PRIME_RL_SOURCE}/src${PYTHONPATH:+:${PYTHONPATH}}"
probe_args=()
if [[ "${NVFP4_ENVIRONMENT_ONLY}" == "1" ]]; then
probe_args+=(--environment-only)
fi
cd /app
VIRTUAL_ENV=/app/.venv uv run --active --no-sync python \
"${PRIME_RL_SOURCE}/benchmarks/scripts/nvfp4_layerwise_reload.py" \
"${probe_args[@]}" \
--output "/workspace/results/${POD_NAME}.json"
env:
- name: PRIME_RL_SOURCE
value: /workspace/live
- name: NVFP4_ENVIRONMENT_ONLY
value: "${NVFP4_ENVIRONMENT_ONLY}"
- name: PRIME_RL_VLLM_PYTHON_OVERLAY
value: /workspace/vllm-fixes/fix-nvfp4-reload-writable-scales
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: HF_HOME
value: /tmp/huggingface
- name: HF_HUB_CACHE
value: /model-cache
- name: HF_HUB_OFFLINE
value: "1"
- name: TRANSFORMERS_OFFLINE
value: "1"
- name: HF_HUB_DISABLE_XET
value: "1"
- name: HF_HUB_DOWNLOAD_TIMEOUT
value: "1800"
- name: HF_HUB_ETAG_TIMEOUT
value: "300"
- name: UV_CACHE_DIR
value: /workspace/.cache/uv/arm64
- name: UV_LINK_MODE
value: copy
# Keep generated kernels across Jobs. The versioned root prevents a
# vLLM/FlashInfer/Torch or compiler upgrade from reusing stale code.
- name: FLASHINFER_WORKSPACE_BASE
value: /workspace/.cache/nvfp4/sm100a/vllm-910cc8543-flashinfer-0.6.15.post1-torch-2.11.0-cu128-gcc13
- name: VLLM_CACHE_ROOT
value: /workspace/.cache/nvfp4/sm100a/vllm-910cc8543-flashinfer-0.6.15.post1-torch-2.11.0-cu128-gcc13/vllm
- name: TORCH_EXTENSIONS_DIR
value: /workspace/.cache/nvfp4/sm100a/vllm-910cc8543-flashinfer-0.6.15.post1-torch-2.11.0-cu128-gcc13/torch-extensions
- name: TRITON_CACHE_DIR
value: /workspace/.cache/nvfp4/sm100a/vllm-910cc8543-flashinfer-0.6.15.post1-torch-2.11.0-cu128-gcc13/triton
- name: CUDA_CACHE_PATH
value: /workspace/.cache/nvfp4/sm100a/vllm-910cc8543-flashinfer-0.6.15.post1-torch-2.11.0-cu128-gcc13/cuda
- name: NVFP4_CACHE_KEY
value: image-91292f812_sm100a_cuda12.8_torch2.11.0_vllm-910cc8543_flashinfer-0.6.15.post1
- name: NVFP4_CACHE_READY_MARKER
value: /workspace/.cache/nvfp4/sm100a/vllm-910cc8543-flashinfer-0.6.15.post1-torch-2.11.0-cu128-gcc13/.prime-rl-ready
- name: VLLM_ALLOW_INSECURE_SERIALIZATION
value: "1"
- name: TOKENIZERS_PARALLELISM
value: "false"
resources:
requests:
cpu: "16"
memory: 96Gi
nvidia.com/gpu: "1"
limits:
cpu: "64"
memory: 256Gi
nvidia.com/gpu: "1"
volumeMounts:
- name: source
mountPath: /workspace
- name: model-cache
mountPath: /model-cache
readOnly: true
- name: dshm
mountPath: /dev/shm
volumes:
- name: source
persistentVolumeClaim:
claimName: prime-rl-dev-source
- name: model-cache
hostPath:
path: /scratch/model-cache
type: Directory
- name: dshm
emptyDir:
medium: Memory
sizeLimit: 32Gi
@@ -0,0 +1,110 @@
output_dir = "/data/nvfp4-e2e/runs/qwen3-30b-a3b-instruct-4x4"
max_steps = 20
seq_len = 8192
clean_output_dir = true
[log]
level = "info"
[model]
name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
[weight_broadcast]
type = "nccl"
timeout = 7200
quantize_in_weight_transfer = false
# The k8s launcher maps these two counts to separate, full-node pods. The
# aggregate gpus_per_node value only satisfies prime-rl's single-node schema;
# each GB200 node physically has four GPUs.
[deployment]
type = "single_node"
num_train_gpus = 4
num_infer_gpus = 4
gpus_per_node = 8
[trainer]
dist_timeout_seconds = 7200
[trainer.file_monitor]
filename = "trainer-metrics.jsonl"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
ep = 4
ep_comm_backend = "torch"
optim_cpu_offload = true
fsdp_cpu_offload = false
ac_offloading = "None"
conversion_dir = "/data/nvfp4-e2e/model-conversions/qwen3-30b-a3b-instruct-2507"
fused_lm_head_token_chunk_size = 1024
[trainer.model.ac]
mode = "full"
freq = 1
[trainer.model.compile]
[trainer.optim]
type = "sign_sgd"
lr = 1e-6
weight_decay = 0.0
max_norm = 1.0
[trainer.loss]
type = "default"
kl_tau = 0.001
[orchestrator]
batch_size = 64
group_size = 8
oversampling_factor = 1.0
max_off_policy_steps = 0
post_batch_filters = []
collect_inference_metrics = true
[orchestrator.file_monitor]
filename = "orchestrator-metrics.jsonl"
[orchestrator.model.client]
wait_for_ready_timeout = 10800
[orchestrator.renderer]
name = "qwen3"
enable_thinking = false
[orchestrator.train.sampling]
temperature = 1.0
max_completion_tokens = 2048
[[orchestrator.train.env]]
name = "math"
env.taskset = { id = "i3_math_v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[inference]
quantization = "nvfp4_per_token"
gpu_memory_utilization = 0.85
enable_prefix_caching = true
[inference.model]
dtype = "bfloat16"
max_model_len = 8192
# Establish the RL/weight-transfer baseline before separately validating
# online-NVFP4 reloads under captured CUDA graphs.
enforce_eager = true
[inference.parallel]
tp = 4
[k8s]
release = "nvfp4-qwen3-e2e-4x4"
namespace = "dev-matej"
create_namespace = false
chart = "../fft/charts/prime-rl-fft"
example = "nvfp4-qwen3-e2e-4x4"
values_out = "k8s/experiments/nvfp4-qwen3-e2e-4x4.generated.values.yaml"
overlays = [
"k8s/experiments/nvfp4-qwen3-e2e-4x4.values.yaml",
]
@@ -0,0 +1,131 @@
weightBroadcast:
type: nccl
port: 29501
trainer:
replicas: 1
gpu:
enabled: true
count: 4
autoStart: true
inference:
enabled: true
islands: 1
podsPerIsland: 1
gpu:
enabled: true
count: 4
autoStart: true
tp: 4
router:
enabled: true
scope: global
policy: consistent_hash
backendPort: 8001
orchestrator:
enabled: true
autoStart: true
command: uv run --no-sync orchestrator @ /etc/prime-rl/orchestrator.toml
resumeCleanup:
enabled: true
outputDir: /data/nvfp4-e2e/runs/qwen3-30b-a3b-instruct-4x4
configs:
trainer: "output_dir = \"/data/nvfp4-e2e/runs/qwen3-30b-a3b-instruct-4x4\"\nmatmul_precision = \"high\"\nmax_steps = 20\nenable_router_replay = false\ndist_timeout_seconds = 7200\nmax_concurrent_runs = 1\nenable_token_export = false\n\n[model]\nname = \"Qwen/Qwen3-30B-A3B-Instruct-2507\"\ntrust_remote_code = false\nconversion_dir = \"/data/nvfp4-e2e/model-conversions/qwen3-30b-a3b-instruct-2507\"\nseq_len = 8192\nattn = \"flash_attention_3\"\nfsdp_cpu_offload = false\noptim_cpu_offload = true\nreshard_after_forward = true\ndp_replicate = 1\nep = 4\nep_comm_backend = \"torch\"\ndeepep_num_sms = 20\ncp = 1\ncp_style = \"ring\"\nimpl = \"custom\"\noptimization_dtype = \"float32\"\nreduce_dtype = \"float32\"\nmoe_router_dtype = \"float32\"\nmoe_use_grouped_mm = true\nfreeze_moe_router = false\nfused_lm_head_token_chunk_size = 1024\n\n[model.compile]\nfullgraph = false\n\n[model.ac]\nmode = \"full\"\nfreq = 1\ntargets = [\n \"norm\",\n]\n\n[model.debug]\nrandom_init = false\nforce_balanced_routing = false\n\n[tokenizer]\nname = \"Qwen/Qwen3-30B-A3B-Instruct-2507\"\ntrust_remote_code = false\n\n[data]\n\n[loss]\ntype = \"default\"\ndppo_mask_low = 0.2\ndppo_mask_high = 0.2\nadv_tau = 1.0\nkl_tau = 0.001\n\n[optim]\nlr = 1e-06\nweight_decay = 0.0\nmax_norm = 1.0\ntype = \"sign_sgd\"\n\n[scheduler]\ntype = \"constant\"\n\n[weight_broadcast]\nhost = \"localhost\"\nport = 29501\ntimeout = 7200\ninference_world_size = 4\ntype = \"nccl\"\nquantize_in_weight_transfer = false\n\n[rollout_transport]\ntype = \"filesystem\"\n\n[log]\nlevel = \"info\"\nvf_level = \"info\"\njson_logging = false\nlog_data = false\ninterval = 10.0\nranks_filter = [\n 0,\n]\n\n[file_monitor]\nfilename = \"trainer-metrics.jsonl\"\n\n[gc]\ninterval = 50\n\n[env_vars]\n"
orchestrator: "pre_batch_filters = [\n { type = \"gibberish\", enforce = false, token_id_threshold = 100000, logprob_offset = 2.0 },\n { type = \"repetition\", enforce = false, window = 3000, prob_threshold = 0.99 },\n { type = \"zero_advantage\", enforce = false },\n]\npost_batch_filters = []\ncollect_inference_metrics = true\noutput_dir = \"/data/nvfp4-e2e/runs/qwen3-30b-a3b-instruct-4x4/run_default\"\nbatch_size = 64\noversampling_factor = 1.0\nmax_inflight_rollouts = 64\ngroup_size = 8\nseq_len = 8192\nnum_train_workers = 4\nmax_steps = 20\nmax_off_policy_steps = 0\nbench = false\n\n[algo]\ntype = \"grpo\"\n\n[algo.sampling]\nsource = \"policy\"\n\n[model]\nname = \"Qwen/Qwen3-30B-A3B-Instruct-2507\"\ntrust_remote_code = false\n\n[model.client]\nwait_for_ready_timeout = 10800\nbase_url = [\n \"http://nvfp4-qwen3-e2e-4x4-inference-0.nvfp4-qwen3-e2e-4x4-inference.dev-matej.svc.cluster.local:8000/v1\",\n]\napi_key_var = \"VLLM_API_KEY\"\nskip_model_check = false\ndp_rank_count = 1\nadmin_base_url = [\n \"http://nvfp4-qwen3-e2e-4x4-inference-0.nvfp4-qwen3-e2e-4x4-inference.dev-matej.svc.cluster.local:8000/v1\",\n]\n\n[model.client.headers]\n\n[model.client.headers_from_env]\n\n[model.client.extra_headers_from_state]\nX-Session-ID = \"trajectory_id\"\n\n[[train.env]]\nname = \"math\"\n\n[train.env.env.taskset]\nid = \"i3_math_v1\"\n\n[train.env.env.agent.harness]\nid = \"null\"\n\n[train.env.env.agent.harness.runtime]\ntype = \"subprocess\"\n\n[train.sampling]\ntemperature = 1.0\nmax_completion_tokens = 2048\n\n[train.sampling.extra_body]\n\n[tokenizer]\nname = \"Qwen/Qwen3-30B-A3B-Instruct-2507\"\ntrust_remote_code = false\n\n[renderer]\nname = \"qwen3\"\nenable_thinking = false\n\n[optim]\nlr = 0.0001\n\n[log]\nlevel = \"info\"\nvf_level = \"info\"\njson_logging = false\nlog_data = false\ninterval = 10.0\n\n[env_vars]\n\n[file_monitor]\nfilename = \"orchestrator-metrics.jsonl\"\n\n[weight_broadcast]\nhost = \"localhost\"\nport = 29501\ntimeout = 7200\ninference_world_size = 4\ntype = \"nccl\"\nquantize_in_weight_transfer = false\n\n[rollout_transport]\ntype = \"filesystem\"\n"
inference: 'enable_lora = false
max_loras = 8
max_cpu_loras = 100
enable_prefix_caching = true
gpu_memory_utilization = 0.85
quantization = "nvfp4_per_token"
api_server_count = 1
data_parallel_rpc_port = 13345
seed = 0
enable_expert_parallel = false
all2all_backend = "allgather_reducescatter"
enable_eplb = false
enable_dbo = false
use_deep_gemm = false
use_pd_kv_transfer = false
enable_return_routed_experts = false
enable_fp32_lm_head = true
enable_fp32_router_logits = true
[server]
port = 8000
liveness_timeout_seconds = 30.0
[model]
name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
trust_remote_code = false
dtype = "bfloat16"
max_model_len = 8192
enforce_eager = true
tool_call_parser = "hermes"
[parallel]
tp = 4
dp = 1
[log]
level = "info"
vf_level = "info"
json_logging = false
log_data = false
interval = 10.0
[env_vars]
[weight_broadcast]
type = "nccl"
[vllm_extra]
'
config:
example: nvfp4-qwen3-e2e-4x4
secrets:
enabled: true
name: prime-rl-secrets
image:
repository: docker.io/primeintellect/prime-rl
tag: commit-e96bbae
@@ -0,0 +1,120 @@
runId: nvfp4-qwen3-e2e-4x4
imagePullSecrets:
- name: ghcr-secret
image:
repository: ghcr.io/primeintellect-ai/prime-rl
tag: nvfp4-e2e.dev1-arm64
pullPolicy: IfNotPresent
devSource:
enabled: false
# Reuse the large RWX PVC for run output and the one-time trainer-native model
# conversion. The root was provisioned world-writable by the dev workspace.
storage:
enabled: true
existingClaim: model-cache
mountPath: /data
fixPermissions: false
# The HF snapshot is already present on every GB200 node.
modelCache:
enabled: true
type: hostPath
hostPath: /scratch/model-cache
subPath: ""
mountPath: /model-cache
readOnly: true
offline: true
# Mount the exact cache populated by the successful SM100 layerwise test.
inferenceCache:
enabled: true
existingClaim: prime-rl-dev-source
subPath: .cache/nvfp4/sm100a/vllm-910cc8543-flashinfer-0.6.15.post1-torch-2.11.0-cu128-gcc13
mountPath: /inference-cache
weightBroadcast:
type: nccl
port: 29501
inferenceWorldSize: 4
orchestrator:
runAsRoot: true
resources:
requests:
cpu: "4"
memory: 16Gi
nodeSelector:
kubernetes.io/arch: arm64
nvidia.com/gpu.product: NVIDIA-GB200
trainer:
hostNetwork: true
resources:
requests:
cpu: "64"
memory: 640Gi
rdma:
enabled: true
deviceName: rdma/rdma_shared_device_a
count: 1
nodeSelector:
kubernetes.io/arch: arm64
nvidia.com/gpu.product: NVIDIA-GB200
env: &nccl-env
- name: NCCL_IB_HCA
value: mlx5_2
- name: NCCL_CROSS_NIC
value: "0"
- name: VLLM_RPC_TIMEOUT
value: "7200000"
- name: TRANSFORMERS_OFFLINE
value: "1"
inference:
# Avoid the auxiliary vllm-router for this one TP=4 server.
router:
enabled: false
hostNetwork: true
command: bash /app/k8s/experiments/run_nvfp4_inference.sh
resources:
requests:
cpu: "64"
memory: 384Gi
rdma:
enabled: true
deviceName: rdma/rdma_shared_device_a
count: 1
nodeSelector:
kubernetes.io/arch: arm64
nvidia.com/gpu.product: NVIDIA-GB200
env:
- name: NCCL_IB_HCA
value: mlx5_2
- name: NCCL_CROSS_NIC
value: "0"
- name: VLLM_RPC_TIMEOUT
value: "7200000"
- name: TRANSFORMERS_OFFLINE
value: "1"
- name: VLLM_ALLOW_INSECURE_SERIALIZATION
value: "1"
- name: TOKENIZERS_PARALLELISM
value: "false"
- name: UV_CACHE_DIR
value: /inference-cache/uv
- name: UV_LINK_MODE
value: copy
- name: VLLM_CACHE_ROOT
value: /inference-cache/vllm
- name: TORCH_EXTENSIONS_DIR
value: /inference-cache/torch-extensions
- name: CUDA_CACHE_PATH
value: /inference-cache/cuda
- name: NVFP4_CACHE_KEY
value: image-91292f812_sm100a_cuda12.8_torch2.11.0_vllm-910cc8543_flashinfer-0.6.15.post1
- name: NVFP4_CACHE_READY_MARKER
value: /inference-cache/.prime-rl-ready
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env bash
set -euo pipefail
# Pin the process environment explicitly. The Helm chart also supplies generic
# cache defaults; these versioned paths are the authoritative values for this
# exact runtime and avoid relying on duplicate-env ordering.
export UV_CACHE_DIR=/inference-cache/uv
export UV_LINK_MODE=copy
export FLASHINFER_WORKSPACE_BASE=/inference-cache
export VLLM_CACHE_ROOT=/inference-cache/vllm
export TORCH_EXTENSIONS_DIR=/inference-cache/torch-extensions
export TRITON_CACHE_DIR=/inference-cache/triton
export CUDA_CACHE_PATH=/inference-cache/cuda
# Verify that this is the immutable experiment image, including the approved
# writable-scale fix. Nothing is installed or modified in the pod.
/app/.venv/bin/python - <<'PY'
from importlib.metadata import version
from pathlib import Path
import vllm
expected = {
"vllm": "0.23.1rc1.dev1392+g910cc8543",
"flashinfer-python": "0.6.15.post1",
"flashinfer-cubin": "0.6.15.post1",
}
actual = {package: version(package) for package in expected}
if actual != expected:
raise RuntimeError(f"Unexpected NVFP4 runtime: {actual!r} != {expected!r}")
path = (
Path(vllm.__file__).parent
/ "model_executor/layers/quantization/utils/flashinfer_fp4_moe.py"
)
source = path.read_text()
for scale in ("a13_scale", "a2_scale"):
old = f"{scale}.max().to(torch.float32).expand(num_experts)"
new = f"{scale}.max().to(torch.float32).repeat(num_experts)"
if source.count(old) != 0 or source.count(new) != 2:
raise RuntimeError(f"Writable NVFP4 scale fix is absent or unexpected in {path}")
print(f"Verified pinned NVFP4 runtime and writable-scale fix in {path}")
PY
export NVFP4_CACHE_HIT=0
if [[ -f "$NVFP4_CACHE_READY_MARKER" ]] && \
[[ "$(<"$NVFP4_CACHE_READY_MARKER")" == "$NVFP4_CACHE_KEY" ]]; then
# Wheel extraction gives byte-identical CUDA sources fresh mtimes on every
# pod. Refresh cached build outputs so Ninja does not rebuild them solely
# because the source inode was recreated.
find "$FLASHINFER_WORKSPACE_BASE" \
-type f \( -name '*.so' -o -name '*.o' -o -name '*.a' \) \
-exec touch {} +
export NVFP4_CACHE_HIT=1
echo "Reusing persistent NVFP4 JIT cache: $NVFP4_CACHE_KEY"
else
# Mark the versioned cache ready only after the API health endpoint proves
# that model load, online quantization, and lazy kernel setup all succeeded.
(
for _ in $(seq 1 2400); do
if curl -fsS http://127.0.0.1:8000/health >/dev/null 2>&1; then
marker_tmp="${NVFP4_CACHE_READY_MARKER}.$$"
printf '%s\n' "$NVFP4_CACHE_KEY" >"$marker_tmp"
mv "$marker_tmp" "$NVFP4_CACHE_READY_MARKER"
echo "Marked persistent NVFP4 JIT cache ready: $NVFP4_CACHE_KEY"
exit 0
fi
sleep 5
done
echo "Inference did not become healthy; leaving cache unmarked" >&2
) &
fi
cd /app
exec uv run --active --no-sync inference @ /etc/prime-rl/inference.toml "$@"
@@ -14,6 +14,7 @@ from prime_rl.configs.shared import (
BaseModelConfig,
ClientConfig,
EnvVars,
FileMonitorConfig,
FileSystemTransportConfig,
HeartbeatConfig,
LogConfig,
@@ -493,6 +494,9 @@ class OrchestratorConfig(BaseConfig):
prime_monitor: PrimeMonitorConfig | None = None
file_monitor: FileMonitorConfig | None = None
"""Local JSONL metric sink. If set, orchestrator metrics are appended to ``<output_dir>/metrics.jsonl``."""
collect_inference_metrics: bool = True
"""Collect inference-server metrics (requires wandb)."""
@@ -20,6 +20,7 @@ from prime_rl.configs.orchestrator import (
)
from prime_rl.configs.shared import (
EnvVars,
FileMonitorConfig,
SlurmConfig,
VLMConfig,
)
@@ -242,6 +243,9 @@ class RLConfig(BaseConfig):
wandb: SharedWandbConfig | None = None
"""Shared W&B config. If None, falls back to the sub-config W&B settings."""
file_monitor: FileMonitorConfig | None = None
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/metrics.jsonl`` on both trainer and orchestrator. If None, falls back to the sub-config settings."""
model: SharedModelConfig | None = None
"""Shared model config. If None, falls back to the sub-config model settings."""
@@ -8,6 +8,7 @@ from renderers.base import MODEL_RENDERER_MAP
from prime_rl.configs.shared import (
EnvVars,
FileMonitorConfig,
HeartbeatConfig,
SlurmConfig,
TrainerLogConfig,
@@ -191,6 +192,9 @@ class SFTConfig(BaseConfig):
wandb: WandbConfig | None = None
file_monitor: FileMonitorConfig | None = None
"""Local JSONL metric sink. If set, metrics are appended to ``<output_dir>/metrics.jsonl``."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — checkpoints and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
@@ -221,6 +221,18 @@ class WandbWithExtrasConfig(WandbConfig):
"""Extras logging configuration. If None, no extras are logged."""
class FileMonitorConfig(BaseConfig):
"""Enable the local JSONL metric sink (``<output_dir>/metrics.jsonl``).
Present (non-None) enables it, mirroring the ``prime_monitor`` pattern. Metrics
are the same scalars sent to W&B; useful for self-hosted dashboards or when W&B
is disabled.
"""
filename: str = "metrics.jsonl"
"""Name of the JSONL file written under the component's ``output_dir``."""
class PrimeMonitorConfig(BaseConfig):
base_url: str = "https://api.primeintellect.ai/api/v1/rft"
"""Base URL for the Prime Intellect monitoring API."""
@@ -7,6 +7,7 @@ from pydantic import Field, model_validator
from prime_rl.configs.shared import (
BaseModelConfig,
EnvVars,
FileMonitorConfig,
FileSystemTransportConfig,
HeartbeatConfig,
MetricsServerConfig,
@@ -582,6 +583,9 @@ class TrainerConfig(BaseConfig):
wandb: WandbConfig | None = None
file_monitor: FileMonitorConfig | None = None
"""Local JSONL metric sink. If set, trainer metrics are appended to ``<output_dir>/metrics.jsonl``."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
@@ -106,6 +106,9 @@ def propagate_shared_fields(data: Any) -> Any:
propagate("wandb.tags", "trainer.wandb.tags", "orchestrator.wandb.tags")
propagate("wandb.offline", "trainer.wandb.offline", "orchestrator.wandb.offline")
# [file_monitor] leaf. (Bare empty ``[file_monitor]`` block enablement is at the end.)
propagate("file_monitor.filename", "trainer.file_monitor.filename", "orchestrator.file_monitor.filename")
# [tokenizer]. ``chat_template`` also flows to ``inference.model`` (vLLM's
# ``--chat-template``); ``name`` and ``trust_remote_code`` can legitimately
# differ between sub-configs (auto-derived from model names, which may
@@ -172,7 +175,7 @@ def propagate_shared_fields(data: Any) -> Any:
# (not ``is not None``) is what makes CLI ``--no-wandb`` / ``--no-ckpt``
# work — those land as the *string* ``"None"`` until ``BaseConfig``'s
# parent-class validator converts it, which happens after this one.
for key in ("ckpt", "wandb"):
for key in ("ckpt", "wandb", "file_monitor"):
if isinstance(get(key), dict):
fill(f"trainer.{key}", {})
fill(f"orchestrator.{key}", {})
+9 -3
View File
@@ -18,7 +18,9 @@ dependencies = [
"torchaudio",
"torchdata>=0.11.0",
"transformers==5.6.2",
"vllm>=0.24.0",
"vllm==0.23.1rc1.dev1392+g910cc8543",
"flashinfer-python==0.6.15.post1",
"flashinfer-cubin==0.6.15.post1",
"mooncake-transfer-engine>=0.3.10.post2",
"wandb>=0.26.1",
"wandb-workspaces>=0.4.3",
@@ -157,6 +159,8 @@ requires-dist = [
[tool.uv.exclude-newer-package]
# we want latest vllm, remove next patch
vllm = false
flashinfer-python = false
flashinfer-cubin = false
tokenspeed-mla = false
fastokens = false
flash_attn_3 = false
@@ -200,9 +204,11 @@ vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://wheels.vllm.ai/910cc8543a6907c9cc87c417f8f2420969278bf5/vllm-0.23.1rc1.dev1392%2Bg910cc8543-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://wheels.vllm.ai/910cc8543a6907c9cc87c417f8f2420969278bf5/vllm-0.23.1rc1.dev1392%2Bg910cc8543-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
flashinfer-python = { url = "https://github.com/flashinfer-ai/flashinfer/releases/download/v0.6.15.post1/flashinfer_python-0.6.15.post1-py3-none-any.whl" }
flashinfer-cubin = { url = "https://github.com/flashinfer-ai/flashinfer/releases/download/v0.6.15.post1/flashinfer_cubin-0.6.15.post1-py3-none-any.whl" }
deep-ep = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.1.0+1fd57b0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
@@ -0,0 +1,28 @@
"""Apply the approved writable-scale fix to the pinned vLLM wheel in an image.
The experiment intentionally builds from the exact upstream nightly wheel. The
fix is tiny but not yet present in that immutable wheel, so fail closed unless
the source matches the reviewed change exactly.
"""
from pathlib import Path
import vllm
path = Path(vllm.__file__).parent / "model_executor/layers/quantization/utils/flashinfer_fp4_moe.py"
source = path.read_text()
replacements = {
"a13_scale.max().to(torch.float32).expand(num_experts)": "a13_scale.max().to(torch.float32).repeat(num_experts)",
"a2_scale.max().to(torch.float32).expand(num_experts)": "a2_scale.max().to(torch.float32).repeat(num_experts)",
}
for old, new in replacements.items():
old_count = source.count(old)
new_count = source.count(new)
if (old_count, new_count) == (2, 0):
source = source.replace(old, new)
elif (old_count, new_count) != (0, 2):
raise RuntimeError(f"Unexpected vLLM source in {path}: {old_count=} {new_count=}")
path.write_text(source)
print(f"Applied writable NVFP4 MoE scale fix to {path}")
+8 -1
View File
@@ -387,6 +387,7 @@ class RolloutDispatcher:
kind=kind,
env_name=env_name,
task_idx=example["task_idx"],
task=example.get("task"),
rollouts_to_schedule=group_size,
target_rollouts=group_size,
eval_step=eval_step,
@@ -438,6 +439,7 @@ class RolloutDispatcher:
cache_salt = None
if env.requires_group_scoring:
# Legacy-only route (a v1 env never group-scores) — addressed by row.
permits = group.rollouts_to_schedule
group.rollouts_to_schedule = 0
await self.acquire(permits)
@@ -451,15 +453,20 @@ class RolloutDispatcher:
)
)
else:
# A v1 env takes the task itself; the legacy bridge its dataset row.
if group.task is not None:
addressing = {"task_data": group.task.data.model_dump(mode="json")}
else:
addressing = {"task_idx": group.task_idx}
permits = 1
group.rollouts_to_schedule -= 1
await self.acquire(permits)
task = asyncio.create_task(
env.run(
client=client,
task_idx=group.task_idx,
model_name=model_name,
cache_salt=cache_salt,
**addressing,
)
)
+66 -34
View File
@@ -2,15 +2,19 @@
Each ``Env`` owns a v1 ``EnvServer`` (spawned as a child process, or an
external one given by ``config.address``) and an ``EnvClient`` to drive it. The
orchestrator never *runs* an environment: it asks the server for ``info``
(``num_tasks`` + whether group scoring is needed), then runs rollouts purely by
**task index**. The server answers one ``Episode`` per env-rollout, whose traces
we validate into ``Trace[WireTaskData]`` — real ``vf.Trace``\\ s (never loose
dicts) whose task keeps the env's task-specific
fields as extras (``WireTaskData`` allows them). The orchestrator never imports the
env package: the env's *type* and *runtime* both live only in the server, and the orchestrator
drives it purely by task index. (Nothing here reads typed env task fields — only ``task.idx``
and a full ``task.model_dump``, both of which ``WireTaskData`` preserves.)
orchestrator never *runs* an environment — the agents and their runtimes live only
in the server — but it does own the *taskset*: a v1 env's tasks are loaded here,
once, and each dispatched env-rollout ships its task's data on the request
(``task_data``); the server pydantic-validates it into the taskset's declared
``TaskData`` type and runs it. That keeps the server (and every worker in its
pool) stateless about data — no per-worker dataset loads, no idx-addressed task
cache — and gives the orchestrator real tasks to cycle, shuffle, and filter. Only
the legacy (v0) bridge, whose dataset genuinely lives server-side, is still driven
by ``task_idx`` (its count comes from ``info``).
The server answers one ``Episode`` per env-rollout, whose traces we validate into
``Trace[WireTaskData]`` — real ``vf.Trace``\\ s (never loose dicts) whose task
keeps the env's task-specific fields as extras (``WireTaskData`` allows them).
"""
from __future__ import annotations
@@ -22,6 +26,7 @@ import os
import queue
import sys
from collections.abc import Iterator, Sequence
from itertools import islice
from multiprocessing.process import BaseProcess
from pathlib import Path
from typing import Generic, TypeVar
@@ -40,9 +45,8 @@ from prime_rl.utils.logger import get_logger
# task.idx + task.model_dump).
ROLLOUT_TYPE = Rollout[vf.WireTaskData]
# Max wait for a spawned env server to bind and report its address. The child
# loads the taskset (possibly downloading a dataset) before reporting, so this
# is generous.
# Max wait for a spawned env server to bind and report its address. A legacy
# child loads its dataset before reporting, so this is generous.
ENV_SERVER_SPAWN_TIMEOUT = 600.0
@@ -78,14 +82,20 @@ def _run_env_server(
class Env:
"""Wraps a v1 env server + client. The orchestrator never loads the env."""
"""Wraps a v1 env server + client. The orchestrator owns the taskset (loaded once,
client-side); the server owns agent/harness execution."""
def __init__(self, config: EnvConfig):
self.config = config
self.sampling_args: dict = {}
self.num_tasks: int | None = 0
"""Task count reported by the server; ``None`` means the taskset is infinite."""
"""Task count; ``None`` means the taskset is infinite."""
self.requires_group_scoring: bool = False
self.tasks: Iterator[vf.Task] | None = None
"""The env's tasks, client-side; ``None`` for legacy (its dataset lives on the
server). A finite taskset is materialized at ``start()`` (``num_tasks`` is its
count) and iterated from there; an infinite one streams off its generator.
Consumed once — by ``TrainSource`` (train) or ``EvalEnv.start`` (eval)."""
self._env_client: EnvClient | None = None
self._env_server_process: BaseProcess | None = None
@@ -100,25 +110,36 @@ class Env:
return self._env_client
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
"""Spawn the env server (if needed), connect, and cache its ``info``."""
"""Spawn the env server (if needed), connect, and load the taskset client-side
(legacy instead asks the server for ``info`` — its dataset is server-side)."""
external = self.config.address is not None
address = self.config.address or await self._spawn(log_dir, log_level or "INFO", json_logging)
get_logger().debug(f"Connecting {self.name} to env server {address}")
self._env_client = EnvClient(address=address)
# A spawned server already reported its address *after* binding + loading,
# so it's up — the untimed ``info`` below is enough. An external server has
# no such handshake, so poll until it answers before we block on ``info``.
# A spawned server already reported its address *after* binding, so it's up. An
# external server has no such handshake, so poll until it answers.
if external:
await self.env_client.wait_for_server_startup()
info = await self.env_client.info()
self.num_tasks = info.num_tasks
self.requires_group_scoring = info.requires_group_scoring
if self.config.is_legacy:
info = await self.env_client.info()
self.num_tasks = info.num_tasks
self.requires_group_scoring = info.requires_group_scoring
else:
taskset = vf.load_taskset(self.config.env.taskset)
if type(taskset).INFINITE:
self.tasks = iter(taskset.load())
self.num_tasks = None
else:
# Materialize off the event loop — load() may pull a dataset.
materialized = await asyncio.to_thread(lambda: list(taskset.load()))
self.tasks = iter(materialized)
self.num_tasks = len(materialized)
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
get_logger().info(f"Env {self.name} ready: num_tasks={num_tasks} group_scoring={self.requires_group_scoring}")
async def _spawn(self, log_dir: Path, log_level: str, json_logging: bool) -> str:
"""Spawn a v1 EnvServer child process (it loads the env; we never do).
The server binds an OS-assigned port (``:0``) and reports the concrete
"""Spawn a v1 EnvServer child process (it runs the agents; the tasks come from
us). The server binds an OS-assigned port (``:0``) and reports the concrete
address back over a queue — no free-port guess, no TOCTOU race. Its output
goes to ``<log_dir>/<name>.log`` (``log_dir`` is already the train/eval-split
``.../logs/envs/{train,eval}`` the orchestrator passes in)."""
@@ -170,12 +191,20 @@ class Env:
return vf.SamplingConfig(**sampling)
async def run(
self, client: vf.ClientConfig, task_idx: int, model_name: str, cache_salt: str | None
self,
client: vf.ClientConfig,
model_name: str,
cache_salt: str | None,
task_data: dict | None = None,
task_idx: int | None = None,
) -> list[Rollout]:
"""Run one episode for ``task_idx``; return its typed Traces. A zero-trace
episode raises (the dispatcher synthesizes the error marker); a not-``ok``
episode marks its clean traces failed so partial episodes never train."""
"""Run one episode; return its typed Traces. A v1 env takes the task itself
(``task_data``); the legacy bridge is addressed by dataset row (``task_idx``).
A zero-trace episode raises (the dispatcher synthesizes the error marker); a
not-``ok`` episode marks its clean traces failed so partial episodes never
train."""
episode = await self.env_client.run(
task_data=task_data,
task_idx=task_idx,
client=client,
model=model_name,
@@ -236,13 +265,16 @@ class EvalEnv(Env):
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
await super().start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
if self.num_tasks is None:
if self.config.num_examples < 0:
raise ValueError(f"Eval env {self.name} has an infinite taskset — set num_examples to bound it")
n = self.config.num_examples
else:
n = self.num_tasks if self.config.num_examples < 0 else min(self.config.num_examples, self.num_tasks)
self.examples = [{"task_idx": i} for i in range(n)]
n = self.config.num_examples
if self.tasks is None: # legacy: the dataset lives on the server — address it by row
count = self.num_tasks if n < 0 else min(n, self.num_tasks)
self.examples = [{"task_idx": i} for i in range(count)]
return
if self.num_tasks is None and n < 0:
raise ValueError(f"Eval env {self.name} has an infinite taskset — set num_examples to bound it")
# A fixed eval set, pulled off the tasks once and reused every epoch.
tasks = list(self.tasks) if n < 0 else list(islice(self.tasks, n))
self.examples = [{"task_idx": task.data.idx, "task": task} for task in tasks]
EnvT = TypeVar("EnvT", bound=Env)
@@ -231,6 +231,7 @@ class Orchestrator:
self.monitor = setup_monitor(
wandb_config=config.wandb,
prime_config=config.prime_monitor,
file_config=config.file_monitor,
output_dir=config.output_dir,
tokenizer=self.tokenizer,
run_config=config,
+24 -15
View File
@@ -1,14 +1,18 @@
"""TrainSource: weighted round-robin across train envs, infinite pull.
Weights are each env's configured ``ratio`` (default 1, i.e. equal weight
per env). A finite env serves a shuffled task-index table, reshuffled on
cursor exhaustion; an infinite env (``num_tasks is None``) streams a
monotonic ``task_idx`` — the server generates tasks on demand, so every
pull is a fresh task and there are no epochs to shuffle."""
per env). A v1 env serves the tasks the orchestrator loaded client-side: a
finite one as a shuffled table (reshuffled on cursor exhaustion), an
infinite one (``num_tasks is None``) straight off its generator — every
pull is a fresh task and there are no epochs to shuffle. A legacy env's
dataset lives on its server, so it serves shuffled task *indices*."""
from __future__ import annotations
import random
from collections.abc import Iterator
import verifiers.v1 as vf
from prime_rl.orchestrator.envs import TrainEnvs
@@ -17,7 +21,8 @@ class TrainSource:
"""``next_example(available_permits)`` picks a weighted-RR env and
returns its next example (or ``None`` when the env's per-call permit
cost doesn't fit — the dispatch loop retries when permits free up).
Returned dicts carry ``env_name`` + ``task_idx``."""
Returned dicts carry ``env_name`` + ``task_idx`` (+ ``task`` for v1 envs,
whose data is shipped to the env server at dispatch)."""
def __init__(self, train_envs: TrainEnvs, *, seed: int | None) -> None:
self.rng = random.Random(seed)
@@ -25,22 +30,26 @@ class TrainSource:
if not self.envs:
raise ValueError("TrainSource needs at least one train env")
# A finite env's shuffled index table; ``None`` for an infinite env,
# whose cursor alone is the (monotonic) task_idx stream.
# A finite env's shuffled example table; ``None`` for an infinite env,
# whose generator (``self.iters``) is pulled per example.
self.examples: dict[str, list[dict] | None] = {}
self.iters: dict[str, Iterator[vf.Task]] = {}
self.cursors: dict[str, int] = {}
# Group-scoring envs reserve ``group_size`` permits up front;
# per-rollout envs need 1
self.env_costs: dict[str, int] = {}
for env in self.envs:
# The orchestrator never loads the env: sample over the task-index
# range the server reported via info() (num_tasks; None = infinite).
if env.num_tasks is None:
self.examples[env.name] = None
else:
if env.tasks is None: # legacy: sample over the index range from info()
rows: list[dict] = [{"task_idx": i, "env_name": env.name} for i in range(env.num_tasks)]
self.rng.shuffle(rows)
self.examples[env.name] = rows
elif env.num_tasks is None: # infinite: pull the generator per example
self.examples[env.name] = None
self.iters[env.name] = env.tasks
else:
rows = [{"task_idx": task.data.idx, "task": task, "env_name": env.name} for task in env.tasks]
self.rng.shuffle(rows)
self.examples[env.name] = rows
self.cursors[env.name] = 0
self.env_costs[env.name] = env.config.group_size if env.requires_group_scoring else 1
@@ -53,9 +62,9 @@ class TrainSource:
return None
rows = self.examples[env_name]
cursor = self.cursors[env_name]
if rows is None: # infinite env: the cursor is the task_idx
self.cursors[env_name] = cursor + 1
return {"task_idx": cursor, "env_name": env_name}
if rows is None: # infinite env: pull the next generated task
task = next(self.iters[env_name])
return {"task_idx": task.data.idx, "task": task, "env_name": env_name}
if cursor >= len(rows):
self.rng.shuffle(rows)
cursor = 0
+3
View File
@@ -63,6 +63,9 @@ class GroupState:
task_idx: int
rollouts_to_schedule: int
target_rollouts: int
task: vf.Task | None = None
"""The group's task (v1 envs — its data is shipped on every dispatch). ``None`` for
legacy envs, which are addressed by ``task_idx`` alone."""
emitted: int = 0
eval_step: int | None = None
pinned_client: vf.ClientConfig | None = None
@@ -15,6 +15,13 @@ def ceil_div(x: int, y: int) -> int:
return (x + y - 1) // y
def ue8m0_for_device(device: torch.device | None = None) -> bool:
"""DeepGEMM requires UE8M0 (power-of-2) scales on SM100; SM90 supports exact float
scales, and UE8M0 there is a pure precision loss (it measurably raises the
trainer/inference mismatch KL)."""
return torch.cuda.get_device_capability(device)[0] >= 10
# ---------------------------------------------------------------------------
# Layout building
# ---------------------------------------------------------------------------
@@ -16,6 +16,7 @@ from prime_rl.trainer.models.kernels.fp8_utils import (
grouped_per_channel_cast_to_fp8_rowmajor_triton,
grouped_per_channel_cast_to_fp8_sm90_kmajor_triton,
grouped_per_token_cast_to_fp8_triton,
ue8m0_for_device,
unpack_rows_triton,
)
@@ -66,7 +67,7 @@ def _compute_grad_weight(
actual_ms_tensor,
ks_tensor,
block_starts_tensor,
True,
False,
GROUP_ALIGNMENT,
)
dy_fp8 = grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
@@ -77,7 +78,7 @@ def _compute_grad_weight(
actual_ms_tensor,
ks_tensor,
block_starts_tensor,
True,
False,
GROUP_ALIGNMENT,
)
grouped_weight_grad = deep_gemm.k_grouped_fp8_gemm_nt_contiguous
@@ -113,6 +114,7 @@ class _GroupedFP8Gemm(torch.autograd.Function):
block_starts_tensor,
) = build_grouped_layout(offs, total_m=x.size(0))
use_ue8m0 = ue8m0_for_device(x.device)
x_fp8 = grouped_per_token_cast_to_fp8_triton(
x,
padded_total_m,
@@ -120,12 +122,12 @@ class _GroupedFP8Gemm(torch.autograd.Function):
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
True,
use_ue8m0,
GROUP_ALIGNMENT,
)
weight_fp8 = grouped_per_block_cast_to_fp8_triton(
weight.transpose(1, 2),
True,
use_ue8m0,
GROUP_ALIGNMENT,
)
@@ -197,6 +199,7 @@ class _GroupedFP8Gemm(torch.autograd.Function):
)
if ctx.needs_input_grad[0]:
use_ue8m0 = ue8m0_for_device(grad_output.device)
dy_fp8 = grouped_per_token_cast_to_fp8_triton(
grad_output,
padded_total_m,
@@ -204,12 +207,12 @@ class _GroupedFP8Gemm(torch.autograd.Function):
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
True,
use_ue8m0,
GROUP_ALIGNMENT,
)
weight_dx_fp8 = grouped_per_block_cast_to_fp8_triton(
weight,
True,
use_ue8m0,
GROUP_ALIGNMENT,
)
grad_x_padded = torch.empty(
@@ -17,6 +17,7 @@ from prime_rl.trainer.models.kernels.fp8_utils import (
per_block_cast_to_fp8_triton,
per_token_cast_to_fp8_tp_triton,
per_token_cast_to_fp8_triton,
ue8m0_for_device,
)
from prime_rl.utils.logger import get_logger
@@ -26,8 +27,9 @@ class _FP8BlockwiseMM(torch.autograd.Function):
def forward(ctx, x, weight, block_size, out_dtype=torch.bfloat16):
x_shape = x.shape
x_2d = x.reshape(-1, x_shape[-1]).contiguous()
x_fp8 = per_token_cast_to_fp8_triton(x_2d, True, block_size)
weight_fp8 = per_block_cast_to_fp8_triton(weight, True, block_size)
use_ue8m0 = ue8m0_for_device(x.device)
x_fp8 = per_token_cast_to_fp8_triton(x_2d, use_ue8m0, block_size)
weight_fp8 = per_block_cast_to_fp8_triton(weight, use_ue8m0, block_size)
out = torch.empty((x_2d.size(0), weight.size(0)), device=x.device, dtype=out_dtype)
deep_gemm.fp8_gemm_nt(x_fp8, weight_fp8, out)
@@ -42,11 +44,12 @@ class _FP8BlockwiseMM(torch.autograd.Function):
x_2d, weight = ctx.saved_tensors
block_size = ctx.block_size
grad_output_2d = grad_output.reshape(-1, grad_output.shape[-1]).contiguous()
use_ue8m0 = ue8m0_for_device(grad_output.device)
grad_x = grad_weight = None
if ctx.needs_input_grad[0]:
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, True, block_size)
weight_dx_fp8 = per_block_cast_to_fp8_tp_triton(weight, True, block_size)
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, use_ue8m0, block_size)
weight_dx_fp8 = per_block_cast_to_fp8_tp_triton(weight, use_ue8m0, block_size)
grad_x_2d = torch.empty_like(x_2d)
deep_gemm.fp8_gemm_nt(grad_output_fp8, weight_dx_fp8, grad_x_2d)
grad_x = grad_x_2d.reshape(ctx.x_shape)
@@ -64,8 +67,8 @@ class _FP8BlockwiseMM(torch.autograd.Function):
else:
grad_output_2d_padded = grad_output_2d
x_2d_padded = x_2d
grad_output_t_fp8 = per_token_cast_to_fp8_tp_triton(grad_output_2d_padded, True, block_size)
x_t_fp8 = per_token_cast_to_fp8_tp_triton(x_2d_padded, True, block_size)
grad_output_t_fp8 = per_token_cast_to_fp8_tp_triton(grad_output_2d_padded, use_ue8m0, block_size)
x_t_fp8 = per_token_cast_to_fp8_tp_triton(x_2d_padded, use_ue8m0, block_size)
grad_weight_fp32 = torch.zeros_like(weight, dtype=torch.float32)
deep_gemm.fp8_gemm_nt(
grad_output_t_fp8,
+3 -1
View File
@@ -86,7 +86,9 @@ def train(config: TrainerConfig):
# Setup the monitor
logger.info(f"Initializing monitor ({config.wandb})")
monitor = setup_monitor(config.wandb, output_dir=config.output_dir, run_config=config)
monitor = setup_monitor(
config.wandb, file_config=config.file_monitor, output_dir=config.output_dir, run_config=config
)
# Setup heartbeat (only on rank 0)
heart = None
+3 -1
View File
@@ -73,7 +73,9 @@ def train(config: SFTConfig):
# Setup the monitor
logger.info(f"Initializing monitor ({config.wandb})")
monitor = setup_monitor(config.wandb, output_dir=config.output_dir, run_config=config)
monitor = setup_monitor(
config.wandb, file_config=config.file_monitor, output_dir=config.output_dir, run_config=config
)
# Setup heartbeat (only on rank 0)
heart = None
+14 -1
View File
@@ -2,9 +2,10 @@ from pathlib import Path
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.configs.shared import PrimeMonitorConfig, WandbWithExtrasConfig
from prime_rl.configs.shared import FileMonitorConfig, PrimeMonitorConfig, WandbWithExtrasConfig
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.monitor.base import Monitor, NoOpMonitor
from prime_rl.utils.monitor.file import FileMonitor
from prime_rl.utils.monitor.multi import MultiMonitor
from prime_rl.utils.monitor.prime import PrimeMonitor
from prime_rl.utils.monitor.wandb import WandbMonitor
@@ -13,6 +14,7 @@ __all__ = [
"Monitor",
"WandbMonitor",
"PrimeMonitor",
"FileMonitor",
"MultiMonitor",
"NoOpMonitor",
"setup_monitor",
@@ -37,6 +39,7 @@ def setup_monitor(
run_config: BaseConfig | None = None,
*,
prime_config: PrimeMonitorConfig | None = None,
file_config: FileMonitorConfig | None = None,
keep_full_history: bool = True,
train_env_names: list[str] = [],
eval_env_names: list[str] = [],
@@ -83,6 +86,16 @@ def setup_monitor(
)
)
if file_config is not None:
monitors.append(
FileMonitor(
config=file_config,
output_dir=output_dir,
run_config=run_config,
keep_full_history=keep_full_history,
)
)
if len(monitors) == 0:
_MONITOR = NoOpMonitor(keep_full_history=keep_full_history)
elif len(monitors) == 1:
+40
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import math
import random
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any
@@ -8,6 +9,45 @@ if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
_DROPPED_JSON_VALUE = object()
def drop_non_finite_json_values(value: Any, dropped_paths: list[str], path: str = "") -> Any:
"""Recursively drop non-finite floats (NaN/inf) from a JSON-serializable value.
Appends the dotted path of each dropped value to `dropped_paths`. Used before
serializing metric payloads that must be strict JSON (the public Prime API and
the local `metrics.jsonl` sink), since NaN/Infinity are not valid JSON.
"""
if isinstance(value, float) and not math.isfinite(value):
dropped_paths.append(path)
return _DROPPED_JSON_VALUE
if isinstance(value, dict):
return {
key: sanitized_item
for key, item in value.items()
if (
sanitized_item := drop_non_finite_json_values(
item,
dropped_paths,
f"{path}.{key}" if path else str(key),
)
)
is not _DROPPED_JSON_VALUE
}
if isinstance(value, list):
return [
sanitized_item
for idx, item in enumerate(value)
if (sanitized_item := drop_non_finite_json_values(item, dropped_paths, f"{path}[{idx}]"))
is not _DROPPED_JSON_VALUE
]
return value
def sample_items_for_logging(items: list[Any], sample_ratio: float | None) -> list[Any]:
"""Apply monitor sample_ratio semantics to a batch of items.
+103
View File
@@ -0,0 +1,103 @@
from __future__ import annotations
import json
import os
import time
from pathlib import Path
from typing import TYPE_CHECKING, Any
from prime_rl.configs.shared import FileMonitorConfig
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.monitor.base import Monitor, drop_non_finite_json_values
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
class FileMonitor(Monitor):
"""Appends logged metrics to a local ``metrics.jsonl`` file.
A self-hosted, dependency-free mirror of what ``WandbMonitor.log`` sees: one
JSON object per line, ``{"step": step, "time": <wall>, **metrics}``. The file is
flushed after every write so an in-progress run can be read (e.g. to build a
static dashboard snapshot mid-run). Only rank 0 writes. Samples and
distributions are not persisted here (scalars only).
"""
def __init__(
self,
config: FileMonitorConfig | None,
output_dir: Path | None = None,
run_config: BaseConfig | None = None,
keep_full_history: bool = True,
):
self.config = config
self.logger = get_logger()
self.history: list[dict[str, Any]] = []
self._keep_full_history = keep_full_history
self.output_dir = output_dir
self._file = None
rank = int(os.environ.get("RANK", os.environ.get("DP_RANK", "0")))
self.enabled = self.config is not None
self.is_master = rank == 0
if not self.enabled or not self.is_master:
if not self.is_master:
self.logger.warning(f"Skipping {self.__class__.__name__} initialization from non-master rank ({rank})")
return
if output_dir is None:
self.logger.warning("FileMonitor requires an output_dir; disabling.")
self.enabled = False
return
output_dir.mkdir(parents=True, exist_ok=True)
self._path = output_dir / config.filename
# Line-buffered append so a concurrently-running dashboard can tail the file.
self._file = open(self._path, "a", buffering=1) # noqa: SIM115
self.logger.info(f"Logging metrics to {self._path}")
def log(self, metrics: dict[str, Any], step: int) -> None:
if self._keep_full_history:
self.history.append(metrics)
else:
self.history = [metrics]
if not self.is_master or not self.enabled or self._file is None:
return
dropped_paths: list[str] = []
sanitized = drop_non_finite_json_values(metrics, dropped_paths)
if dropped_paths:
preview = ", ".join(dropped_paths[:5])
suffix = " ..." if len(dropped_paths) > 5 else ""
self.logger.debug(
f"Dropping {len(dropped_paths)} non-finite value(s) from metrics.jsonl: {preview}{suffix}"
)
row = {"step": step, "time": time.time(), **sanitized}
self._file.write(json.dumps(row))
self._file.write("\n")
def log_samples(self, rollouts: list[Rollout], step: int) -> None:
pass
def log_eval_samples(self, rollouts: list[Rollout], env_name: str, step: int) -> None:
pass
def log_distributions(self, distributions: dict[str, list[float]], step: int) -> None:
pass
def save_final_summary(self, filename: str = "final_summary.json") -> None:
if not self.is_master or not self.enabled or self.output_dir is None:
return
summary = self.history[-1] if self.history else {}
dropped_paths: list[str] = []
sanitized = drop_non_finite_json_values(summary, dropped_paths)
with open(self.output_dir / filename, "w") as f:
json.dump(sanitized, f)
def close(self) -> None:
if self._file is not None:
self._file.close()
self._file = None
+2 -36
View File
@@ -3,7 +3,6 @@ from __future__ import annotations
import asyncio
import io
import json
import math
import os
import time
from datetime import datetime, timezone
@@ -21,7 +20,7 @@ from verifiers.v1.push import trace_to_sample
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.configs.shared import PrimeMonitorConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.monitor.base import Monitor, sample_items_for_logging
from prime_rl.utils.monitor.base import Monitor, drop_non_finite_json_values, sample_items_for_logging
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
@@ -52,46 +51,13 @@ _SAMPLE_SCHEMA = pa.schema(
)
_DROPPED_JSON_VALUE = object()
def _drop_non_finite_json_values(value: Any, dropped_paths: list[str], path: str = "") -> Any:
if isinstance(value, float) and not math.isfinite(value):
dropped_paths.append(path)
return _DROPPED_JSON_VALUE
if isinstance(value, dict):
return {
key: sanitized_item
for key, item in value.items()
if (
sanitized_item := _drop_non_finite_json_values(
item,
dropped_paths,
f"{path}.{key}" if path else str(key),
)
)
is not _DROPPED_JSON_VALUE
}
if isinstance(value, list):
return [
sanitized_item
for idx, item in enumerate(value)
if (sanitized_item := _drop_non_finite_json_values(item, dropped_paths, f"{path}[{idx}]"))
is not _DROPPED_JSON_VALUE
]
return value
class PrimeMonitor(Monitor):
"""Logs to Prime Intellect API."""
def _sanitize_json_payload(self, endpoint: str, payload: dict[str, Any]) -> dict[str, Any]:
"""Drop non-finite floats before sending JSON payloads to the public API."""
dropped_paths: list[str] = []
sanitized_payload = _drop_non_finite_json_values(payload, dropped_paths)
sanitized_payload = drop_non_finite_json_values(payload, dropped_paths)
if not dropped_paths:
return payload
Generated
+1763 -1698
View File
File diff suppressed because it is too large Load Diff