Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6f7f8c0b2a | ||
|
|
560cf1a86b | ||
|
|
440b3afaa8 | ||
|
|
f5946b098e | ||
|
|
cd00986f71 | ||
|
|
208ea64308 | ||
|
|
c505e07a1a |
@@ -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: |
|
||||
|
||||
+5
-2
@@ -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
|
||||
@@ -106,9 +107,11 @@ RUN --mount=type=cache,target=/app/.cache/uv \
|
||||
&& \
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
|
||||
&& \
|
||||
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra modelexpress --extra quack --group mamba-ssm --locked --no-dev \
|
||||
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
|
||||
|
||||
@@ -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()
|
||||
Vendored
+1
-1
Submodule deps/research-environments updated: e40d32690f...f5d423c321
Vendored
+1
-1
Submodule deps/verifiers updated: 192fd8ef0d...b13ba60da6
@@ -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
|
||||
Executable
+75
@@ -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 "$@"
|
||||
@@ -82,7 +82,7 @@ class ModelConfig(BaseModelConfig):
|
||||
|
||||
|
||||
class WeightBroadcastConfig(BaseConfig):
|
||||
type: Literal["nccl", "filesystem"] = "filesystem"
|
||||
type: Literal["nccl", "filesystem", "nixl"] = "filesystem"
|
||||
"""Weight broadcast transport."""
|
||||
|
||||
|
||||
@@ -366,7 +366,7 @@ class InferenceConfig(BaseConfig):
|
||||
gpu_memory_utilization: float = 0.9
|
||||
"""GPU memory utilization. Forwarded as ``--gpu-memory-utilization``."""
|
||||
|
||||
quantization: Literal["mxfp8", "fp8_per_block"] | None = None
|
||||
quantization: str | None = None
|
||||
"""Online inference quantization method. Forwarded as ``--quantization``."""
|
||||
|
||||
api_server_count: int = Field(1, ge=0)
|
||||
@@ -435,24 +435,6 @@ class InferenceConfig(BaseConfig):
|
||||
raise ValueError("Must use SLURM for multi-node / disaggregated deployment.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_mxfp8_requires_sm100(self):
|
||||
"""Reject MXFP8 when validation runs on a non-SM100 CUDA host."""
|
||||
if self.quantization != "mxfp8":
|
||||
return self
|
||||
|
||||
try:
|
||||
import torch
|
||||
except ModuleNotFoundError as exc:
|
||||
raise ValueError("inference.quantization='mxfp8' requires torch to validate SM100 support.") from exc
|
||||
|
||||
if torch.cuda.is_available():
|
||||
capability = torch.cuda.get_device_capability()
|
||||
if capability != (10, 0):
|
||||
detected = f"SM{capability[0]}{capability[1]}"
|
||||
raise ValueError(f"inference.quantization='mxfp8' requires SM100, detected {detected}.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_llmd_no_routed_experts(self):
|
||||
"""Reject routed-expert return with the llm-d router (breaks P/D, unverified for multi-node)."""
|
||||
|
||||
@@ -14,6 +14,7 @@ from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
ClientConfig,
|
||||
EnvVars,
|
||||
FileMonitorConfig,
|
||||
FileSystemTransportConfig,
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
@@ -392,27 +393,43 @@ class FileSystemWeightBroadcastConfig(BaseConfig):
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
|
||||
|
||||
class NCCLWeightBroadcastConfig(BaseConfig):
|
||||
type: Literal["nccl"] = "nccl"
|
||||
|
||||
class InMemoryWeightBroadcastConfig(BaseConfig):
|
||||
host: str = "localhost"
|
||||
"""Host for the NCCL broadcast rendezvous."""
|
||||
"""Weight transfer host."""
|
||||
|
||||
port: int
|
||||
"""Weight transfer port."""
|
||||
|
||||
timeout: int = 1200
|
||||
"""Weight transfer timeout in seconds."""
|
||||
|
||||
inference_world_size: int = Field(1, ge=1)
|
||||
"""Total inference workers across all servers."""
|
||||
|
||||
|
||||
class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nccl"] = "nccl"
|
||||
|
||||
port: int = 29501
|
||||
"""Port for the NCCL broadcast rendezvous."""
|
||||
|
||||
timeout: int = 1200
|
||||
"""Timeout in seconds for the NCCL broadcast."""
|
||||
|
||||
quantize_in_weight_transfer: bool = False
|
||||
"""Use kernel-format FP8 quantized NCCL transfer for weight updates."""
|
||||
|
||||
inference_world_size: int = Field(1, ge=1)
|
||||
"""Total inference GPUs across all servers. Used by ``init_nccl_broadcast`` to compute per-server rank offsets."""
|
||||
|
||||
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nixl"] = "nixl"
|
||||
|
||||
port: int = 8001
|
||||
"""ModelExpress gRPC port."""
|
||||
|
||||
session_id: str = "default"
|
||||
"""ModelExpress session ID."""
|
||||
|
||||
|
||||
WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig, Field(discriminator="type")
|
||||
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
@@ -477,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)."""
|
||||
|
||||
|
||||
@@ -12,11 +12,15 @@ from prime_rl.configs.orchestrator import (
|
||||
from prime_rl.configs.orchestrator import (
|
||||
NCCLWeightBroadcastConfig as OrchestratorNCCLWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.orchestrator import (
|
||||
NIXLWeightBroadcastConfig as OrchestratorNIXLWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.orchestrator import (
|
||||
OrchestratorConfig,
|
||||
)
|
||||
from prime_rl.configs.shared import (
|
||||
EnvVars,
|
||||
FileMonitorConfig,
|
||||
SlurmConfig,
|
||||
VLMConfig,
|
||||
)
|
||||
@@ -32,6 +36,9 @@ from prime_rl.configs.trainer import (
|
||||
from prime_rl.configs.trainer import (
|
||||
NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
NIXLWeightBroadcastConfig as TrainerNIXLWeightBroadcastConfig,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource
|
||||
from prime_rl.utils.validation import (
|
||||
propagate_shared_fields,
|
||||
@@ -110,20 +117,47 @@ class SharedModelConfig(BaseConfig):
|
||||
"""VLM configuration. Set this to enable vision-language model support."""
|
||||
|
||||
|
||||
class SharedWeightBroadcastConfig(BaseConfig):
|
||||
type: Literal["nccl", "filesystem"] = "nccl"
|
||||
"""Weight broadcast transport."""
|
||||
class SharedInMemoryWeightBroadcastConfig(BaseConfig):
|
||||
host: str = "localhost"
|
||||
"""Weight transfer host."""
|
||||
|
||||
port: int
|
||||
"""Weight transfer port."""
|
||||
|
||||
timeout: int = 1200
|
||||
"""Timeout in seconds for in-memory weight transfer."""
|
||||
|
||||
|
||||
class SharedNCCLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
|
||||
type: Literal["nccl"] = "nccl"
|
||||
|
||||
port: int = 29501
|
||||
"""Port for NCCL weight broadcast."""
|
||||
|
||||
timeout: int = 1200
|
||||
"""Timeout in seconds for NCCL weight broadcast."""
|
||||
|
||||
quantize_in_weight_transfer: bool = False
|
||||
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
|
||||
|
||||
|
||||
class SharedNIXLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
|
||||
type: Literal["nixl"] = "nixl"
|
||||
|
||||
port: int = 8001
|
||||
"""ModelExpress gRPC port."""
|
||||
|
||||
session_id: str = "default"
|
||||
"""ModelExpress session ID."""
|
||||
|
||||
|
||||
class SharedFileSystemWeightBroadcastConfig(BaseConfig):
|
||||
type: Literal["filesystem"] = "filesystem"
|
||||
|
||||
|
||||
SharedWeightBroadcastConfig: TypeAlias = Annotated[
|
||||
SharedFileSystemWeightBroadcastConfig | SharedNCCLWeightBroadcastConfig | SharedNIXLWeightBroadcastConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
class BaseDeploymentConfig(BaseConfig):
|
||||
gpus_per_node: int = 8
|
||||
"""GPUs per node."""
|
||||
@@ -209,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."""
|
||||
|
||||
@@ -295,11 +332,11 @@ class RLConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_quantize_in_weight_transfer(self):
|
||||
if self.weight_broadcast is None or not self.weight_broadcast.quantize_in_weight_transfer:
|
||||
if not isinstance(self.weight_broadcast, SharedNCCLWeightBroadcastConfig):
|
||||
return self
|
||||
|
||||
if self.weight_broadcast.type != "nccl":
|
||||
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires weight_broadcast.type = 'nccl'.")
|
||||
if not self.weight_broadcast.quantize_in_weight_transfer:
|
||||
return self
|
||||
|
||||
if self.inference is None:
|
||||
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires an inference config.")
|
||||
@@ -339,38 +376,39 @@ class RLConfig(BaseConfig):
|
||||
"""Auto-setup shared weight broadcast config for trainer, orchestrator, and inference.
|
||||
|
||||
Defaults to NCCL broadcast when no ``weight_broadcast`` is configured. Falls back to
|
||||
filesystem when LoRA is enabled (not yet supported with NCCL) or when no inference
|
||||
server is configured (NCCL requires a running inference pool).
|
||||
filesystem when LoRA is enabled (not yet supported by in-memory transfer) or when no
|
||||
inference server is configured.
|
||||
"""
|
||||
if self.weight_broadcast is None:
|
||||
if self.trainer.model.lora is not None or self.inference is None:
|
||||
self.weight_broadcast = SharedWeightBroadcastConfig(type="filesystem")
|
||||
self.weight_broadcast = SharedFileSystemWeightBroadcastConfig()
|
||||
else:
|
||||
self.weight_broadcast = SharedWeightBroadcastConfig()
|
||||
if self.weight_broadcast.type == "nccl" and self.trainer.model.lora is not None:
|
||||
# LoRA adapters are transferred via the filesystem (loaded from disk by the inference
|
||||
# servers); NCCL broadcast only writes a STABLE marker, so LoRA over NCCL cannot transfer
|
||||
# an adapter and would hang/fail on the startup weight sync.
|
||||
self.weight_broadcast = SharedNCCLWeightBroadcastConfig()
|
||||
if self.weight_broadcast.type != "filesystem" and self.trainer.model.lora is not None:
|
||||
raise ValueError(
|
||||
"LoRA training is not yet supported with NCCL weight broadcast. "
|
||||
"LoRA training is not yet supported with in-memory weight broadcast. "
|
||||
"Set weight_broadcast.type = 'filesystem'."
|
||||
)
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
if self.weight_broadcast.type in ("nccl", "nixl"):
|
||||
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
|
||||
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type,
|
||||
inference_world_size=inference_world_size,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
|
||||
type=self.weight_broadcast.type,
|
||||
common_config = dict(
|
||||
host=self.weight_broadcast.host,
|
||||
port=self.weight_broadcast.port,
|
||||
timeout=self.weight_broadcast.timeout,
|
||||
inference_world_size=inference_world_size,
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
transport_config = dict(
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
trainer_config_type = TrainerNCCLWeightBroadcastConfig
|
||||
orchestrator_config_type = OrchestratorNCCLWeightBroadcastConfig
|
||||
else:
|
||||
transport_config = dict(session_id=self.weight_broadcast.session_id)
|
||||
trainer_config_type = TrainerNIXLWeightBroadcastConfig
|
||||
orchestrator_config_type = OrchestratorNIXLWeightBroadcastConfig
|
||||
self.trainer.weight_broadcast = trainer_config_type(**common_config, **transport_config)
|
||||
self.orchestrator.weight_broadcast = orchestrator_config_type(**common_config, **transport_config)
|
||||
elif self.weight_broadcast.type == "filesystem":
|
||||
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
|
||||
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
|
||||
@@ -417,9 +455,6 @@ class RLConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_lora(self):
|
||||
if self.trainer.model.lora is not None:
|
||||
if self.trainer.weight_broadcast.type == "nccl":
|
||||
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
|
||||
|
||||
if self.orchestrator.model.lora is None:
|
||||
from prime_rl.configs.orchestrator import LoRAConfig
|
||||
|
||||
@@ -548,7 +583,7 @@ class RLConfig(BaseConfig):
|
||||
)
|
||||
self.inference.parallel.dp = num_infer_gpus // self.inference.parallel.tp
|
||||
# Ensure api_server_count matches DP so all workers are created.
|
||||
# Without this, the NCCL broadcast group expects dp*tp workers
|
||||
# Without this, in-memory weight transfer expects dp*tp workers
|
||||
# but only api_server_count*tp exist, causing a deadlock.
|
||||
dp = self.inference.parallel.dp
|
||||
if self.inference.api_server_count < dp and not self.inference.enable_lora:
|
||||
@@ -602,7 +637,7 @@ class RLConfig(BaseConfig):
|
||||
# Auto-infer DP and api_server_count for standard multi-node inference.
|
||||
# Without EP, vLLM only creates api_server_count * tp workers per node,
|
||||
# not gpus_per_node workers. If DP isn't set, the broadcast group expects
|
||||
# more workers than exist, deadlocking NCCL init.
|
||||
# more workers than exist, deadlocking in-memory transfer initialization.
|
||||
if (
|
||||
self.inference is not None
|
||||
and not self.inference.enable_expert_parallel
|
||||
@@ -616,19 +651,20 @@ class RLConfig(BaseConfig):
|
||||
if self.inference.api_server_count == 1 and dp_per_node > 1:
|
||||
self.inference.api_server_count = dp_per_node
|
||||
|
||||
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
|
||||
# Every allocated inference GPU is a NCCL rank in the weight broadcast.
|
||||
if self.weight_broadcast is not None and self.weight_broadcast.type in ("nccl", "nixl"):
|
||||
# Every allocated inference GPU is an in-memory transfer worker.
|
||||
# The external-LB launcher starts dp_per_node (= gpus_per_node / tp)
|
||||
# TP-sharded servers per node, i.e. gpus_per_node workers per node, so use
|
||||
# the GPU count directly. Deriving it from api_server_count double-counts:
|
||||
# api_server_count can resolve to the *global* DP size, making the node
|
||||
# factor count twice and NCCL wait for ranks that never connect. Matches
|
||||
# factor count twice and wait for ranks that never connect. Matches
|
||||
# the disaggregated path below.
|
||||
total_infer_workers = self.deployment.total_infer_nodes * self.deployment.gpus_per_node
|
||||
assert self.trainer.weight_broadcast.type == "nccl"
|
||||
self.trainer.weight_broadcast.host = "0.0.0.0"
|
||||
assert self.trainer.weight_broadcast.type in ("nccl", "nixl")
|
||||
if self.trainer.weight_broadcast.type == "nccl":
|
||||
self.trainer.weight_broadcast.host = "0.0.0.0"
|
||||
self.trainer.weight_broadcast.inference_world_size = total_infer_workers
|
||||
assert self.orchestrator.weight_broadcast.type == "nccl"
|
||||
assert self.orchestrator.weight_broadcast.type in ("nccl", "nixl")
|
||||
self.orchestrator.weight_broadcast.inference_world_size = total_infer_workers
|
||||
|
||||
return self
|
||||
@@ -659,10 +695,10 @@ class RLConfig(BaseConfig):
|
||||
infer_deploy.num_decode_nodes * stride
|
||||
)
|
||||
self.orchestrator.inference_metrics_roles = role_order * self.deployment.num_infer_replicas
|
||||
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
|
||||
assert self.trainer.weight_broadcast.type == "nccl"
|
||||
if self.weight_broadcast is not None and self.weight_broadcast.type in ("nccl", "nixl"):
|
||||
assert self.trainer.weight_broadcast.type in ("nccl", "nixl")
|
||||
self.trainer.weight_broadcast.inference_world_size = total_infer_gpus
|
||||
assert self.orchestrator.weight_broadcast.type == "nccl"
|
||||
assert self.orchestrator.weight_broadcast.type in ("nccl", "nixl")
|
||||
self.orchestrator.weight_broadcast.inference_world_size = total_infer_gpus
|
||||
|
||||
return self
|
||||
|
||||
@@ -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,
|
||||
@@ -514,28 +515,44 @@ class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
"""Weight checkpoint serialization format."""
|
||||
|
||||
|
||||
class NCCLWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
type: Literal["nccl"] = "nccl"
|
||||
|
||||
class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
|
||||
host: str = "localhost"
|
||||
"""Host for the NCCL broadcast rendezvous."""
|
||||
"""Weight transfer host."""
|
||||
|
||||
port: int = 29501
|
||||
"""Port for the NCCL broadcast rendezvous."""
|
||||
port: int
|
||||
"""Weight transfer port."""
|
||||
|
||||
timeout: int = 1200
|
||||
"""Timeout in seconds for the NCCL broadcast."""
|
||||
"""Weight transfer timeout in seconds."""
|
||||
|
||||
# TODO: Should not be configurable, but auto-inferred
|
||||
inference_world_size: int = 1
|
||||
"""Number of GPUs used for inference."""
|
||||
"""Number of inference workers."""
|
||||
|
||||
|
||||
class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nccl"] = "nccl"
|
||||
|
||||
port: int = 29501
|
||||
"""Port for the NCCL broadcast rendezvous."""
|
||||
|
||||
quantize_in_weight_transfer: bool = False
|
||||
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
|
||||
|
||||
|
||||
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nixl"] = "nixl"
|
||||
|
||||
port: int = 8001
|
||||
"""ModelExpress gRPC port."""
|
||||
|
||||
session_id: str = "default"
|
||||
"""ModelExpress session ID."""
|
||||
|
||||
|
||||
WeightBroadcastConfig: TypeAlias = Annotated[
|
||||
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig, Field(discriminator="type")
|
||||
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
|
||||
|
||||
@@ -566,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."""
|
||||
|
||||
@@ -684,9 +704,8 @@ class TrainerConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_lora_broadcast(self):
|
||||
if self.model.lora is not None and self.weight_broadcast.type == "nccl":
|
||||
# TODO: Support NCCL broadcast with LoRA
|
||||
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
|
||||
if self.model.lora is not None and self.weight_broadcast.type in ("nccl", "nixl"):
|
||||
raise ValueError("In-memory weight broadcast does not support LoRA yet.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -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}", {})
|
||||
|
||||
+10
-6
@@ -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",
|
||||
@@ -44,6 +46,7 @@ dependencies = [
|
||||
"pandas>=2.0",
|
||||
"msgspec>=0.18",
|
||||
"torchao>=0.17.0",
|
||||
"modelexpress==0.3.0",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
@@ -76,9 +79,6 @@ disagg = [
|
||||
gpt-oss = [
|
||||
"kernels",
|
||||
]
|
||||
modelexpress = [
|
||||
"modelexpress==0.3.0",
|
||||
]
|
||||
quack = [
|
||||
"quack-kernels>=0.4.1",
|
||||
]
|
||||
@@ -159,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
|
||||
@@ -202,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'" },
|
||||
|
||||
@@ -61,7 +61,7 @@ if [ -n "$PRIME_RL_REF" ]; then
|
||||
# override's lockfile pins different versions.
|
||||
( cd "$DEST" && uv sync --inexact --no-dev --all-packages \
|
||||
--extra flash-attn --extra flash-attn-3 --extra flash-attn-cute \
|
||||
--extra gpt-oss --extra modelexpress \
|
||||
--extra gpt-oss \
|
||||
--group mamba-ssm )
|
||||
export VIRTUAL_ENV="$DEST/.venv"
|
||||
export PATH="$DEST/.venv/bin:$PATH"
|
||||
|
||||
+3
-4
@@ -297,12 +297,11 @@ def verify(arch: str, model_dir: Path) -> None:
|
||||
|
||||
# Roundtrip weight conversion: HF -> PrimeRL -> HF
|
||||
# Normalize both through the same roundtrip to handle expert format differences
|
||||
prime_cls = preset["prime_model_class"]
|
||||
with torch.no_grad():
|
||||
roundtrip_sd = prime_cls.convert_to_hf(dict(prime_model.state_dict()))
|
||||
roundtrip_sd = prime_model.convert_to_hf(dict(prime_model.state_dict()))
|
||||
orig_sd = dict(hf_model.state_dict())
|
||||
prime_cls.convert_to_prime(orig_sd)
|
||||
prime_cls.convert_to_hf(orig_sd)
|
||||
prime_model.convert_to_prime(orig_sd)
|
||||
prime_model.convert_to_hf(orig_sd)
|
||||
|
||||
for key in orig_sd:
|
||||
assert key in roundtrip_sd, f"Missing key after roundtrip: {key}"
|
||||
|
||||
@@ -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}")
|
||||
@@ -68,6 +68,7 @@ def models(request: Request) -> OpenAIServingModels:
|
||||
WORKER_EXTENSION_CLS = {
|
||||
"nccl": "prime_rl.inference.vllm.worker.nccl.NCCLWeightUpdateWorker",
|
||||
"filesystem": "prime_rl.inference.vllm.worker.filesystem.FileSystemWeightUpdateWorker",
|
||||
"nixl": "prime_rl.inference.vllm.worker.nixl.NIXLWeightUpdateWorker",
|
||||
}
|
||||
|
||||
|
||||
@@ -143,9 +144,10 @@ async def init_broadcaster(request: Request):
|
||||
rank_offset = data.get("rank_offset")
|
||||
inference_world_size = data.get("inference_world_size")
|
||||
quantize_in_weight_transfer = data.get("quantize_in_weight_transfer", False)
|
||||
session_id = data.get("session_id", "default")
|
||||
await engine_client(request).collective_rpc(
|
||||
"init_broadcaster",
|
||||
args=(host, port, rank_offset, inference_world_size, timeout, quantize_in_weight_transfer),
|
||||
args=(host, port, rank_offset, inference_world_size, timeout, quantize_in_weight_transfer, session_id),
|
||||
)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@@ -100,6 +100,7 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
inference_world_size: int,
|
||||
timeout: int,
|
||||
quantize_in_weight_transfer: bool = False,
|
||||
session_id: str = "default",
|
||||
) -> None:
|
||||
"""Initialize the NCCL broadcast receiver.
|
||||
|
||||
@@ -107,6 +108,7 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
rank_offset: Starting GPU offset for this server in the global inference group.
|
||||
inference_world_size: Total number of inference GPUs across all servers.
|
||||
"""
|
||||
del session_id
|
||||
self.quantize_in_weight_transfer = quantize_in_weight_transfer
|
||||
# Use the worker's device index directly as the local rank.
|
||||
# The previous dp_group-based computation broke in vLLM v1 multiprocess
|
||||
|
||||
@@ -0,0 +1,648 @@
|
||||
"""vLLM worker extension for composed, sharded NIXL weight pulls."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import dataclass
|
||||
from functools import wraps
|
||||
from math import prod
|
||||
from threading import Event
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from modelexpress import p2p_pb2
|
||||
from modelexpress.client import MxClient
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from prime_rl.inference.vllm.worker.weight_transfer import update_mla_absorbed_weights
|
||||
from prime_rl.trainer.rl.broadcast.nixl.agent import MemDesc, NixlAgent, make_agent_name, set_ucx_env_defaults
|
||||
from prime_rl.trainer.rl.broadcast.nixl.cuda_malloc_memory import (
|
||||
size_cuda_buffers,
|
||||
use_cuda_malloc_pool,
|
||||
)
|
||||
from prime_rl.trainer.rl.broadcast.nixl.graph import (
|
||||
Destination,
|
||||
OperationChain,
|
||||
RecordedCopy,
|
||||
TensorReplayPlan,
|
||||
WeightLoadRecorder,
|
||||
apply_chain,
|
||||
make_hf_lazy_weights,
|
||||
plan_tensor_replay,
|
||||
)
|
||||
from prime_rl.trainer.rl.broadcast.nixl.model_express import ModelExpressSession
|
||||
from prime_rl.trainer.rl.broadcast.nixl.tensor_routing import route_sharded_tensor
|
||||
from prime_rl.trainer.rl.broadcast.nixl.trainer_tensor_table import TrainerTensorTable
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.worker.gpu_worker import Worker
|
||||
else:
|
||||
Worker = object
|
||||
|
||||
logger = init_logger("vllm.inference.vllm.worker_nixl")
|
||||
_BUFFER_POLL_INTERVAL = 0.01
|
||||
|
||||
|
||||
@dataclass
|
||||
class TensorCopyPlan:
|
||||
recorded_copy: RecordedCopy
|
||||
staging_tensor: torch.Tensor
|
||||
replay_ops: OperationChain
|
||||
|
||||
|
||||
@dataclass
|
||||
class LayerWeightTransferPlan:
|
||||
reload_layer: nn.Module | None
|
||||
copies: list[TensorCopyPlan]
|
||||
persistent_copies: list[TensorCopyPlan]
|
||||
|
||||
@property
|
||||
def destination_names(self) -> set[str]:
|
||||
return {plan.recorded_copy.destination_name for plan in self.copies}
|
||||
|
||||
|
||||
@dataclass
|
||||
class WeightTransferGroup:
|
||||
name: str
|
||||
layers: list[LayerWeightTransferPlan]
|
||||
pulls: list[tuple[Any, Any, list[int]]]
|
||||
|
||||
|
||||
@dataclass
|
||||
class WeightTransferPlan:
|
||||
receive_arenas: dict[torch.dtype, torch.Tensor]
|
||||
receive_buffer_count: int
|
||||
groups: list[WeightTransferGroup]
|
||||
|
||||
|
||||
class NIXLWeightUpdateWorker(Worker):
|
||||
@property
|
||||
def raw_model(self) -> nn.Module:
|
||||
return cast(nn.Module, self.model_runner.get_model())
|
||||
|
||||
def liveness_probe(self) -> None:
|
||||
return None
|
||||
|
||||
def init_broadcaster(
|
||||
self,
|
||||
host: str,
|
||||
port: int,
|
||||
rank_offset: int,
|
||||
inference_world_size: int,
|
||||
timeout: int,
|
||||
quantize_in_weight_transfer: bool = False,
|
||||
session_id: str = "default",
|
||||
) -> None:
|
||||
del inference_world_size, quantize_in_weight_transfer
|
||||
global_rank = rank_offset + self.device.index
|
||||
server_url = f"{host}:{port}"
|
||||
set_ucx_env_defaults()
|
||||
self.nixl_agent = NixlAgent(make_agent_name("inference", global_rank))
|
||||
self.model_express = ModelExpressSession(
|
||||
client=MxClient(server_url=server_url),
|
||||
role="inference",
|
||||
rank=global_rank,
|
||||
session_id=session_id,
|
||||
worker_id=f"inference-{global_rank}",
|
||||
)
|
||||
self.weight_transfer_timeout = timeout
|
||||
self.weight_transfer_plan: WeightTransferPlan | None = None
|
||||
logger.info(
|
||||
"NIXL worker configured: global_rank=%d, ModelExpress=%s, session=%s",
|
||||
global_rank,
|
||||
server_url,
|
||||
session_id,
|
||||
)
|
||||
|
||||
@torch.no_grad()
|
||||
def initialize_transfer(self) -> WeightTransferPlan:
|
||||
if self.weight_transfer_plan is not None:
|
||||
return self.weight_transfer_plan
|
||||
|
||||
trainer_ref = self.model_express.wait_for(
|
||||
"trainer",
|
||||
count=1,
|
||||
status=None,
|
||||
timeout=self.weight_transfer_timeout,
|
||||
)[0]
|
||||
table = TrainerTensorTable.decode(self.model_express.fetch(trainer_ref).nixl_metadata)
|
||||
copies = self.trace_weight_loads(table)
|
||||
plan = self.build_transfer_plan(table, copies)
|
||||
self.buffer_sessions = []
|
||||
for buffer_index in range(table.staging_buffer_count):
|
||||
session = ModelExpressSession(
|
||||
client=self.model_express.client,
|
||||
role="inference",
|
||||
rank=self.model_express.rank,
|
||||
session_id=f"{self.model_express.session_id}:layers:{buffer_index}",
|
||||
worker_id=f"inference-buffer-{self.model_express.rank}-{buffer_index}",
|
||||
)
|
||||
session.publish()
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.buffer_sessions.append(session)
|
||||
# Join the current generation directly. Publishing a transient READY
|
||||
# before the first pull would let the trainer mistake initialization
|
||||
# for a completed acknowledgement.
|
||||
self.model_express.publish(nixl_metadata=self.nixl_agent.get_metadata())
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.weight_transfer_plan = plan
|
||||
logger.info(
|
||||
"Initialized NIXL transfer plan on rank %d with %d groups",
|
||||
self.model_express.rank,
|
||||
len(plan.groups),
|
||||
)
|
||||
return plan
|
||||
|
||||
def trace_weight_loads(
|
||||
self,
|
||||
table: TrainerTensorTable,
|
||||
) -> list[RecordedCopy]:
|
||||
"""Trace vLLM weight loading into source-to-destination copies."""
|
||||
from vllm.model_executor.model_loader.reload.layerwise import (
|
||||
_get_original_loader,
|
||||
initialize_layerwise_reload,
|
||||
)
|
||||
from vllm.model_executor.model_loader.reload.meta import SKIP_TENSORS
|
||||
from vllm.model_executor.model_loader.reload.utils import get_layer_tensors
|
||||
|
||||
model = self.raw_model
|
||||
recorder = WeightLoadRecorder()
|
||||
regular_by_layer: dict[int, list[RecordedCopy]] = defaultdict(list)
|
||||
persistent: list[RecordedCopy] = []
|
||||
original_loaders: list[tuple[torch.Tensor, Any]] = []
|
||||
with torch.device(self.device), set_current_vllm_config(self.vllm_config):
|
||||
initialize_layerwise_reload(model)
|
||||
try:
|
||||
for module in model.modules():
|
||||
for name, tensor in get_layer_tensors(module).items():
|
||||
destination = Destination(module, name, tensor)
|
||||
if not tensor.is_meta:
|
||||
recorder.register_destination_storage(destination)
|
||||
loader = _get_original_loader(tensor)
|
||||
original_loaders.append((tensor, loader))
|
||||
tensor.weight_loader = self.wrap_weight_loader_for_recording(
|
||||
recorder,
|
||||
destination,
|
||||
loader,
|
||||
)
|
||||
|
||||
model.load_weights(
|
||||
make_hf_lazy_weights(
|
||||
table,
|
||||
device=self.device,
|
||||
recorder=recorder,
|
||||
hf_config=self.model_runner.model_config.hf_text_config,
|
||||
)
|
||||
)
|
||||
|
||||
for copy in recorder.copies:
|
||||
if copy.is_persistent or copy.destination_name in SKIP_TENSORS:
|
||||
copy.is_persistent = True
|
||||
persistent.append(copy)
|
||||
else:
|
||||
regular_by_layer[id(copy.destination_module)].append(copy)
|
||||
finally:
|
||||
try:
|
||||
for tensor, loader in reversed(original_loaders):
|
||||
tensor.weight_loader = loader
|
||||
finally:
|
||||
self._restore_layerwise_state(model)
|
||||
|
||||
regular = [copy for copies in regular_by_layer.values() for copy in copies]
|
||||
return regular + persistent
|
||||
|
||||
@staticmethod
|
||||
def wrap_weight_loader_for_recording(
|
||||
recorder: WeightLoadRecorder,
|
||||
destination: Destination,
|
||||
loader: Any,
|
||||
):
|
||||
@wraps(loader)
|
||||
def recording_loader(*args, **kwargs):
|
||||
recorder.active_destination = destination
|
||||
try:
|
||||
return loader(*args, **kwargs)
|
||||
finally:
|
||||
recorder.active_destination = None
|
||||
|
||||
return recording_loader
|
||||
|
||||
@staticmethod
|
||||
def _restore_layerwise_state(model: nn.Module) -> None:
|
||||
from vllm.model_executor.model_loader.reload.layerwise import LAYERWISE_INFO, _place_kernel_tensors
|
||||
|
||||
for layer in model.modules():
|
||||
info = LAYERWISE_INFO.get(layer)
|
||||
if info is not None and info.can_load():
|
||||
if info.kernel_tensors is not None:
|
||||
_place_kernel_tensors(layer, info)
|
||||
info.reset()
|
||||
if hasattr(model, "_original_do_torchao_reload"):
|
||||
model._do_torchao_reload = model._original_do_torchao_reload
|
||||
|
||||
def build_transfer_plan(
|
||||
self,
|
||||
table: TrainerTensorTable,
|
||||
copies: list[RecordedCopy],
|
||||
) -> WeightTransferPlan:
|
||||
replay_plans = self.plan_tensor_replays(table, copies)
|
||||
receive_buffer_elements = self.calculate_receive_buffer_elements(
|
||||
table,
|
||||
copies,
|
||||
replay_plans,
|
||||
)
|
||||
receive_buffer_count = self.choose_receive_buffer_count(
|
||||
receive_buffer_elements,
|
||||
table.staging_buffer_count,
|
||||
)
|
||||
receive_arenas = self.allocate_receive_arenas(
|
||||
receive_buffer_elements,
|
||||
receive_buffer_count,
|
||||
)
|
||||
groups = self.build_transfer_groups(
|
||||
table,
|
||||
copies,
|
||||
replay_plans,
|
||||
receive_buffer_elements,
|
||||
receive_arenas,
|
||||
receive_buffer_count,
|
||||
)
|
||||
return WeightTransferPlan(
|
||||
receive_arenas=receive_arenas,
|
||||
receive_buffer_count=receive_buffer_count,
|
||||
groups=groups,
|
||||
)
|
||||
|
||||
def plan_tensor_replays(
|
||||
self,
|
||||
table: TrainerTensorTable,
|
||||
copies: list[RecordedCopy],
|
||||
) -> dict[int, TensorReplayPlan]:
|
||||
tensors = {tensor.name: tensor for group in table.groups for tensor in group.tensors}
|
||||
replay_plans: dict[int, TensorReplayPlan] = {}
|
||||
for copy in copies:
|
||||
source = tensors[copy.source_name]
|
||||
replay_plans[id(copy)] = plan_tensor_replay(
|
||||
tuple(source.shape),
|
||||
getattr(torch, source.wire_dtype),
|
||||
copy.ops,
|
||||
)
|
||||
return replay_plans
|
||||
|
||||
def calculate_receive_buffer_elements(
|
||||
self,
|
||||
table: TrainerTensorTable,
|
||||
copies: list[RecordedCopy],
|
||||
replay_plans: dict[int, TensorReplayPlan],
|
||||
) -> dict[torch.dtype, int]:
|
||||
tensors = {tensor.name: tensor for group in table.groups for tensor in group.tensors}
|
||||
tensor_groups = {
|
||||
tensor.name: group_index for group_index, group in enumerate(table.groups) for tensor in group.tensors
|
||||
}
|
||||
group_elements: dict[torch.dtype, list[int]] = defaultdict(lambda: [0] * len(table.groups))
|
||||
for copy in copies:
|
||||
source = tensors[copy.source_name]
|
||||
source_dtype = getattr(torch, source.wire_dtype)
|
||||
group_elements[source_dtype][tensor_groups[source.name]] += prod(replay_plans[id(copy)].source_shape)
|
||||
return {dtype: max(elements, default=0) for dtype, elements in group_elements.items()}
|
||||
|
||||
def choose_receive_buffer_count(
|
||||
self,
|
||||
receive_buffer_elements: dict[torch.dtype, int],
|
||||
staging_buffer_count: int,
|
||||
) -> int:
|
||||
receive_buffer_bytes = max(
|
||||
1,
|
||||
sum(elements * dtype.itemsize for dtype, elements in receive_buffer_elements.items()),
|
||||
)
|
||||
allocated_bytes = torch.cuda.memory_allocated(self.device)
|
||||
peak_growth_bytes = max(
|
||||
0,
|
||||
torch.cuda.max_memory_allocated(self.device) - allocated_bytes,
|
||||
)
|
||||
free_bytes, _ = torch.cuda.mem_get_info(self.device)
|
||||
max_receive_buffers = min(2, staging_buffer_count) if peak_growth_bytes else 1
|
||||
if peak_growth_bytes or free_bytes < receive_buffer_bytes:
|
||||
torch.cuda.empty_cache()
|
||||
return size_cuda_buffers(
|
||||
receive_buffer_bytes,
|
||||
max_receive_buffers,
|
||||
self.device,
|
||||
extra_headroom_bytes=receive_buffer_bytes + peak_growth_bytes,
|
||||
)
|
||||
|
||||
def allocate_receive_arenas(
|
||||
self,
|
||||
receive_buffer_elements: dict[torch.dtype, int],
|
||||
receive_buffer_count: int,
|
||||
) -> dict[torch.dtype, torch.Tensor]:
|
||||
with use_cuda_malloc_pool():
|
||||
receive_arenas = {
|
||||
dtype: torch.empty(
|
||||
receive_buffer_count * elements,
|
||||
dtype=dtype,
|
||||
device=self.device,
|
||||
)
|
||||
for dtype, elements in receive_buffer_elements.items()
|
||||
if elements
|
||||
}
|
||||
for arena in receive_arenas.values():
|
||||
self.nixl_agent.register_tensor(arena)
|
||||
return receive_arenas
|
||||
|
||||
def build_transfer_groups(
|
||||
self,
|
||||
table: TrainerTensorTable,
|
||||
copies: list[RecordedCopy],
|
||||
replay_plans: dict[int, TensorReplayPlan],
|
||||
receive_buffer_elements: dict[torch.dtype, int],
|
||||
receive_arenas: dict[torch.dtype, torch.Tensor],
|
||||
receive_buffer_count: int,
|
||||
) -> list[WeightTransferGroup]:
|
||||
tensors = {tensor.name: tensor for group in table.groups for tensor in group.tensors}
|
||||
tensor_groups = {
|
||||
tensor.name: group_index for group_index, group in enumerate(table.groups) for tensor in group.tensors
|
||||
}
|
||||
copies_by_group: dict[int, list[RecordedCopy]] = defaultdict(list)
|
||||
for copy in copies:
|
||||
copies_by_group[tensor_groups[copy.source_name]].append(copy)
|
||||
|
||||
reload_layers: dict[int, nn.Module] = {}
|
||||
for copy in copies:
|
||||
if not copy.is_persistent:
|
||||
reload_layers.setdefault(id(copy.destination_module), copy.destination_module)
|
||||
|
||||
reload_layer_groups: dict[int, int] = {}
|
||||
for copy in copies:
|
||||
layer_id = id(copy.destination_module)
|
||||
if layer_id not in reload_layers:
|
||||
continue
|
||||
source_group = tensor_groups[copy.source_name]
|
||||
previous_group = reload_layer_groups.setdefault(layer_id, source_group)
|
||||
if previous_group != source_group:
|
||||
raise RuntimeError(
|
||||
f"vLLM reload layer {type(copy.destination_module).__name__} reads trainer groups "
|
||||
f"{table.groups[previous_group].name!r} and {table.groups[source_group].name!r}"
|
||||
)
|
||||
|
||||
agent_devices = {agent_index: agent.device_id for agent_index, agent in enumerate(table.agents)}
|
||||
peer_names: dict[int, str] = {}
|
||||
transfer_groups: list[WeightTransferGroup] = []
|
||||
|
||||
for group_index, group in enumerate(table.groups):
|
||||
copy_plans_by_layer: dict[int, list[TensorCopyPlan]] = defaultdict(list)
|
||||
persistent_plans_by_layer: dict[int, list[TensorCopyPlan]] = defaultdict(list)
|
||||
local_descs: dict[int, list[MemDesc]] = defaultdict(list)
|
||||
remote_descs: dict[int, list[MemDesc]] = defaultdict(list)
|
||||
cursors = {
|
||||
dtype: (group_index % receive_buffer_count) * elements
|
||||
for dtype, elements in receive_buffer_elements.items()
|
||||
}
|
||||
|
||||
for copy in copies_by_group[group_index]:
|
||||
replay_plan = replay_plans[id(copy)]
|
||||
source = tensors[copy.source_name]
|
||||
source_dtype = getattr(torch, source.wire_dtype)
|
||||
numel = prod(replay_plan.source_shape)
|
||||
cursor = cursors[source_dtype]
|
||||
staging_tensor = receive_arenas[source_dtype].narrow(0, cursor, numel).view(replay_plan.source_shape)
|
||||
cursors[source_dtype] += numel
|
||||
copy_plan = TensorCopyPlan(
|
||||
recorded_copy=copy,
|
||||
staging_tensor=staging_tensor,
|
||||
replay_ops=replay_plan.replay_ops,
|
||||
)
|
||||
plans = persistent_plans_by_layer if copy.is_persistent else copy_plans_by_layer
|
||||
plans[id(copy.destination_module)].append(copy_plan)
|
||||
|
||||
for route in route_sharded_tensor(replay_plan, source, staging_tensor):
|
||||
local_descs[route.agent].append((route.destination_addr, route.nbytes, self.device.index))
|
||||
remote_descs[route.agent].append((route.source_addr, route.nbytes, agent_devices[route.agent]))
|
||||
|
||||
transfer_groups.append(
|
||||
WeightTransferGroup(
|
||||
name=group.name,
|
||||
layers=self.build_layer_transfer_plans(
|
||||
reload_layers,
|
||||
copy_plans_by_layer,
|
||||
persistent_plans_by_layer,
|
||||
),
|
||||
pulls=self.prepare_group_pulls(
|
||||
table,
|
||||
local_descs,
|
||||
remote_descs,
|
||||
peer_names,
|
||||
),
|
||||
)
|
||||
)
|
||||
return transfer_groups
|
||||
|
||||
def build_layer_transfer_plans(
|
||||
self,
|
||||
reload_layers: dict[int, nn.Module],
|
||||
copy_plans_by_layer: dict[int, list[TensorCopyPlan]],
|
||||
persistent_plans_by_layer: dict[int, list[TensorCopyPlan]],
|
||||
) -> list[LayerWeightTransferPlan]:
|
||||
layer_plans: list[LayerWeightTransferPlan] = []
|
||||
for layer_id, layer in reload_layers.items():
|
||||
copies = copy_plans_by_layer.get(layer_id, [])
|
||||
persistent_copies = persistent_plans_by_layer.get(layer_id, [])
|
||||
if copies:
|
||||
layer_plans.append(
|
||||
LayerWeightTransferPlan(
|
||||
reload_layer=layer,
|
||||
copies=copies,
|
||||
persistent_copies=persistent_copies,
|
||||
)
|
||||
)
|
||||
elif persistent_copies:
|
||||
layer_plans.append(
|
||||
LayerWeightTransferPlan(
|
||||
reload_layer=None,
|
||||
copies=[],
|
||||
persistent_copies=persistent_copies,
|
||||
)
|
||||
)
|
||||
|
||||
remaining_persistent = [
|
||||
plan
|
||||
for layer_id, plans in persistent_plans_by_layer.items()
|
||||
if layer_id not in reload_layers
|
||||
for plan in plans
|
||||
]
|
||||
if remaining_persistent:
|
||||
layer_plans.append(
|
||||
LayerWeightTransferPlan(
|
||||
reload_layer=None,
|
||||
copies=[],
|
||||
persistent_copies=remaining_persistent,
|
||||
)
|
||||
)
|
||||
return layer_plans
|
||||
|
||||
def prepare_group_pulls(
|
||||
self,
|
||||
table: TrainerTensorTable,
|
||||
local_descs: dict[int, list[MemDesc]],
|
||||
remote_descs: dict[int, list[MemDesc]],
|
||||
peer_names: dict[int, str],
|
||||
) -> list[tuple[Any, Any, list[int]]]:
|
||||
pulls: list[tuple[Any, Any, list[int]]] = []
|
||||
for agent_index, remote in sorted(remote_descs.items()):
|
||||
peer_name = peer_names.get(agent_index)
|
||||
if peer_name is None:
|
||||
peer_name = self.nixl_agent.add_remote_agent(table.agents[agent_index].metadata)
|
||||
self.nixl_agent.make_connection(peer_name)
|
||||
peer_names[agent_index] = peer_name
|
||||
local_prepared = self.nixl_agent.prepare_xfer_dlist(local_descs[agent_index])
|
||||
remote_prepared = self.nixl_agent.prepare_xfer_dlist(remote, agent_name=peer_name)
|
||||
pulls.append((local_prepared, remote_prepared, list(range(len(remote)))))
|
||||
return pulls
|
||||
|
||||
@torch.no_grad()
|
||||
def update_weights_from_path(self, weight_dir: str | None = None) -> None:
|
||||
del weight_dir
|
||||
plan = self.initialize_transfer()
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.model_express.wait_for(
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_READY,
|
||||
timeout=self.weight_transfer_timeout,
|
||||
)
|
||||
|
||||
started = time.perf_counter()
|
||||
self.apply_transfer_plan(plan)
|
||||
update_mla_absorbed_weights(self.raw_model)
|
||||
torch.cuda.synchronize(self.device)
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_READY)
|
||||
logger.info(
|
||||
"Applied NIXL policy update on rank %d in %.2fs",
|
||||
self.model_express.rank,
|
||||
time.perf_counter() - started,
|
||||
)
|
||||
|
||||
def apply_transfer_plan(self, plan: WeightTransferPlan) -> None:
|
||||
from vllm.model_executor.layers.quantization.base_config import QuantizeMethodBase
|
||||
from vllm.model_executor.model_loader.reload.layerwise import (
|
||||
LAYERWISE_INFO,
|
||||
_copy_and_restore_kernel_tensors,
|
||||
finalize_layerwise_reload,
|
||||
initialize_layerwise_reload,
|
||||
)
|
||||
from vllm.model_executor.model_loader.reload.meta import materialize_layer
|
||||
from vllm.model_executor.model_loader.reload.utils import get_layer_tensors
|
||||
|
||||
model = self.raw_model
|
||||
cancelled = Event()
|
||||
|
||||
def pull_group(group_index: int) -> WeightTransferGroup:
|
||||
transfer_group = plan.groups[group_index]
|
||||
session = self.buffer_sessions[group_index % len(self.buffer_sessions)]
|
||||
session.wait_for(
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_READY,
|
||||
timeout=self.weight_transfer_timeout,
|
||||
poll_interval=_BUFFER_POLL_INTERVAL,
|
||||
cancelled=cancelled.is_set,
|
||||
)
|
||||
|
||||
for local, remote, indices in transfer_group.pulls:
|
||||
handle = self.nixl_agent.post_read(local, indices, remote)
|
||||
self.nixl_agent.wait(
|
||||
handle,
|
||||
context=f"weight pull for {transfer_group.name}",
|
||||
timeout=self.weight_transfer_timeout,
|
||||
cancelled=cancelled.is_set,
|
||||
)
|
||||
return transfer_group
|
||||
|
||||
def acknowledge_group(group_index: int) -> None:
|
||||
session = self.buffer_sessions[group_index % len(self.buffer_sessions)]
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_READY)
|
||||
session.wait_for(
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
|
||||
timeout=self.weight_transfer_timeout,
|
||||
poll_interval=_BUFFER_POLL_INTERVAL,
|
||||
cancelled=cancelled.is_set,
|
||||
)
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
|
||||
def prefetch_group(group_index: int) -> WeightTransferGroup:
|
||||
torch.cuda.set_device(self.device)
|
||||
transfer_group = pull_group(group_index)
|
||||
acknowledge_group(group_index)
|
||||
return transfer_group
|
||||
|
||||
def replay_group(transfer_group: WeightTransferGroup) -> None:
|
||||
for layer_plan in transfer_group.layers:
|
||||
layer = layer_plan.reload_layer
|
||||
if layer is None:
|
||||
for copy_plan in layer_plan.persistent_copies:
|
||||
self.replay_tensor_copy(copy_plan)
|
||||
continue
|
||||
|
||||
info = LAYERWISE_INFO[layer]
|
||||
materialize_layer(layer, info)
|
||||
# Match loader semantics for destinations with unwritten padding.
|
||||
destination_names = layer_plan.destination_names
|
||||
for name, tensor in get_layer_tensors(layer).items():
|
||||
if name in destination_names and not tensor.is_meta:
|
||||
tensor.zero_()
|
||||
for copy_plan in layer_plan.copies:
|
||||
self.replay_tensor_copy(copy_plan)
|
||||
for copy_plan in layer_plan.persistent_copies:
|
||||
self.replay_tensor_copy(copy_plan)
|
||||
|
||||
if hasattr(layer, "_already_called_process_weights_after_loading"):
|
||||
delattr(layer, "_already_called_process_weights_after_loading")
|
||||
quant_method = getattr(layer, "quant_method", None)
|
||||
if isinstance(quant_method, QuantizeMethodBase):
|
||||
quant_method.process_weights_after_loading(layer)
|
||||
if info.kernel_tensors is not None:
|
||||
_copy_and_restore_kernel_tensors(layer, info)
|
||||
info.reset()
|
||||
|
||||
with torch.device(self.device), set_current_vllm_config(self.vllm_config):
|
||||
initialize_layerwise_reload(model)
|
||||
pipelined = plan.receive_buffer_count > 1
|
||||
executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="nixl-prefetch") if pipelined else None
|
||||
try:
|
||||
pull = executor.submit(prefetch_group, 0) if executor is not None else None
|
||||
for group_index in range(len(plan.groups)):
|
||||
transfer_group = pull.result() if pull is not None else pull_group(group_index)
|
||||
|
||||
torch.cuda.synchronize(self.device)
|
||||
if executor is not None and group_index + 1 < len(plan.groups):
|
||||
pull = executor.submit(prefetch_group, group_index + 1)
|
||||
|
||||
replay_group(transfer_group)
|
||||
torch.cuda.synchronize(self.device)
|
||||
|
||||
if not pipelined:
|
||||
acknowledge_group(group_index)
|
||||
finally:
|
||||
cancelled.set()
|
||||
if executor is not None:
|
||||
executor.shutdown(wait=True, cancel_futures=True)
|
||||
|
||||
finalize_layerwise_reload(model, self.model_runner.model_config)
|
||||
|
||||
@staticmethod
|
||||
def replay_tensor_copy(plan: TensorCopyPlan) -> None:
|
||||
copy = plan.recorded_copy
|
||||
parameter = getattr(copy.destination_module, copy.destination_name)
|
||||
destination = parameter.as_strided(
|
||||
copy.destination_shape,
|
||||
copy.destination_stride,
|
||||
copy.destination_offset,
|
||||
)
|
||||
value = apply_chain(plan.staging_tensor, plan.replay_ops)
|
||||
destination.copy_(value)
|
||||
@@ -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,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -28,6 +28,8 @@ from typing import TYPE_CHECKING
|
||||
|
||||
import tomli_w
|
||||
import verifiers.v1 as vf
|
||||
from modelexpress import p2p_pb2
|
||||
from modelexpress.client import MxClient
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from renderers.base import Renderer
|
||||
@@ -70,9 +72,10 @@ from prime_rl.orchestrator.utils import (
|
||||
)
|
||||
from prime_rl.orchestrator.watcher import WeightWatcher
|
||||
from prime_rl.trainer.model import setup_tokenizer
|
||||
from prime_rl.trainer.rl.broadcast.nixl.model_express import ModelExpressSession
|
||||
from prime_rl.transport import TrainingBatch, setup_training_batch_sender
|
||||
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
|
||||
from prime_rl.utils.client import init_nccl_broadcast
|
||||
from prime_rl.utils.client import init_nccl_broadcast, init_nixl_broadcast
|
||||
from prime_rl.utils.config import to_toml_dict
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
@@ -189,6 +192,7 @@ class Orchestrator:
|
||||
self.lora_name = None
|
||||
self.resume_step = None
|
||||
self.lag_task = None
|
||||
self.model_express = None
|
||||
|
||||
# ── lifecycle ──────────────────────────────────────────────────────────
|
||||
|
||||
@@ -227,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,
|
||||
@@ -308,6 +313,24 @@ class Orchestrator:
|
||||
inference_world_size=config.weight_broadcast.inference_world_size,
|
||||
quantize_in_weight_transfer=config.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
elif config.weight_broadcast.type == "nixl":
|
||||
await init_nixl_broadcast(
|
||||
self.policy_inference.admin_clients,
|
||||
config.weight_broadcast.host,
|
||||
config.weight_broadcast.port,
|
||||
config.weight_broadcast.timeout,
|
||||
config.weight_broadcast.inference_world_size,
|
||||
config.weight_broadcast.session_id,
|
||||
)
|
||||
self.model_express = ModelExpressSession(
|
||||
client=MxClient(server_url=f"{config.weight_broadcast.host}:{config.weight_broadcast.port}"),
|
||||
role="orchestrator",
|
||||
rank=0,
|
||||
session_id=config.weight_broadcast.session_id,
|
||||
worker_id="orchestrator",
|
||||
)
|
||||
self.model_express.publish()
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
|
||||
get_logger().info(f"Initializing training batch sender ({config.rollout_transport})")
|
||||
self.sender = setup_training_batch_sender(config.output_dir, config.rollout_transport)
|
||||
@@ -325,18 +348,31 @@ class Orchestrator:
|
||||
get_logger().info("Training from scratch")
|
||||
|
||||
# Sync inference to the incoming policy before the first step when resuming or when using
|
||||
# NCCL, which rendezvouses with the trainer's first-step broadcast (train.py). A fresh
|
||||
# filesystem run needs no sync (the base model IS policy v0) and must not wait for a
|
||||
# startup broadcast: runs registered after the trainer's first step never receive one.
|
||||
if self.resume_step is not None or config.weight_broadcast.type == "nccl":
|
||||
# an in-memory transport, which rendezvouses with the trainer's startup broadcast.
|
||||
if self.resume_step is not None or config.weight_broadcast.type in ("nccl", "nixl"):
|
||||
sync_version = self.resume_step if self.resume_step is not None else 0
|
||||
check_exists = config.weight_broadcast.type != "nccl"
|
||||
# Without a ckpt block, fall back to a default timeout instead of not waiting at all.
|
||||
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else STARTUP_WEIGHT_WAIT_TIMEOUT_S
|
||||
weights_path = get_weight_dir(
|
||||
config.output_dir, sync_version, check_exists=check_exists, wait_timeout=wait_timeout
|
||||
)
|
||||
if config.weight_broadcast.type == "nixl":
|
||||
weights_path = None
|
||||
else:
|
||||
check_exists = config.weight_broadcast.type == "filesystem"
|
||||
# Without a ckpt block, fall back to a default timeout instead of not waiting at all.
|
||||
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else STARTUP_WEIGHT_WAIT_TIMEOUT_S
|
||||
weights_path = get_weight_dir(
|
||||
config.output_dir, sync_version, check_exists=check_exists, wait_timeout=wait_timeout
|
||||
)
|
||||
if self.model_express is not None:
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_READY)
|
||||
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=sync_version)
|
||||
if self.model_express is not None:
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
# Complete the startup rendezvous before the watcher begins its next cycle.
|
||||
await asyncio.to_thread(
|
||||
self.model_express.wait_for,
|
||||
"trainer",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
|
||||
timeout=config.weight_broadcast.timeout,
|
||||
)
|
||||
if self.lora_name is not None:
|
||||
self.policy_inference.update_model_name(self.lora_name)
|
||||
self.policy.model_name = self.lora_name
|
||||
@@ -385,6 +421,7 @@ class Orchestrator:
|
||||
observers=[self.dispatcher, self],
|
||||
lora_name=self.lora_name,
|
||||
ckpt_step=self.policy.version,
|
||||
model_express=self.model_express,
|
||||
)
|
||||
# Single periodic logger for the whole pipeline. It's the only
|
||||
# consumer of ``dispatcher.metrics.drained()`` (which clears on read)
|
||||
@@ -843,18 +880,16 @@ class Orchestrator:
|
||||
are 1-indexed while policy versions stay 0-indexed, so the shipped-batch
|
||||
count is ``progress.step - 1``."""
|
||||
lead = (self.progress.step - 1) - self.policy.version
|
||||
# The trainer skips the final NCCL weight broadcast (inference group is
|
||||
# torn down), so policy.version never reaches the last step. Without this
|
||||
# the gate deadlocks waiting for a version that will never be published.
|
||||
# The last batch uses the penultimate policy anyway, so let it through.
|
||||
building_final_batch_nccl = (
|
||||
self.config.weight_broadcast.type == "nccl"
|
||||
# The trainer skips the final in-memory weight broadcasts, so policy.version never
|
||||
# reaches the last step. Let the final batch through instead of waiting for it.
|
||||
building_final_batch_without_update = (
|
||||
self.config.weight_broadcast.type in ("nccl", "nixl")
|
||||
and self.config.max_steps is not None
|
||||
and self.progress.step >= self.config.max_steps - 1
|
||||
)
|
||||
gate = self.dispatcher.dispatch_allowed
|
||||
was_set = gate.is_set()
|
||||
if lead > TARGET_LAG and not building_final_batch_nccl:
|
||||
if lead > TARGET_LAG and not building_final_batch_without_update:
|
||||
if was_set:
|
||||
get_logger().info(
|
||||
"Pausing dispatcher to prevent orchestrator from racing from trainer. Waiting for new policy..."
|
||||
@@ -870,12 +905,14 @@ class Orchestrator:
|
||||
gate.set()
|
||||
|
||||
async def on_version_pending(self, step: int) -> None:
|
||||
"""No-op: the dispatch gate is re-evaluated in ``on_new_version`` once
|
||||
the new policy version is live."""
|
||||
if self.model_express is not None:
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_READY)
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
"""``VersionObserver`` hook: the watcher just advanced ``policy.version``;
|
||||
re-evaluate the dispatch gate (may resume if the trainer caught up)."""
|
||||
if self.model_express is not None:
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.update_dispatch_gate()
|
||||
|
||||
async def stop(self) -> None:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -7,8 +7,11 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import time
|
||||
|
||||
from modelexpress import p2p_pb2
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.types import Policy, VersionObserver
|
||||
from prime_rl.trainer.rl.broadcast.nixl.model_express import ModelExpressSession
|
||||
from prime_rl.utils.async_utils import safe_cancel
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
@@ -29,6 +32,7 @@ class WeightWatcher:
|
||||
lora_name: str | None,
|
||||
ckpt_step: int = 0,
|
||||
poll_interval: float = 1.0,
|
||||
model_express: ModelExpressSession | None = None,
|
||||
) -> None:
|
||||
self.config = config
|
||||
self.policy = policy
|
||||
@@ -37,6 +41,7 @@ class WeightWatcher:
|
||||
self.lora_name = lora_name
|
||||
self.ckpt_step = ckpt_step
|
||||
self.poll_interval = poll_interval
|
||||
self.model_express = model_express
|
||||
|
||||
self.last_update_weights_time: float = 0.0
|
||||
self.last_wait_for_ckpt_time: float = 0.0
|
||||
@@ -64,9 +69,14 @@ class WeightWatcher:
|
||||
self.task = None
|
||||
|
||||
def compute_next_ckpt_step(self) -> int:
|
||||
"""Next checkpoint to adopt — at least ``policy.version`` (we stay
|
||||
one step ahead of the trainer) plus anything fresher already
|
||||
published in ``broadcasts/``."""
|
||||
"""Return the next policy version exposed by the configured transport."""
|
||||
if self.model_express is not None:
|
||||
if self.config.max_steps is not None and self.ckpt_step >= self.config.max_steps - 2:
|
||||
return self.ckpt_step
|
||||
# ModelExpress status changes are unversioned, so its rendezvous advances
|
||||
# exactly one policy version per READY/INITIALIZING cycle.
|
||||
return self.ckpt_step + 1
|
||||
|
||||
broadcast_dir = get_broadcast_dir(self.config.output_dir)
|
||||
latest_ckpt_step = get_latest_ckpt_step(broadcast_dir) or 0
|
||||
return max(self.policy.version, latest_ckpt_step)
|
||||
@@ -77,20 +87,21 @@ class WeightWatcher:
|
||||
# Another caller raced us — bail without re-applying
|
||||
return
|
||||
|
||||
broadcast_dir = get_broadcast_dir(self.config.output_dir)
|
||||
weights_path = get_step_path(broadcast_dir, next_step)
|
||||
stable_marker = weights_path / "STABLE"
|
||||
if not stable_marker.exists():
|
||||
get_logger().info(
|
||||
f"Orchestrator paused: waiting for trainer to broadcast checkpoint {next_step}. "
|
||||
"Training is progressing normally."
|
||||
)
|
||||
t0 = time.perf_counter()
|
||||
await wait_for_path(stable_marker)
|
||||
self.last_wait_for_ckpt_time = time.perf_counter() - t0
|
||||
get_logger().info(
|
||||
f"Orchestrator resumed: checkpoint {next_step} ready (after {format_time(self.last_wait_for_ckpt_time)})"
|
||||
)
|
||||
t0 = time.perf_counter()
|
||||
weights_path = None
|
||||
if self.model_express is not None:
|
||||
await self.wait_for_model_express_status(p2p_pb2.SOURCE_STATUS_READY)
|
||||
else:
|
||||
broadcast_dir = get_broadcast_dir(self.config.output_dir)
|
||||
weights_path = get_step_path(broadcast_dir, next_step)
|
||||
stable_marker = weights_path / "STABLE"
|
||||
if not stable_marker.exists():
|
||||
get_logger().info(
|
||||
f"Orchestrator paused: waiting for trainer to broadcast checkpoint {next_step}. "
|
||||
"Training is progressing normally."
|
||||
)
|
||||
await wait_for_path(stable_marker)
|
||||
self.last_wait_for_ckpt_time = time.perf_counter() - t0
|
||||
|
||||
# Drain off-policy rollouts BEFORE pausing the inference engines.
|
||||
# Aborting a rollout triggers vLLM's KV-connector cleanup (NIXL's
|
||||
@@ -131,6 +142,21 @@ class WeightWatcher:
|
||||
f"Observer {type(observer).__name__}.on_new_version({next_step}) raised: {exc!r}"
|
||||
)
|
||||
|
||||
if self.model_express is not None:
|
||||
await self.wait_for_model_express_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
|
||||
async def wait_for_model_express_status(self, status: int) -> None:
|
||||
while not self.stopped.is_set():
|
||||
found = await asyncio.to_thread(
|
||||
self.model_express.exists_role_with_status,
|
||||
"trainer",
|
||||
status,
|
||||
)
|
||||
if found:
|
||||
return
|
||||
await asyncio.sleep(self.poll_interval)
|
||||
raise asyncio.CancelledError
|
||||
|
||||
def gauges(self) -> dict[str, float]:
|
||||
return {
|
||||
"watcher/policy_version": float(self.policy.version),
|
||||
|
||||
@@ -38,18 +38,29 @@ AutoConfig.register("qwen3_5_moe_text", Qwen3_5MoeConfig, exist_ok=True)
|
||||
# GptOssConfig is just HF's class - already registered by transformers, no override needed.
|
||||
|
||||
_CUSTOM_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, OrderedDict())
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(LlamaConfig, LlamaForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3Config, Qwen3ForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(AfmoeConfig, AfmoeForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Glm4MoeConfig, Glm4MoeForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(GlmMoeDsaConfig, GlmMoeDsaForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(LagunaConfig, LagunaForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(MiniMaxM2Config, MiniMaxM2ForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(NemotronHConfig, NemotronHForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3MoeConfig, Qwen3MoeForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3_5TextConfig, Qwen3_5ForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3_5MoeConfig, Qwen3_5MoeForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(GptOssConfig, GptOssForCausalLM, exist_ok=True)
|
||||
_CUSTOM_CAUSAL_LM_MODELS: tuple[
|
||||
tuple[type[PretrainedConfig], type[PreTrainedModelPrimeRL]],
|
||||
...,
|
||||
] = (
|
||||
(LlamaConfig, LlamaForCausalLM),
|
||||
(Qwen3Config, Qwen3ForCausalLM),
|
||||
(AfmoeConfig, AfmoeForCausalLM),
|
||||
(Glm4MoeConfig, Glm4MoeForCausalLM),
|
||||
(GlmMoeDsaConfig, GlmMoeDsaForCausalLM),
|
||||
(LagunaConfig, LagunaForCausalLM),
|
||||
(MiniMaxM2Config, MiniMaxM2ForCausalLM),
|
||||
(NemotronHConfig, NemotronHForCausalLM),
|
||||
(Qwen3MoeConfig, Qwen3MoeForCausalLM),
|
||||
(Qwen3_5TextConfig, Qwen3_5ForCausalLM),
|
||||
(Qwen3_5MoeConfig, Qwen3_5MoeForCausalLM),
|
||||
(GptOssConfig, GptOssForCausalLM),
|
||||
)
|
||||
for config_cls, model_cls in _CUSTOM_CAUSAL_LM_MODELS:
|
||||
_CUSTOM_CAUSAL_LM_MAPPING.register(config_cls, model_cls, exist_ok=True)
|
||||
|
||||
_CUSTOM_CAUSAL_LM_BY_MODEL_TYPE = {
|
||||
config_cls.model_type: model_cls for config_cls, model_cls in _CUSTOM_CAUSAL_LM_MODELS
|
||||
}
|
||||
|
||||
|
||||
class AutoModelForCausalLMPrimeRL(_BaseAutoModelClass):
|
||||
@@ -59,6 +70,11 @@ class AutoModelForCausalLMPrimeRL(_BaseAutoModelClass):
|
||||
AutoModelForCausalLMPrimeRL = auto_class_update(AutoModelForCausalLMPrimeRL, head_doc="causal language modeling")
|
||||
|
||||
|
||||
def get_custom_causal_lm_cls(model_config: PretrainedConfig) -> type[PreTrainedModelPrimeRL]:
|
||||
"""Resolve the PrimeRL model class from a possibly non-PrimeRL config instance."""
|
||||
return _CUSTOM_CAUSAL_LM_BY_MODEL_TYPE[model_config.model_type]
|
||||
|
||||
|
||||
def supports_custom_impl(model_config: PretrainedConfig) -> bool:
|
||||
"""Check if the model configuration supports the custom PrimeRL implementation.
|
||||
|
||||
@@ -88,6 +104,7 @@ def get_custom_vlm_cls(model_config: PretrainedConfig) -> type | None:
|
||||
__all__ = [
|
||||
"AutoModelForCausalLMPrimeRL",
|
||||
"PreTrainedModelPrimeRL",
|
||||
"get_custom_causal_lm_cls",
|
||||
"supports_custom_impl",
|
||||
"get_custom_vlm_cls",
|
||||
"PrimeLmOutput",
|
||||
|
||||
@@ -1,138 +1,30 @@
|
||||
import re
|
||||
"""HF<->prime weight conversion for AFMoE, as a declarative op chain.
|
||||
|
||||
import torch
|
||||
from torch import Tensor
|
||||
AFMoE specifics:
|
||||
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
* Per-layer MLP prefix is ``model.layers.{i}.mlp``.
|
||||
* The router shares its name between HF and prime, so it is *not* renamed.
|
||||
* Shared experts: HF ``shared_experts.{gate,down,up}_proj.weight`` map to prime
|
||||
``shared_expert.{w1,w2,w3}`` (no ``.weight`` suffix on the prime side).
|
||||
* Routed experts: HF per-expert ``experts.{e}.{gate,down,up}_proj.weight`` stack
|
||||
into prime ``experts.{w1,w2,w3}`` along dim 0 (no fused gate_up layout).
|
||||
* Prime-only runtime buffers ``mlp.tokens_per_expert`` and ``mlp.reorderer.*``
|
||||
are dropped on the way back to HF.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import GATE_DOWN_UP, ConvOp, Drop, Rename, Stack
|
||||
|
||||
|
||||
def get_num_experts_from_state_dict(state_dict: dict[str, Tensor], layer_idx: int) -> int:
|
||||
"""Get the number of experts from the HF state dict for a given layer."""
|
||||
pattern = re.compile(rf"model\.layers\.{layer_idx}\.mlp\.experts\.(\d+)\.")
|
||||
expert_indices = set()
|
||||
for key in state_dict.keys():
|
||||
match = pattern.search(key)
|
||||
if match:
|
||||
expert_indices.add(int(match.group(1)))
|
||||
return len(expert_indices)
|
||||
|
||||
|
||||
def is_moe_layer_hf(state_dict: dict[str, Tensor], layer_idx: int) -> bool:
|
||||
"""Check if a layer is a MoE layer in HF format."""
|
||||
return any(f"model.layers.{layer_idx}.mlp.experts." in k for k in state_dict.keys())
|
||||
|
||||
|
||||
def is_moe_layer_tt(state_dict: dict[str, Tensor], layer_idx: int) -> bool:
|
||||
"""Check if a layer is a MoE layer in TT format."""
|
||||
return f"model.layers.{layer_idx}.mlp.experts.w1" in state_dict
|
||||
|
||||
|
||||
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int) -> None:
|
||||
"""Convert a single MoE layer from HF format to TT format in-place.
|
||||
|
||||
Args:
|
||||
state_dict: The state dict to modify in-place.
|
||||
layer_idx: The layer index to convert.
|
||||
"""
|
||||
prefix = f"model.layers.{layer_idx}.mlp"
|
||||
|
||||
# Check if this is a MoE layer (has individual experts)
|
||||
is_moe_layer = is_moe_layer_hf(state_dict, layer_idx)
|
||||
if not is_moe_layer:
|
||||
return # Dense layer, no conversion needed
|
||||
|
||||
num_experts = get_num_experts_from_state_dict(state_dict, layer_idx)
|
||||
if num_experts == 0:
|
||||
return
|
||||
|
||||
# Convert shared experts: shared_experts -> shared_expert, gate_proj/up_proj/down_proj -> w1/w3/w2
|
||||
shared_mappings = [
|
||||
(f"{prefix}.shared_experts.gate_proj.weight", f"{prefix}.shared_expert.w1"),
|
||||
(f"{prefix}.shared_experts.down_proj.weight", f"{prefix}.shared_expert.w2"),
|
||||
(f"{prefix}.shared_experts.up_proj.weight", f"{prefix}.shared_expert.w3"),
|
||||
]
|
||||
for hf_key, tt_key in shared_mappings:
|
||||
if hf_key in state_dict:
|
||||
state_dict[tt_key] = state_dict.pop(hf_key)
|
||||
|
||||
# Stack individual expert weights into grouped format
|
||||
# HF: experts.{i}.gate_proj.weight [hidden_dim, hidden_size]
|
||||
# TT: experts.w1 [num_experts, hidden_dim, hidden_size]
|
||||
expert_mappings = [
|
||||
("gate_proj", "w1"),
|
||||
("down_proj", "w2"),
|
||||
("up_proj", "w3"),
|
||||
]
|
||||
|
||||
for hf_name, tt_name in expert_mappings:
|
||||
expert_weights = []
|
||||
for i in range(num_experts):
|
||||
hf_key = f"{prefix}.experts.{i}.{hf_name}.weight"
|
||||
if hf_key in state_dict:
|
||||
expert_weights.append(state_dict.pop(hf_key))
|
||||
|
||||
if expert_weights:
|
||||
# Stack along first dimension: [num_experts, out_dim, in_dim]
|
||||
stacked = torch.stack(expert_weights, dim=0)
|
||||
state_dict[f"{prefix}.experts.{tt_name}"] = stacked
|
||||
|
||||
|
||||
def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int) -> None:
|
||||
"""Convert a single MoE layer from TT format to HF format in-place.
|
||||
|
||||
Args:
|
||||
state_dict: The state dict to modify in-place.
|
||||
layer_idx: The layer index to convert.
|
||||
"""
|
||||
prefix = f"model.layers.{layer_idx}.mlp"
|
||||
|
||||
# Check if this is a MoE layer in TT format
|
||||
if not is_moe_layer_tt(state_dict, layer_idx):
|
||||
return # Dense layer, no conversion needed
|
||||
|
||||
# Convert shared expert: shared_expert -> shared_experts, w1/w2/w3 -> gate_proj/down_proj/up_proj
|
||||
shared_mappings = [
|
||||
(f"{prefix}.shared_expert.w1", f"{prefix}.shared_experts.gate_proj.weight"),
|
||||
(f"{prefix}.shared_expert.w2", f"{prefix}.shared_experts.down_proj.weight"),
|
||||
(f"{prefix}.shared_expert.w3", f"{prefix}.shared_experts.up_proj.weight"),
|
||||
]
|
||||
for tt_key, hf_key in shared_mappings:
|
||||
if tt_key in state_dict:
|
||||
state_dict[hf_key] = state_dict.pop(tt_key)
|
||||
|
||||
# Unstack grouped expert weights into individual experts
|
||||
expert_mappings = [
|
||||
("w1", "gate_proj"),
|
||||
("w2", "down_proj"),
|
||||
("w3", "up_proj"),
|
||||
]
|
||||
|
||||
for tt_name, hf_name in expert_mappings:
|
||||
tt_key = f"{prefix}.experts.{tt_name}"
|
||||
if tt_key in state_dict:
|
||||
stacked = state_dict.pop(tt_key)
|
||||
num_experts = stacked.shape[0]
|
||||
for i in range(num_experts):
|
||||
hf_key = f"{prefix}.experts.{i}.{hf_name}.weight"
|
||||
state_dict[hf_key] = stacked[i]
|
||||
|
||||
# Remove TT-specific buffers that don't exist in HF
|
||||
for key in list(state_dict.keys()):
|
||||
if f"{prefix}.tokens_per_expert" in key:
|
||||
del state_dict[key]
|
||||
if f"{prefix}.reorderer" in key:
|
||||
del state_dict[key]
|
||||
|
||||
|
||||
def convert_hf_to_tt_moe(state_dict: dict[str, Tensor]) -> None:
|
||||
"""Convert all MoE layers from HF format to TT format in-place."""
|
||||
num_layers = get_max_layer_num(state_dict)
|
||||
for layer_idx in range(num_layers):
|
||||
convert_hf_layer_to_tt(state_dict, layer_idx)
|
||||
|
||||
|
||||
def convert_tt_to_hf_moe(state_dict: dict[str, Tensor]) -> None:
|
||||
"""Convert all MoE layers from TT format to HF format in-place."""
|
||||
num_layers = get_max_layer_num(state_dict)
|
||||
for layer_idx in range(num_layers):
|
||||
convert_tt_layer_to_hf(state_dict, layer_idx)
|
||||
def conversion_chain(config) -> list[ConvOp]:
|
||||
ops: list[ConvOp] = []
|
||||
for i in range(config.num_hidden_layers):
|
||||
p = f"model.layers.{i}.mlp"
|
||||
for wn, hf_proj in GATE_DOWN_UP:
|
||||
ops.append(Rename(f"{p}.shared_experts.{hf_proj}.weight", f"{p}.shared_expert.{wn}"))
|
||||
for wn, hf_proj in GATE_DOWN_UP:
|
||||
ops.append(Stack(stacked=f"{p}.experts.{wn}", item=f"{p}.experts.{{e}}.{hf_proj}.weight"))
|
||||
ops.append(Drop(f"{p}.tokens_per_expert"))
|
||||
ops.append(Drop(f"{p}.reorderer", is_prefix=True))
|
||||
return ops
|
||||
|
||||
@@ -31,12 +31,7 @@ from prime_rl.trainer.models.layers.rotary_emb import (
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
from .configuration_afmoe import AfmoeConfig
|
||||
from .converting_afmoe import (
|
||||
convert_hf_layer_to_tt,
|
||||
convert_hf_to_tt_moe,
|
||||
convert_tt_layer_to_hf,
|
||||
convert_tt_to_hf_moe,
|
||||
)
|
||||
from .converting_afmoe import conversion_chain
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -333,24 +328,8 @@ class AfmoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
return any("mlp.experts.w1" in module_name for module_name in state_dict.keys())
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
|
||||
convert_tt_to_hf_moe(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_to_prime(cls, state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
|
||||
convert_hf_to_tt_moe(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_hf(cls, state_dict: dict[str, torch.Tensor], layer_idx: int) -> dict[str, torch.Tensor]:
|
||||
convert_tt_layer_to_hf(state_dict, layer_idx)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_prime(cls, state_dict: dict[str, torch.Tensor], layer_idx: int) -> dict[str, torch.Tensor]:
|
||||
convert_hf_layer_to_tt(state_dict, layer_idx)
|
||||
return state_dict
|
||||
def conversion_chain(cls, config):
|
||||
return conversion_chain(config)
|
||||
|
||||
|
||||
class AfmoeModel(AfmoePreTrainedModel):
|
||||
|
||||
@@ -11,6 +11,14 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
|
||||
after loading with meta device.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
|
||||
"""Whether a tensor is stored in FP32 in the source checkpoint.
|
||||
|
||||
Runtime upcasts for training or inference do not change the wire dtype.
|
||||
"""
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, config, **kwargs):
|
||||
"""Public from_config that mirrors the Auto class API."""
|
||||
@@ -68,56 +76,29 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
|
||||
raise NotImplementedError(f"is_prime_state_dict is not implemented for {cls.__name__}")
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
"""
|
||||
Convert state dict from PrimeRL training format to HuggingFace format in-place.
|
||||
def conversion_chain(cls, config) -> list:
|
||||
"""Declarative operations converting between HF and PrimeRL state dicts."""
|
||||
return []
|
||||
|
||||
This is used when saving checkpoints or broadcasting weights to inference engines
|
||||
that expect HuggingFace-compatible format.
|
||||
def convert_to_hf(self, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
"""Convert a PrimeRL state dict to HuggingFace format in-place."""
|
||||
from prime_rl.trainer.models.conversion_ops import apply_prime_to_hf
|
||||
|
||||
Args:
|
||||
state_dict: The state dict to convert (modified in-place).
|
||||
"""
|
||||
raise NotImplementedError(f"convert_to_hf is not implemented for {cls.__name__}")
|
||||
return apply_prime_to_hf(state_dict, self.conversion_chain(self.config))
|
||||
|
||||
@classmethod
|
||||
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
"""
|
||||
Convert state dict from HuggingFace format to PrimeRL training format in-place.
|
||||
def convert_to_prime(self, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
"""Convert a HuggingFace state dict to PrimeRL format in-place."""
|
||||
from prime_rl.trainer.models.conversion_ops import apply_hf_to_prime
|
||||
|
||||
This is used when loading pretrained HuggingFace models for training with
|
||||
PrimeRL-specific optimizations.
|
||||
return apply_hf_to_prime(state_dict, self.conversion_chain(self.config))
|
||||
|
||||
Args:
|
||||
state_dict: The state dict to convert (modified in-place).
|
||||
"""
|
||||
raise NotImplementedError(f"convert_to_prime is not implemented for {cls.__name__}")
|
||||
def convert_layer_to_hf(self, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
"""Convert one layer from PrimeRL to HuggingFace format in-place."""
|
||||
return self.convert_to_hf(state_dict)
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
"""
|
||||
Convert a single layer's state dict from PrimeRL format to HuggingFace format in-place.
|
||||
|
||||
This is used for layer-by-layer conversion during NCCL broadcast to reduce memory usage.
|
||||
|
||||
Args:
|
||||
state_dict: The state dict containing the layer to convert (modified in-place).
|
||||
layer_idx: The index of the layer to convert.
|
||||
"""
|
||||
raise NotImplementedError(f"convert_layer_to_hf is not implemented for {cls.__name__}")
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
"""
|
||||
Convert a single layer's state dict from HuggingFace format to PrimeRL format in-place.
|
||||
|
||||
This is used for layer-by-layer conversion during loading.
|
||||
|
||||
Args:
|
||||
state_dict: The state dict containing the layer to convert (modified in-place).
|
||||
layer_idx: The index of the layer to convert.
|
||||
"""
|
||||
raise NotImplementedError(f"convert_layer_to_prime is not implemented for {cls.__name__}")
|
||||
def convert_layer_to_prime(self, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
"""Convert one layer from HuggingFace to PrimeRL format in-place."""
|
||||
return self.convert_to_prime(state_dict)
|
||||
|
||||
@classmethod
|
||||
def convert_adapter_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
|
||||
@@ -0,0 +1,364 @@
|
||||
"""Declarative, invertible state-dict conversion operators.
|
||||
|
||||
Every prime-rl model converts between the HuggingFace checkpoint layout and
|
||||
the PrimeRL training layout. Historically each model hand-wrote a pair of
|
||||
imperative ``convert_hf_*`` / ``convert_*_to_hf`` functions; this module
|
||||
replaces them with a declarative chain of small operators, each of which knows
|
||||
how to go *both* directions:
|
||||
|
||||
forward (``hf_to_prime``): HF checkpoint -> PrimeRL training layout
|
||||
backward (``prime_to_hf``): PrimeRL training layout -> HF checkpoint
|
||||
|
||||
A model declares a flat list of ``ConvOp``\\ s (with concrete, fully-templated
|
||||
keys). :func:`apply_hf_to_prime` plays them in order;
|
||||
:func:`apply_prime_to_hf` plays each op's backward in reverse order. The
|
||||
conversion is thus defined once and the inverse falls out for free.
|
||||
|
||||
Design constraints:
|
||||
|
||||
* **Sharding-aware, no gathers.** Pure name ops (:class:`Rename`,
|
||||
:class:`PrefixRename`, :class:`Drop`) are value-agnostic, so they operate on
|
||||
DTensors/local shards untouched. The only value-touching op,
|
||||
:class:`Stack`, stacks/unstacks along a new (expert) dim and takes an
|
||||
``expert_offset`` so a rank can unstack just its *local* experts into
|
||||
globally-numbered per-expert keys — no all-gather. Any op that genuinely
|
||||
needs a full tensor is the caller's responsibility to gather first (via the
|
||||
trainer's ``_resolve_dtensors``); none of the ops here gather on their own.
|
||||
* **Every op is present-guarded** — it no-ops when its inputs are absent — so
|
||||
the same per-layer op list can be emitted for every layer and simply skips
|
||||
dense / non-matching layers, exactly as the imperative loops did.
|
||||
* **"Backward" means "what the imperative ``*_to_hf`` did"**, not a strict
|
||||
mathematical inverse: a few conversions are intentionally lossy (e.g.
|
||||
NemotronH shifts a router bias one way and does not undo it). Such ops carry
|
||||
an explicit backward (see :class:`MapValue`).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Callable
|
||||
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
StateDict = dict[str, Tensor]
|
||||
|
||||
|
||||
class ConvOp(ABC):
|
||||
@abstractmethod
|
||||
def hf_to_prime(self, sd: StateDict) -> None: ...
|
||||
|
||||
@abstractmethod
|
||||
def prime_to_hf(self, sd: StateDict) -> None: ...
|
||||
|
||||
|
||||
def apply_hf_to_prime(sd: StateDict, ops: list[ConvOp]) -> StateDict:
|
||||
"""Play the chain forward (HF -> prime), in place."""
|
||||
for op in ops:
|
||||
op.hf_to_prime(sd)
|
||||
return sd
|
||||
|
||||
|
||||
def apply_prime_to_hf(sd: StateDict, ops: list[ConvOp]) -> StateDict:
|
||||
"""Play each op's backward in reverse order (prime -> HF), in place."""
|
||||
for op in reversed(ops):
|
||||
op.prime_to_hf(sd)
|
||||
return sd
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Name operators (value-agnostic — safe on DTensors / shards, no gather)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
@dataclass
|
||||
class Rename(ConvOp):
|
||||
"""Rename a single key. ``hf`` is the HF name, ``prime`` the PrimeRL name."""
|
||||
|
||||
hf: str
|
||||
prime: str
|
||||
|
||||
def hf_to_prime(self, sd: StateDict) -> None:
|
||||
if self.hf in sd:
|
||||
sd[self.prime] = sd.pop(self.hf)
|
||||
|
||||
def prime_to_hf(self, sd: StateDict) -> None:
|
||||
if self.prime in sd:
|
||||
sd[self.hf] = sd.pop(self.prime)
|
||||
|
||||
|
||||
@dataclass
|
||||
class PrefixRename(ConvOp):
|
||||
"""Rename every key under a prefix (e.g. ``backbone.`` <-> ``model.``,
|
||||
``mixer.`` <-> ``mamba.``, ``block_sparse_moe.`` <-> ``mlp.``)."""
|
||||
|
||||
hf: str
|
||||
prime: str
|
||||
|
||||
@staticmethod
|
||||
def _swap(sd: StateDict, old: str, new: str) -> None:
|
||||
for key in [k for k in sd if k.startswith(old)]:
|
||||
sd[new + key[len(old) :]] = sd.pop(key)
|
||||
|
||||
def hf_to_prime(self, sd: StateDict) -> None:
|
||||
self._swap(sd, self.hf, self.prime)
|
||||
|
||||
def prime_to_hf(self, sd: StateDict) -> None:
|
||||
self._swap(sd, self.prime, self.hf)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Drop(ConvOp):
|
||||
"""Drop keys (by exact name or prefix) that have no counterpart in the
|
||||
other format. Symmetric: removes matching keys whenever present, in either
|
||||
direction — covers prime-only runtime buffers dropped on the way to HF
|
||||
(``tokens_per_expert``, ``reorderer``) and HF-only keys dropped on the way
|
||||
to prime (e.g. NemotronH ``mtp.*`` multi-token-prediction heads). Only use
|
||||
for keys that are genuinely absent from one side, so neither direction
|
||||
needs to recreate them."""
|
||||
|
||||
name: str
|
||||
is_prefix: bool = False
|
||||
|
||||
def _drop(self, sd: StateDict) -> None:
|
||||
for key in [k for k in sd if (k.startswith(self.name) if self.is_prefix else k == self.name)]:
|
||||
del sd[key]
|
||||
|
||||
def hf_to_prime(self, sd: StateDict) -> None:
|
||||
self._drop(sd)
|
||||
|
||||
def prime_to_hf(self, sd: StateDict) -> None:
|
||||
self._drop(sd)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Value operators
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
@dataclass
|
||||
class Stack(ConvOp):
|
||||
"""Stack a variable-cardinality ``{e}``-indexed group of keys into one
|
||||
tensor along a NEW leading dim, and unstack back.
|
||||
|
||||
``item`` is the per-element key pattern with an ``{e}`` placeholder, e.g.
|
||||
``"…mlp.experts.{e}.gate_proj.weight"``; ``stacked`` is the combined key.
|
||||
Not MoE-specific — any indexed group (experts, layers, ...) fits.
|
||||
|
||||
* forward: collect contiguous elements ``0..N-1`` and ``torch.stack`` them.
|
||||
* backward: unstack along ``dim`` into per-element keys, numbering from
|
||||
``index_offset`` (0 for a full tensor; the global id of local row 0 when
|
||||
serving a shard — so a rank can unstack just its local slice into
|
||||
globally-numbered keys without gathering).
|
||||
"""
|
||||
|
||||
stacked: str
|
||||
item: str
|
||||
dim: int = 0
|
||||
index_offset: int = 0
|
||||
|
||||
def hf_to_prime(self, sd: StateDict) -> None:
|
||||
items: list[Tensor] = []
|
||||
e = 0
|
||||
while self.item.format(e=e) in sd:
|
||||
items.append(sd.pop(self.item.format(e=e)))
|
||||
e += 1
|
||||
if items:
|
||||
sd[self.stacked] = torch.stack(items, dim=self.dim)
|
||||
|
||||
def prime_to_hf(self, sd: StateDict) -> None:
|
||||
if self.stacked not in sd:
|
||||
return
|
||||
t = sd.pop(self.stacked)
|
||||
for e in range(t.shape[self.dim]):
|
||||
sd[self.item.format(e=self.index_offset + e)] = t.select(self.dim, e)
|
||||
|
||||
|
||||
@dataclass
|
||||
class SplitConcat(ConvOp):
|
||||
"""Split one tensor into fixed parts along an EXISTING dim, and concat back.
|
||||
|
||||
``parts`` is ``[(key, size), ...]``; ``size=None`` means an equal split
|
||||
across all parts. Forward (HF -> prime) splits ``combined`` into the part
|
||||
keys (views); backward concatenates them back. Used e.g. for the
|
||||
transformers-v5 fused ``gate_up_proj`` (two equal halves on dim 1), but is
|
||||
a general structural primitive.
|
||||
"""
|
||||
|
||||
combined: str
|
||||
parts: list[tuple[str, "int | None"]]
|
||||
dim: int = 0
|
||||
|
||||
def _sizes(self, total: int) -> list[int]:
|
||||
if all(size is None for _, size in self.parts):
|
||||
n = len(self.parts)
|
||||
assert total % n == 0, f"{self.combined}: dim {self.dim} size {total} not divisible by {n} parts"
|
||||
return [total // n] * n
|
||||
return [int(size) for _, size in self.parts]
|
||||
|
||||
def hf_to_prime(self, sd: StateDict) -> None:
|
||||
if self.combined not in sd:
|
||||
return
|
||||
t = sd.pop(self.combined)
|
||||
offset = 0
|
||||
for (key, _), size in zip(self.parts, self._sizes(t.shape[self.dim])):
|
||||
sd[key] = t.narrow(self.dim, offset, size)
|
||||
offset += size
|
||||
|
||||
def prime_to_hf(self, sd: StateDict) -> None:
|
||||
if not all(key in sd for key, _ in self.parts):
|
||||
return
|
||||
tensors = [sd.pop(key) for key, _ in self.parts]
|
||||
sd[self.combined] = torch.cat(tensors, dim=self.dim)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Synthetic(ConvOp):
|
||||
"""A prime-only tensor with no HF counterpart, created on forward and
|
||||
dropped on backward (e.g. NemotronH's dummy ``experts.w3`` of shape (0,)).
|
||||
|
||||
``factory`` builds the tensor from the current state dict (so it can match
|
||||
device/dtype of a sibling)."""
|
||||
|
||||
prime: str
|
||||
factory: Callable[[StateDict], Tensor]
|
||||
|
||||
def hf_to_prime(self, sd: StateDict) -> None:
|
||||
sd[self.prime] = self.factory(sd)
|
||||
|
||||
def prime_to_hf(self, sd: StateDict) -> None:
|
||||
sd.pop(self.prime, None)
|
||||
|
||||
|
||||
@dataclass
|
||||
class MapValue(ConvOp):
|
||||
"""Apply a value transform to one key. ``forward`` runs HF->prime,
|
||||
``backward`` runs prime->HF. Use for genuinely non-structural conversions
|
||||
(e.g. a bias shift). ``backward`` may be the identity when the imperative
|
||||
converter does not undo the transform (a deliberately lossy roundtrip)."""
|
||||
|
||||
prime: str # the PrimeRL-side key the value lives under (after any rename)
|
||||
forward: Callable[[Tensor], Tensor]
|
||||
backward: Callable[[Tensor], Tensor]
|
||||
|
||||
def hf_to_prime(self, sd: StateDict) -> None:
|
||||
if self.prime in sd:
|
||||
sd[self.prime] = self.forward(sd[self.prime])
|
||||
|
||||
def prime_to_hf(self, sd: StateDict) -> None:
|
||||
if self.prime in sd:
|
||||
sd[self.prime] = self.backward(sd[self.prime])
|
||||
|
||||
|
||||
@dataclass
|
||||
class SqueezeLeading(ConvOp):
|
||||
"""Backward-only: if a prime key carries a leading singleton dim that HF
|
||||
doesn't expect, drop it (GLM shared experts stored as ``(1, …)``). Forward
|
||||
is a no-op — prime tolerates either shape and the dim is only stripped when
|
||||
emitting HF."""
|
||||
|
||||
key: str
|
||||
|
||||
def hf_to_prime(self, sd: StateDict) -> None:
|
||||
return None
|
||||
|
||||
def prime_to_hf(self, sd: StateDict) -> None:
|
||||
if self.key in sd and sd[self.key].shape[0] == 1:
|
||||
sd[self.key] = sd[self.key][0]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Control flow
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
@dataclass
|
||||
class Conditional(ConvOp):
|
||||
"""Run ``then`` or ``else_`` depending on a predicate over the state dict.
|
||||
|
||||
The predicate is evaluated independently in each direction against the
|
||||
*current* state dict (``hf_to_prime`` sees HF keys, ``prime_to_hf`` sees
|
||||
PrimeRL keys), so the branch chosen on the way back can legitimately differ
|
||||
from the way out — which is exactly what the imperative converters do (e.g.
|
||||
accept a fused *or* per-expert HF input, but always emit per-expert)."""
|
||||
|
||||
predicate: Callable[[StateDict], bool]
|
||||
then: list[ConvOp]
|
||||
else_: list[ConvOp] = field(default_factory=list)
|
||||
|
||||
def hf_to_prime(self, sd: StateDict) -> None:
|
||||
apply_hf_to_prime(sd, self.then if self.predicate(sd) else self.else_)
|
||||
|
||||
def prime_to_hf(self, sd: StateDict) -> None:
|
||||
branch = self.then if self.predicate(sd) else self.else_
|
||||
apply_prime_to_hf(sd, branch)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Sequence(ConvOp):
|
||||
"""Bundle several ops into one (forward in order, backward reversed). Lets a
|
||||
helper return a single ``ConvOp`` built from base ops."""
|
||||
|
||||
ops: list[ConvOp]
|
||||
|
||||
def hf_to_prime(self, sd: StateDict) -> None:
|
||||
apply_hf_to_prime(sd, self.ops)
|
||||
|
||||
def prime_to_hf(self, sd: StateDict) -> None:
|
||||
apply_prime_to_hf(sd, self.ops)
|
||||
|
||||
|
||||
def key_present(name: str) -> Callable[[StateDict], bool]:
|
||||
return lambda sd: name in sd
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Shared composition helper for Llama-style routed experts (prime w1=gate,
|
||||
# w2=down, w3=up). Used by several models' converting_<model>.py.
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
GATE_DOWN_UP = (("w1", "gate_proj"), ("w2", "down_proj"), ("w3", "up_proj"))
|
||||
|
||||
|
||||
def routed_experts_op(
|
||||
prefix: str,
|
||||
*,
|
||||
hf_experts: str,
|
||||
prime_experts: str,
|
||||
proj_order=GATE_DOWN_UP,
|
||||
hf_proj_suffix: str = ".weight",
|
||||
fused: bool = False,
|
||||
) -> ConvOp:
|
||||
"""Compose the routed-experts conversion for one layer from base ops.
|
||||
|
||||
Per-expert HF weights <-> stacked prime tensors is a :class:`Stack` per
|
||||
proj. ``hf_experts``/``prime_experts`` are the (relative) expert container
|
||||
names (e.g. ``mlp.experts`` / ``block_sparse_moe.experts``); ``proj_order``
|
||||
maps prime ``wN`` to the HF per-expert proj name.
|
||||
|
||||
With ``fused`` set, the transformers-v5 fused ``gate_up_proj`` input is also
|
||||
accepted: a :class:`Conditional` on its presence splits it (dim 1) into
|
||||
w1/w3 and renames ``down_proj`` -> w2; otherwise the per-expert ``Stack``s
|
||||
run. Prime always stores split w1/w2/w3, so the backward path always goes
|
||||
through the per-expert ``Stack`` unstack (the fused key is absent in prime,
|
||||
so the conditional takes the else branch)."""
|
||||
stacks = [
|
||||
Stack(
|
||||
stacked=f"{prefix}.{prime_experts}.{wn}",
|
||||
item=f"{prefix}.{hf_experts}.{{e}}.{hf_proj}{hf_proj_suffix}",
|
||||
)
|
||||
for wn, hf_proj in proj_order
|
||||
]
|
||||
if not fused:
|
||||
return Sequence(stacks)
|
||||
gate_up = f"{prefix}.{hf_experts}.gate_up_proj"
|
||||
fused_then = [
|
||||
SplitConcat(
|
||||
combined=gate_up,
|
||||
parts=[(f"{prefix}.{prime_experts}.w1", None), (f"{prefix}.{prime_experts}.w3", None)],
|
||||
dim=1,
|
||||
),
|
||||
Rename(f"{prefix}.{hf_experts}.down_proj", f"{prefix}.{prime_experts}.w2"),
|
||||
]
|
||||
return Conditional(key_present(gate_up), then=fused_then, else_=stacks)
|
||||
@@ -1,148 +1,67 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
"""HF<->prime weight conversion for GLM-4 MoE, as a declarative op chain.
|
||||
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
GLM-4 MoE specifics:
|
||||
|
||||
* Router: HF ``mlp.gate.weight`` -> prime ``mlp.router.gate.weight``.
|
||||
* Expert bias: HF ``mlp.gate.e_score_correction_bias`` -> prime
|
||||
``mlp.expert_bias``.
|
||||
* Routed experts: HF per-expert ``mlp.experts.{e}.{gate,down,up}_proj.weight``
|
||||
stack into prime ``mlp.experts.{w1,w2,w3}`` along dim 0; the fused
|
||||
transformers-v5 ``mlp.experts.gate_up_proj`` / ``down_proj`` layout is also
|
||||
accepted on the way in (split along dim 1).
|
||||
* Shared experts: HF ``mlp.shared_experts.{gate,down,up}_proj.weight`` map to
|
||||
prime ``mlp.shared_expert.{w1,w2,w3}`` (no ``.weight`` suffix on prime; this
|
||||
is a plain rename forward). On the way back to HF, GLM strips a leading
|
||||
singleton dim from each shared-expert tensor when present
|
||||
(:class:`~prime_rl.trainer.models.conversion_ops.SqueezeLeading`,
|
||||
backward-only).
|
||||
* Prime-only runtime buffer ``mlp.tokens_per_expert`` is dropped on the way
|
||||
back to HF.
|
||||
|
||||
The per-layer MoE op builder (:func:`glm_moe_layer_ops`) is shared verbatim
|
||||
with GLM-MoE-DSA, whose attention/MLA weights pass through untouched.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import (
|
||||
GATE_DOWN_UP,
|
||||
ConvOp,
|
||||
Drop,
|
||||
Rename,
|
||||
SqueezeLeading,
|
||||
routed_experts_op,
|
||||
)
|
||||
|
||||
|
||||
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
|
||||
i = layer_idx
|
||||
def glm_moe_layer_ops(layer_idx: int) -> list[ConvOp]:
|
||||
"""The HF <-> PrimeRL MoE ops for one GLM-style layer.
|
||||
|
||||
# Check if this is a MoE layer by looking for gate weight
|
||||
if f"model.layers.{i}.mlp.gate.weight" not in state_dict:
|
||||
return
|
||||
|
||||
state_dict[f"model.layers.{i}.mlp.router.gate.weight"] = state_dict[f"model.layers.{i}.mlp.gate.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.gate.weight"]
|
||||
|
||||
# Check if this is the new fused format (transformers 5.0+) or old per-expert format
|
||||
if f"model.layers.{i}.mlp.experts.gate_up_proj" in state_dict:
|
||||
# New fused format: gate_up_proj has shape (num_experts, 2*moe_dim, dim)
|
||||
gate_up_proj = state_dict[f"model.layers.{i}.mlp.experts.gate_up_proj"]
|
||||
down_proj = state_dict[f"model.layers.{i}.mlp.experts.down_proj"]
|
||||
|
||||
num_experts, fused_dim, dim = gate_up_proj.shape
|
||||
moe_dim = fused_dim // 2
|
||||
|
||||
# Split gate_up_proj into w1 (gate) and w3 (up)
|
||||
w1 = gate_up_proj[:, :moe_dim, :] # Gate: (num_experts, moe_dim, dim)
|
||||
w3 = gate_up_proj[:, moe_dim:, :] # Up: (num_experts, moe_dim, dim)
|
||||
w2 = down_proj # Down: (num_experts, dim, moe_dim)
|
||||
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.gate_up_proj"]
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.down_proj"]
|
||||
else:
|
||||
# Old per-expert format
|
||||
num_experts = len([j for j in state_dict.keys() if f"model.layers.{i}.mlp.experts" in j]) // 3
|
||||
if num_experts == 0:
|
||||
return
|
||||
|
||||
dim, moe_dim = state_dict[f"model.layers.{i}.mlp.experts.0.down_proj.weight"].shape
|
||||
w1 = torch.empty(
|
||||
(num_experts, moe_dim, dim), dtype=state_dict[f"model.layers.{i}.mlp.experts.1.down_proj.weight"].dtype
|
||||
) # Gate
|
||||
w2 = torch.empty(
|
||||
(num_experts, dim, moe_dim), dtype=state_dict[f"model.layers.{i}.mlp.experts.1.down_proj.weight"].dtype
|
||||
) # Down
|
||||
w3 = torch.empty(
|
||||
(num_experts, moe_dim, dim), dtype=state_dict[f"model.layers.{i}.mlp.experts.1.down_proj.weight"].dtype
|
||||
) # Up
|
||||
for j in range(num_experts):
|
||||
w1[j].copy_(state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"])
|
||||
w2[j].copy_(state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"])
|
||||
w3[j].copy_(state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"])
|
||||
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"]
|
||||
|
||||
state_dict[f"model.layers.{i}.mlp.experts.w1"] = w1
|
||||
state_dict[f"model.layers.{i}.mlp.experts.w2"] = w2
|
||||
state_dict[f"model.layers.{i}.mlp.experts.w3"] = w3
|
||||
|
||||
state_dict[f"model.layers.{i}.mlp.shared_expert.w1"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_experts.gate_proj.weight"
|
||||
Shared by GLM-4 MoE and GLM-MoE-DSA (their HF <-> PrimeRL MoE conversion is
|
||||
identical; DSA's attention/MLA weights pass through untouched)."""
|
||||
p = f"model.layers.{layer_idx}.mlp"
|
||||
ops: list[ConvOp] = [
|
||||
Rename(f"{p}.gate.weight", f"{p}.router.gate.weight"),
|
||||
Rename(f"{p}.gate.e_score_correction_bias", f"{p}.expert_bias"),
|
||||
routed_experts_op(
|
||||
f"model.layers.{layer_idx}",
|
||||
hf_experts="mlp.experts",
|
||||
prime_experts="mlp.experts",
|
||||
fused=True,
|
||||
),
|
||||
]
|
||||
state_dict[f"model.layers.{i}.mlp.shared_expert.w2"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_experts.down_proj.weight"
|
||||
]
|
||||
state_dict[f"model.layers.{i}.mlp.shared_expert.w3"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_experts.up_proj.weight"
|
||||
]
|
||||
|
||||
del state_dict[f"model.layers.{i}.mlp.shared_experts.gate_proj.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.shared_experts.down_proj.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.shared_experts.up_proj.weight"]
|
||||
|
||||
state_dict[f"model.layers.{i}.mlp.expert_bias"] = state_dict[f"model.layers.{i}.mlp.gate.e_score_correction_bias"]
|
||||
del state_dict[f"model.layers.{i}.mlp.gate.e_score_correction_bias"]
|
||||
for wn, hf_proj in GATE_DOWN_UP:
|
||||
# SqueezeLeading is backward-only and must run *after* the rename has
|
||||
# restored the HF key, so it precedes the Rename in the forward list
|
||||
# (apply_prime_to_hf plays the chain in reverse).
|
||||
ops.append(SqueezeLeading(f"{p}.shared_experts.{hf_proj}.weight"))
|
||||
ops.append(Rename(f"{p}.shared_experts.{hf_proj}.weight", f"{p}.shared_expert.{wn}"))
|
||||
ops.append(Drop(f"{p}.tokens_per_expert"))
|
||||
return ops
|
||||
|
||||
|
||||
def convert_hf_to_tt_moe(state_dict: dict[str, Tensor]):
|
||||
"""Convert MoE weights from HF to TT format in-place."""
|
||||
num_layers = get_max_layer_num(state_dict)
|
||||
for i in range(num_layers):
|
||||
convert_hf_layer_to_tt(state_dict, i)
|
||||
|
||||
|
||||
def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_index: int):
|
||||
"""Convert a layer from TT to HF format in-place."""
|
||||
|
||||
i = layer_index
|
||||
|
||||
# Load balancing terms
|
||||
if f"model.layers.{i}.mlp.expert_bias" in state_dict:
|
||||
state_dict[f"model.layers.{i}.mlp.gate.e_score_correction_bias"] = state_dict[
|
||||
f"model.layers.{i}.mlp.expert_bias"
|
||||
]
|
||||
del state_dict[f"model.layers.{i}.mlp.expert_bias"]
|
||||
if f"model.layers.{i}.mlp.tokens_per_expert" in state_dict:
|
||||
del state_dict[f"model.layers.{i}.mlp.tokens_per_expert"]
|
||||
|
||||
# Shared experts
|
||||
if f"model.layers.{i}.mlp.shared_expert.w1" in state_dict:
|
||||
state_dict[f"model.layers.{i}.mlp.shared_experts.gate_proj.weight"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_expert.w1"
|
||||
]
|
||||
state_dict[f"model.layers.{i}.mlp.shared_experts.down_proj.weight"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_expert.w2"
|
||||
]
|
||||
state_dict[f"model.layers.{i}.mlp.shared_experts.up_proj.weight"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_expert.w3"
|
||||
]
|
||||
|
||||
if state_dict[f"model.layers.{i}.mlp.shared_experts.up_proj.weight"].shape[0] == 1:
|
||||
state_dict[f"model.layers.{i}.mlp.shared_experts.up_proj.weight"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_experts.up_proj.weight"
|
||||
][0]
|
||||
state_dict[f"model.layers.{i}.mlp.shared_experts.down_proj.weight"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_experts.down_proj.weight"
|
||||
][0]
|
||||
state_dict[f"model.layers.{i}.mlp.shared_experts.gate_proj.weight"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_experts.gate_proj.weight"
|
||||
][0]
|
||||
del state_dict[f"model.layers.{i}.mlp.shared_expert.w1"]
|
||||
del state_dict[f"model.layers.{i}.mlp.shared_expert.w2"]
|
||||
del state_dict[f"model.layers.{i}.mlp.shared_expert.w3"]
|
||||
|
||||
# Gate / Router
|
||||
if f"model.layers.{i}.mlp.router.gate.weight" in state_dict:
|
||||
state_dict[f"model.layers.{i}.mlp.gate.weight"] = state_dict[f"model.layers.{i}.mlp.router.gate.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.router.gate.weight"]
|
||||
|
||||
# Routed experts - convert to per-expert format (compatible with vLLM and transformers)
|
||||
w1 = state_dict.pop(f"model.layers.{i}.mlp.experts.w1") # (num_experts, moe_dim, dim)
|
||||
w2 = state_dict.pop(f"model.layers.{i}.mlp.experts.w2") # (num_experts, dim, moe_dim)
|
||||
w3 = state_dict.pop(f"model.layers.{i}.mlp.experts.w3") # (num_experts, moe_dim, dim)
|
||||
|
||||
num_experts = w1.shape[0]
|
||||
for j in range(num_experts):
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"] = w1[j]
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"] = w2[j]
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"] = w3[j]
|
||||
|
||||
|
||||
def convert_tt_to_hf_moe(state_dict: dict[str, Tensor]):
|
||||
"""Convert MoE weights from TT to HF format in-place."""
|
||||
num_layers = get_max_layer_num(state_dict)
|
||||
for i in range(num_layers):
|
||||
convert_tt_layer_to_hf(state_dict, i)
|
||||
def conversion_chain(config) -> list[ConvOp]:
|
||||
ops: list[ConvOp] = []
|
||||
for i in range(config.num_hidden_layers):
|
||||
ops.extend(glm_moe_layer_ops(i))
|
||||
return ops
|
||||
|
||||
@@ -27,12 +27,7 @@ from transformers.utils.deprecation import deprecate_kwarg
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.glm4_moe.configuration_glm4_moe import Glm4MoeConfig
|
||||
from prime_rl.trainer.models.glm4_moe.converting_glm4_moe import (
|
||||
convert_hf_layer_to_tt,
|
||||
convert_hf_to_tt_moe,
|
||||
convert_tt_layer_to_hf,
|
||||
convert_tt_to_hf_moe,
|
||||
)
|
||||
from prime_rl.trainer.models.glm4_moe.converting_glm4_moe import conversion_chain
|
||||
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
@@ -129,6 +124,10 @@ class Glm4MoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
"hidden_states": Glm4MoeDecoderLayer,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
|
||||
return name.endswith("mlp.expert_bias")
|
||||
|
||||
def _init_weights(self, module):
|
||||
super()._init_weights(module)
|
||||
|
||||
@@ -144,28 +143,8 @@ class Glm4MoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
return any("mlp.experts.w1" in module_name for module_name in state_dict.keys())
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
"""Convert MoE weights from PrimeRL training format to HuggingFace format in-place."""
|
||||
convert_tt_to_hf_moe(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
"""Convert MoE weights from HuggingFace format to PrimeRL training format in-place."""
|
||||
convert_hf_to_tt_moe(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
"""Convert a single layer's MoE weights from PrimeRL format to HuggingFace format in-place."""
|
||||
convert_tt_layer_to_hf(state_dict, layer_idx)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
"""Convert a single layer's MoE weights from HuggingFace format to PrimeRL format in-place."""
|
||||
convert_hf_layer_to_tt(state_dict, layer_idx)
|
||||
return state_dict
|
||||
def conversion_chain(cls, config):
|
||||
return conversion_chain(config)
|
||||
|
||||
|
||||
@auto_docstring
|
||||
|
||||
@@ -1,146 +1,24 @@
|
||||
"""HF<->PrimeRL weight conversion for GLM-MoE-DSA.
|
||||
|
||||
The MoE layout is identical to GLM4-MoE. Attention and sparse-indexer
|
||||
parameters retain their names in both formats.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
from prime_rl.trainer.models.conversion_ops import ConvOp
|
||||
from prime_rl.trainer.models.fp8 import quantize_to_vllm_kernel_format
|
||||
from prime_rl.trainer.models.glm4_moe.converting_glm4_moe import glm_moe_layer_ops
|
||||
|
||||
|
||||
def _is_moe_layer(state_dict: dict[str, Tensor], layer_idx: int) -> bool:
|
||||
"""Check if a layer is an MoE layer by looking for the router gate weight."""
|
||||
return f"model.layers.{layer_idx}.mlp.gate.weight" in state_dict
|
||||
|
||||
|
||||
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
|
||||
i = layer_idx
|
||||
|
||||
if not _is_moe_layer(state_dict, i):
|
||||
return
|
||||
|
||||
# Router: gate.weight -> router.gate.weight
|
||||
state_dict[f"model.layers.{i}.mlp.router.gate.weight"] = state_dict[f"model.layers.{i}.mlp.gate.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.gate.weight"]
|
||||
|
||||
# Routed experts: fused or per-expert format -> stacked w1/w2/w3
|
||||
if f"model.layers.{i}.mlp.experts.gate_up_proj" in state_dict:
|
||||
gate_up_proj = state_dict[f"model.layers.{i}.mlp.experts.gate_up_proj"]
|
||||
down_proj = state_dict[f"model.layers.{i}.mlp.experts.down_proj"]
|
||||
|
||||
num_experts, fused_dim, dim = gate_up_proj.shape
|
||||
moe_dim = fused_dim // 2
|
||||
|
||||
w1 = gate_up_proj[:, :moe_dim, :]
|
||||
w3 = gate_up_proj[:, moe_dim:, :]
|
||||
w2 = down_proj
|
||||
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.gate_up_proj"]
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.down_proj"]
|
||||
else:
|
||||
num_experts = len([j for j in state_dict.keys() if f"model.layers.{i}.mlp.experts" in j]) // 3
|
||||
if num_experts == 0:
|
||||
return
|
||||
|
||||
dim, moe_dim = state_dict[f"model.layers.{i}.mlp.experts.0.down_proj.weight"].shape
|
||||
dtype = state_dict[f"model.layers.{i}.mlp.experts.0.down_proj.weight"].dtype
|
||||
w1 = torch.empty((num_experts, moe_dim, dim), dtype=dtype)
|
||||
w2 = torch.empty((num_experts, dim, moe_dim), dtype=dtype)
|
||||
w3 = torch.empty((num_experts, moe_dim, dim), dtype=dtype)
|
||||
for j in range(num_experts):
|
||||
w1[j].copy_(state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"])
|
||||
w2[j].copy_(state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"])
|
||||
w3[j].copy_(state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"])
|
||||
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"]
|
||||
|
||||
state_dict[f"model.layers.{i}.mlp.experts.w1"] = w1
|
||||
state_dict[f"model.layers.{i}.mlp.experts.w2"] = w2
|
||||
state_dict[f"model.layers.{i}.mlp.experts.w3"] = w3
|
||||
|
||||
# Shared experts
|
||||
state_dict[f"model.layers.{i}.mlp.shared_expert.w1"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_experts.gate_proj.weight"
|
||||
]
|
||||
state_dict[f"model.layers.{i}.mlp.shared_expert.w2"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_experts.down_proj.weight"
|
||||
]
|
||||
state_dict[f"model.layers.{i}.mlp.shared_expert.w3"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_experts.up_proj.weight"
|
||||
]
|
||||
del state_dict[f"model.layers.{i}.mlp.shared_experts.gate_proj.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.shared_experts.down_proj.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.shared_experts.up_proj.weight"]
|
||||
|
||||
# Expert bias for load balancing
|
||||
state_dict[f"model.layers.{i}.mlp.expert_bias"] = state_dict[f"model.layers.{i}.mlp.gate.e_score_correction_bias"]
|
||||
del state_dict[f"model.layers.{i}.mlp.gate.e_score_correction_bias"]
|
||||
|
||||
|
||||
def convert_hf_to_tt_moe(state_dict: dict[str, Tensor]):
|
||||
num_layers = get_max_layer_num(state_dict)
|
||||
for i in range(num_layers):
|
||||
convert_hf_layer_to_tt(state_dict, i)
|
||||
|
||||
|
||||
def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_index: int):
|
||||
i = layer_index
|
||||
|
||||
# Expert bias
|
||||
if f"model.layers.{i}.mlp.expert_bias" in state_dict:
|
||||
state_dict[f"model.layers.{i}.mlp.gate.e_score_correction_bias"] = state_dict[
|
||||
f"model.layers.{i}.mlp.expert_bias"
|
||||
]
|
||||
del state_dict[f"model.layers.{i}.mlp.expert_bias"]
|
||||
if f"model.layers.{i}.mlp.tokens_per_expert" in state_dict:
|
||||
del state_dict[f"model.layers.{i}.mlp.tokens_per_expert"]
|
||||
|
||||
# Shared experts
|
||||
if f"model.layers.{i}.mlp.shared_expert.w1" in state_dict:
|
||||
state_dict[f"model.layers.{i}.mlp.shared_experts.gate_proj.weight"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_expert.w1"
|
||||
]
|
||||
state_dict[f"model.layers.{i}.mlp.shared_experts.down_proj.weight"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_expert.w2"
|
||||
]
|
||||
state_dict[f"model.layers.{i}.mlp.shared_experts.up_proj.weight"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_expert.w3"
|
||||
]
|
||||
|
||||
if state_dict[f"model.layers.{i}.mlp.shared_experts.up_proj.weight"].shape[0] == 1:
|
||||
state_dict[f"model.layers.{i}.mlp.shared_experts.up_proj.weight"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_experts.up_proj.weight"
|
||||
][0]
|
||||
state_dict[f"model.layers.{i}.mlp.shared_experts.down_proj.weight"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_experts.down_proj.weight"
|
||||
][0]
|
||||
state_dict[f"model.layers.{i}.mlp.shared_experts.gate_proj.weight"] = state_dict[
|
||||
f"model.layers.{i}.mlp.shared_experts.gate_proj.weight"
|
||||
][0]
|
||||
del state_dict[f"model.layers.{i}.mlp.shared_expert.w1"]
|
||||
del state_dict[f"model.layers.{i}.mlp.shared_expert.w2"]
|
||||
del state_dict[f"model.layers.{i}.mlp.shared_expert.w3"]
|
||||
|
||||
# Router
|
||||
if f"model.layers.{i}.mlp.router.gate.weight" in state_dict:
|
||||
state_dict[f"model.layers.{i}.mlp.gate.weight"] = state_dict[f"model.layers.{i}.mlp.router.gate.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.router.gate.weight"]
|
||||
|
||||
# Routed experts - convert to per-expert format (compatible with vLLM and transformers)
|
||||
w1 = state_dict.pop(f"model.layers.{i}.mlp.experts.w1") # (num_experts, moe_dim, dim)
|
||||
w2 = state_dict.pop(f"model.layers.{i}.mlp.experts.w2") # (num_experts, dim, moe_dim)
|
||||
w3 = state_dict.pop(f"model.layers.{i}.mlp.experts.w3") # (num_experts, moe_dim, dim)
|
||||
|
||||
num_experts = w1.shape[0]
|
||||
for j in range(num_experts):
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"] = w1[j]
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"] = w2[j]
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"] = w3[j]
|
||||
|
||||
|
||||
def convert_tt_to_hf_moe(state_dict: dict[str, Tensor]):
|
||||
num_layers = get_max_layer_num(state_dict)
|
||||
for i in range(num_layers):
|
||||
convert_tt_layer_to_hf(state_dict, i)
|
||||
def conversion_chain(config) -> list[ConvOp]:
|
||||
ops: list[ConvOp] = []
|
||||
for layer_idx in range(config.num_hidden_layers):
|
||||
ops.extend(glm_moe_layer_ops(layer_idx))
|
||||
return ops
|
||||
|
||||
|
||||
def convert_tt_layer_to_vllm_kernel(
|
||||
|
||||
@@ -15,11 +15,8 @@ from transformers.utils.deprecation import deprecate_kwarg
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.glm_moe_dsa.configuration_glm_moe_dsa import GlmMoeDsaConfig, _index_cache_skip_topk
|
||||
from prime_rl.trainer.models.glm_moe_dsa.converting_glm_moe_dsa import (
|
||||
convert_hf_layer_to_tt,
|
||||
convert_hf_to_tt_moe,
|
||||
convert_tt_layer_to_hf,
|
||||
conversion_chain,
|
||||
convert_tt_layer_to_vllm_kernel,
|
||||
convert_tt_to_hf_moe,
|
||||
)
|
||||
from prime_rl.trainer.models.glm_moe_dsa.sparse_mla_attention import GlmMoeDsaAttention, SparseMlaAttentionArgs
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
@@ -137,6 +134,10 @@ class GlmMoeDsaPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
def _init_weights(self, module):
|
||||
super()._init_weights(module)
|
||||
|
||||
@classmethod
|
||||
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
|
||||
return name.endswith("mlp.expert_bias")
|
||||
|
||||
@classmethod
|
||||
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("mlp.experts.1.up_proj" in name or "mlp.experts.gate_up_proj" in name for name in state_dict.keys())
|
||||
@@ -146,24 +147,8 @@ class GlmMoeDsaPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
return any("mlp.experts.w1" in module_name for module_name in state_dict.keys())
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
convert_tt_to_hf_moe(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
convert_hf_to_tt_moe(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
convert_tt_layer_to_hf(state_dict, layer_idx)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
convert_hf_layer_to_tt(state_dict, layer_idx)
|
||||
return state_dict
|
||||
def conversion_chain(cls, config):
|
||||
return conversion_chain(config)
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_vllm_kernel(
|
||||
|
||||
@@ -8,6 +8,8 @@ no key conversion - HF and prime formats are identical for this model.
|
||||
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import ConvOp
|
||||
|
||||
|
||||
def is_hf_state_dict(state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("mlp.experts.gate_up_proj" in name for name in state_dict.keys())
|
||||
@@ -20,9 +22,6 @@ def is_prime_state_dict(state_dict: dict[str, Tensor]) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def convert_to_hf(state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
return state_dict
|
||||
|
||||
|
||||
def convert_to_prime(state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
return state_dict
|
||||
def conversion_chain(config) -> list[ConvOp]:
|
||||
# HF and prime layouts coincide for GPT-OSS, so the conversion is the identity.
|
||||
return []
|
||||
|
||||
@@ -26,8 +26,7 @@ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tu
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.gpt_oss.configuration_gpt_oss import GptOssConfig
|
||||
from prime_rl.trainer.models.gpt_oss.converting_gpt_oss import (
|
||||
convert_to_hf,
|
||||
convert_to_prime,
|
||||
conversion_chain,
|
||||
is_hf_state_dict,
|
||||
is_prime_state_dict,
|
||||
)
|
||||
@@ -193,12 +192,8 @@ class GptOssPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
return is_prime_state_dict(state_dict)
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
return convert_to_hf(state_dict)
|
||||
|
||||
@classmethod
|
||||
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
return convert_to_prime(state_dict)
|
||||
def conversion_chain(cls, config):
|
||||
return conversion_chain(config)
|
||||
|
||||
|
||||
@auto_docstring
|
||||
|
||||
@@ -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
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -1,118 +1,77 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
"""HF<->prime weight conversion for Laguna, as a declarative op chain.
|
||||
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
Laguna specifics:
|
||||
|
||||
* Router: HF ``mlp.gate.weight`` maps to prime ``mlp.router.gate.weight``.
|
||||
* Expert bias: the HF input is *either* ``mlp.experts.e_score_correction_bias``
|
||||
*or* ``mlp.gate.e_score_correction_bias`` (the former wins when both are
|
||||
present); it maps to prime ``mlp.expert_bias``. Backward always emits the
|
||||
canonical ``mlp.experts.e_score_correction_bias``.
|
||||
* Routed experts: HF per-expert ``mlp.experts.{e}.{gate,down,up}_proj.weight``
|
||||
*or* the fused ``mlp.experts.gate_up_proj`` / ``down_proj`` layout stack into
|
||||
prime ``mlp.experts.{w1,w2,w3}`` (w1=gate, w2=down, w3=up).
|
||||
* Shared expert: the HF input is *either* ``mlp.shared_expert.*`` *or*
|
||||
``mlp.shared_experts.*`` (singular wins); it maps to prime
|
||||
``shared_expert.{w1,w2,w3}.weight`` (no ``mlp.`` prefix, keeps ``.weight``).
|
||||
Backward always emits the singular ``mlp.shared_expert.*``.
|
||||
* Prime-only ``mlp.tokens_per_expert`` is dropped on the way back to HF.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import (
|
||||
GATE_DOWN_UP,
|
||||
Conditional,
|
||||
ConvOp,
|
||||
Drop,
|
||||
Rename,
|
||||
routed_experts_op,
|
||||
)
|
||||
|
||||
|
||||
def _pop_first(state_dict: dict[str, Tensor], keys: tuple[str, ...]) -> Tensor | None:
|
||||
for key in keys:
|
||||
if key in state_dict:
|
||||
return state_dict.pop(key)
|
||||
return None
|
||||
def conversion_chain(config) -> list[ConvOp]:
|
||||
ops: list[ConvOp] = []
|
||||
for i in range(config.num_hidden_layers):
|
||||
p = f"model.layers.{i}"
|
||||
|
||||
# Router gate.
|
||||
ops.append(Rename(f"{p}.mlp.gate.weight", f"{p}.mlp.router.gate.weight"))
|
||||
|
||||
def convert_hf_layer_to_prime(state_dict: dict[str, Tensor], layer_idx: int) -> None:
|
||||
prefix = f"model.layers.{layer_idx}"
|
||||
gate_key = f"{prefix}.mlp.gate.weight"
|
||||
if gate_key not in state_dict:
|
||||
return
|
||||
|
||||
state_dict[f"{prefix}.mlp.router.gate.weight"] = state_dict.pop(gate_key)
|
||||
|
||||
expert_bias = _pop_first(
|
||||
state_dict,
|
||||
(
|
||||
f"{prefix}.mlp.experts.e_score_correction_bias",
|
||||
f"{prefix}.mlp.gate.e_score_correction_bias",
|
||||
),
|
||||
)
|
||||
if expert_bias is not None:
|
||||
state_dict[f"{prefix}.mlp.expert_bias"] = expert_bias
|
||||
|
||||
fused_key = f"{prefix}.mlp.experts.gate_up_proj"
|
||||
if fused_key in state_dict:
|
||||
gate_up_proj = state_dict.pop(fused_key)
|
||||
down_proj = state_dict.pop(f"{prefix}.mlp.experts.down_proj")
|
||||
moe_dim = gate_up_proj.shape[1] // 2
|
||||
w1 = gate_up_proj[:, :moe_dim, :]
|
||||
w3 = gate_up_proj[:, moe_dim:, :]
|
||||
w2 = down_proj
|
||||
else:
|
||||
expert_ids = sorted(
|
||||
int(key[len(f"{prefix}.mlp.experts.") :].split(".")[0])
|
||||
for key in state_dict
|
||||
if key.startswith(f"{prefix}.mlp.experts.") and key.endswith(".gate_proj.weight")
|
||||
# Expert bias. The base Rename handles the canonical `experts.` input and
|
||||
# the (always-singular) backward; the conditional adds the forward-only
|
||||
# `gate.` alternate, firing only when the canonical input is absent so it
|
||||
# matches the imperative's "experts wins" preference.
|
||||
ops.append(Rename(f"{p}.mlp.experts.e_score_correction_bias", f"{p}.mlp.expert_bias"))
|
||||
ops.append(
|
||||
Conditional(
|
||||
predicate=lambda sd, p=p: (
|
||||
f"{p}.mlp.gate.e_score_correction_bias" in sd
|
||||
and f"{p}.mlp.experts.e_score_correction_bias" not in sd
|
||||
),
|
||||
then=[Rename(f"{p}.mlp.gate.e_score_correction_bias", f"{p}.mlp.expert_bias")],
|
||||
)
|
||||
)
|
||||
if not expert_ids:
|
||||
return
|
||||
|
||||
first_down = state_dict[f"{prefix}.mlp.experts.{expert_ids[0]}.down_proj.weight"]
|
||||
dim, moe_dim = first_down.shape
|
||||
w1 = torch.empty((len(expert_ids), moe_dim, dim), dtype=first_down.dtype, device=first_down.device)
|
||||
w2 = torch.empty((len(expert_ids), dim, moe_dim), dtype=first_down.dtype, device=first_down.device)
|
||||
w3 = torch.empty((len(expert_ids), moe_dim, dim), dtype=first_down.dtype, device=first_down.device)
|
||||
for out_idx, expert_idx in enumerate(expert_ids):
|
||||
w1[out_idx].copy_(state_dict.pop(f"{prefix}.mlp.experts.{expert_idx}.gate_proj.weight"))
|
||||
w2[out_idx].copy_(state_dict.pop(f"{prefix}.mlp.experts.{expert_idx}.down_proj.weight"))
|
||||
w3[out_idx].copy_(state_dict.pop(f"{prefix}.mlp.experts.{expert_idx}.up_proj.weight"))
|
||||
# Routed experts (per-expert or fused gate_up).
|
||||
ops.append(routed_experts_op(p, hf_experts="mlp.experts", prime_experts="mlp.experts", fused=True))
|
||||
|
||||
state_dict[f"{prefix}.mlp.experts.w1"] = w1
|
||||
state_dict[f"{prefix}.mlp.experts.w2"] = w2
|
||||
state_dict[f"{prefix}.mlp.experts.w3"] = w3
|
||||
# Shared expert. Base Renames handle the singular input + singular
|
||||
# backward; the conditional adds the forward-only plural alternate.
|
||||
for wn, hf_proj in GATE_DOWN_UP:
|
||||
ops.append(Rename(f"{p}.mlp.shared_expert.{hf_proj}.weight", f"{p}.shared_expert.{wn}.weight"))
|
||||
ops.append(
|
||||
Conditional(
|
||||
predicate=lambda sd, p=p: (
|
||||
f"{p}.mlp.shared_experts.gate_proj.weight" in sd
|
||||
and f"{p}.mlp.shared_expert.gate_proj.weight" not in sd
|
||||
),
|
||||
then=[
|
||||
Rename(f"{p}.mlp.shared_experts.{hf_proj}.weight", f"{p}.shared_expert.{wn}.weight")
|
||||
for wn, hf_proj in GATE_DOWN_UP
|
||||
],
|
||||
)
|
||||
)
|
||||
|
||||
shared_prefix = None
|
||||
for candidate in (f"{prefix}.mlp.shared_expert", f"{prefix}.mlp.shared_experts"):
|
||||
if f"{candidate}.gate_proj.weight" in state_dict:
|
||||
shared_prefix = candidate
|
||||
break
|
||||
|
||||
if shared_prefix is not None:
|
||||
state_dict[f"{prefix}.shared_expert.w1.weight"] = state_dict.pop(f"{shared_prefix}.gate_proj.weight")
|
||||
state_dict[f"{prefix}.shared_expert.w2.weight"] = state_dict.pop(f"{shared_prefix}.down_proj.weight")
|
||||
state_dict[f"{prefix}.shared_expert.w3.weight"] = state_dict.pop(f"{shared_prefix}.up_proj.weight")
|
||||
|
||||
|
||||
def convert_prime_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int) -> None:
|
||||
prefix = f"model.layers.{layer_idx}"
|
||||
router_key = f"{prefix}.mlp.router.gate.weight"
|
||||
if router_key not in state_dict:
|
||||
return
|
||||
|
||||
if f"{prefix}.mlp.tokens_per_expert" in state_dict:
|
||||
del state_dict[f"{prefix}.mlp.tokens_per_expert"]
|
||||
if f"{prefix}.mlp.expert_bias" in state_dict:
|
||||
state_dict[f"{prefix}.mlp.experts.e_score_correction_bias"] = state_dict.pop(f"{prefix}.mlp.expert_bias")
|
||||
|
||||
state_dict[f"{prefix}.mlp.gate.weight"] = state_dict.pop(router_key)
|
||||
|
||||
w1 = state_dict.pop(f"{prefix}.mlp.experts.w1")
|
||||
w2 = state_dict.pop(f"{prefix}.mlp.experts.w2")
|
||||
w3 = state_dict.pop(f"{prefix}.mlp.experts.w3")
|
||||
for expert_idx in range(w1.shape[0]):
|
||||
state_dict[f"{prefix}.mlp.experts.{expert_idx}.gate_proj.weight"] = w1[expert_idx]
|
||||
state_dict[f"{prefix}.mlp.experts.{expert_idx}.down_proj.weight"] = w2[expert_idx]
|
||||
state_dict[f"{prefix}.mlp.experts.{expert_idx}.up_proj.weight"] = w3[expert_idx]
|
||||
|
||||
shared_key = f"{prefix}.shared_expert.w1.weight"
|
||||
if shared_key in state_dict:
|
||||
state_dict[f"{prefix}.mlp.shared_expert.gate_proj.weight"] = state_dict.pop(shared_key)
|
||||
state_dict[f"{prefix}.mlp.shared_expert.down_proj.weight"] = state_dict.pop(f"{prefix}.shared_expert.w2.weight")
|
||||
state_dict[f"{prefix}.mlp.shared_expert.up_proj.weight"] = state_dict.pop(f"{prefix}.shared_expert.w3.weight")
|
||||
|
||||
|
||||
def convert_hf_to_prime(state_dict: dict[str, Tensor]) -> None:
|
||||
for layer_idx in range(get_max_layer_num(state_dict)):
|
||||
convert_hf_layer_to_prime(state_dict, layer_idx)
|
||||
|
||||
|
||||
def convert_prime_to_hf(state_dict: dict[str, Tensor]) -> None:
|
||||
for layer_idx in range(get_max_layer_num(state_dict)):
|
||||
convert_prime_layer_to_hf(state_dict, layer_idx)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"convert_hf_layer_to_prime",
|
||||
"convert_hf_to_prime",
|
||||
"convert_prime_layer_to_hf",
|
||||
"convert_prime_to_hf",
|
||||
]
|
||||
# Prime-only runtime buffer.
|
||||
ops.append(Drop(f"{p}.mlp.tokens_per_expert"))
|
||||
return ops
|
||||
|
||||
@@ -15,12 +15,7 @@ from transformers.utils.generic import maybe_autocast
|
||||
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.laguna.configuration_laguna import LagunaConfig
|
||||
from prime_rl.trainer.models.laguna.converting_laguna import (
|
||||
convert_hf_layer_to_prime,
|
||||
convert_hf_to_prime,
|
||||
convert_prime_layer_to_hf,
|
||||
convert_prime_to_hf,
|
||||
)
|
||||
from prime_rl.trainer.models.laguna.converting_laguna import conversion_chain
|
||||
from prime_rl.trainer.models.layers.attn import AttentionConfig, FlashAttention
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
@@ -251,24 +246,8 @@ class LagunaPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
return any("mlp.experts.w1" in name for name in state_dict)
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
convert_prime_to_hf(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
convert_hf_to_prime(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
convert_prime_layer_to_hf(state_dict, layer_idx)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
convert_hf_layer_to_prime(state_dict, layer_idx)
|
||||
return state_dict
|
||||
def conversion_chain(cls, config):
|
||||
return conversion_chain(config)
|
||||
|
||||
|
||||
class LagunaModel(LagunaPreTrainedModel):
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1,98 +1,33 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
"""HF<->prime weight conversion for MiniMax M2, as a declarative op chain.
|
||||
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
Per layer: router ``block_sparse_moe.gate.weight`` <-> ``mlp.router.gate.weight``,
|
||||
the ``e_score_correction_bias`` <-> ``mlp.expert_bias``, and the routed experts
|
||||
(per-expert w1/w2/w3 ``nn.Linear`` <-> stacked w1/w2/w3). The prime-only runtime
|
||||
buffer ``mlp.tokens_per_expert`` is dropped on the way to HF.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import ConvOp, Drop, Rename, routed_experts_op
|
||||
|
||||
# HF stores per-expert projections under the literal names w1/w2/w3 (nn.Linear,
|
||||
# so each carries a `.weight` suffix); prime stacks them as w1/w2/w3.
|
||||
_MINIMAX_PROJ_ORDER = (("w1", "w1"), ("w2", "w2"), ("w3", "w3"))
|
||||
|
||||
|
||||
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
|
||||
"""Convert a layer from HF to PrimeRL format in-place.
|
||||
|
||||
HF MiniMax M2.1 uses `block_sparse_moe` as the MoE block name, with
|
||||
expert weights stored as `experts.{j}.w1.weight` (nn.Linear format).
|
||||
"""
|
||||
i = layer_idx
|
||||
prefix = f"model.layers.{i}"
|
||||
|
||||
# Check if this layer has MoE experts
|
||||
num_experts = len([k for k in state_dict.keys() if f"{prefix}.block_sparse_moe.experts" in k]) // 3
|
||||
if num_experts == 0:
|
||||
return
|
||||
|
||||
# Router: block_sparse_moe.gate.weight -> mlp.router.gate.weight
|
||||
state_dict[f"{prefix}.mlp.router.gate.weight"] = state_dict[f"{prefix}.block_sparse_moe.gate.weight"]
|
||||
del state_dict[f"{prefix}.block_sparse_moe.gate.weight"]
|
||||
|
||||
# e_score_correction_bias: direct tensor under block_sparse_moe -> mlp.expert_bias
|
||||
bias_key = f"{prefix}.block_sparse_moe.e_score_correction_bias"
|
||||
if bias_key in state_dict:
|
||||
state_dict[f"{prefix}.mlp.expert_bias"] = state_dict[bias_key]
|
||||
del state_dict[bias_key]
|
||||
|
||||
# Expert weights: stack individual experts into grouped tensors
|
||||
# HF uses w1.weight, w2.weight, w3.weight (nn.Linear with .weight suffix)
|
||||
dim, moe_dim = state_dict[f"{prefix}.block_sparse_moe.experts.0.w2.weight"].shape
|
||||
dtype = state_dict[f"{prefix}.block_sparse_moe.experts.0.w2.weight"].dtype
|
||||
|
||||
w1 = torch.empty((num_experts, moe_dim, dim), dtype=dtype)
|
||||
w2 = torch.empty((num_experts, dim, moe_dim), dtype=dtype)
|
||||
w3 = torch.empty((num_experts, moe_dim, dim), dtype=dtype)
|
||||
|
||||
for j in range(num_experts):
|
||||
w1[j].copy_(state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w1.weight"])
|
||||
w2[j].copy_(state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w2.weight"])
|
||||
w3[j].copy_(state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w3.weight"])
|
||||
|
||||
del state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w1.weight"]
|
||||
del state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w2.weight"]
|
||||
del state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w3.weight"]
|
||||
|
||||
state_dict[f"{prefix}.mlp.experts.w1"] = w1
|
||||
state_dict[f"{prefix}.mlp.experts.w2"] = w2
|
||||
state_dict[f"{prefix}.mlp.experts.w3"] = w3
|
||||
|
||||
|
||||
def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int):
|
||||
"""Convert a layer from PrimeRL to HF format in-place."""
|
||||
i = layer_idx
|
||||
prefix = f"model.layers.{i}"
|
||||
|
||||
if f"{prefix}.mlp.router.gate.weight" not in state_dict:
|
||||
return
|
||||
|
||||
# Router: mlp.router.gate.weight -> block_sparse_moe.gate.weight
|
||||
state_dict[f"{prefix}.block_sparse_moe.gate.weight"] = state_dict[f"{prefix}.mlp.router.gate.weight"]
|
||||
del state_dict[f"{prefix}.mlp.router.gate.weight"]
|
||||
|
||||
# expert_bias -> block_sparse_moe.e_score_correction_bias
|
||||
if f"{prefix}.mlp.expert_bias" in state_dict:
|
||||
state_dict[f"{prefix}.block_sparse_moe.e_score_correction_bias"] = state_dict[f"{prefix}.mlp.expert_bias"]
|
||||
del state_dict[f"{prefix}.mlp.expert_bias"]
|
||||
|
||||
# tokens_per_expert is a runtime buffer, remove if present
|
||||
if f"{prefix}.mlp.tokens_per_expert" in state_dict:
|
||||
del state_dict[f"{prefix}.mlp.tokens_per_expert"]
|
||||
|
||||
# Expert weights: unstack grouped tensors into individual experts
|
||||
num_experts, moe_dim, dim = state_dict[f"{prefix}.mlp.experts.w1"].shape
|
||||
for j in range(num_experts):
|
||||
state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w1.weight"] = state_dict[f"{prefix}.mlp.experts.w1"][j]
|
||||
state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w2.weight"] = state_dict[f"{prefix}.mlp.experts.w2"][j]
|
||||
state_dict[f"{prefix}.block_sparse_moe.experts.{j}.w3.weight"] = state_dict[f"{prefix}.mlp.experts.w3"][j]
|
||||
|
||||
del state_dict[f"{prefix}.mlp.experts.w1"]
|
||||
del state_dict[f"{prefix}.mlp.experts.w2"]
|
||||
del state_dict[f"{prefix}.mlp.experts.w3"]
|
||||
|
||||
|
||||
def convert_hf_to_tt_moe(state_dict: dict[str, Tensor]):
|
||||
"""Convert MoE weights from HF to PrimeRL format in-place."""
|
||||
num_layers = get_max_layer_num(state_dict)
|
||||
for i in range(num_layers):
|
||||
convert_hf_layer_to_tt(state_dict, i)
|
||||
|
||||
|
||||
def convert_tt_to_hf_moe(state_dict: dict[str, Tensor]):
|
||||
"""Convert MoE weights from PrimeRL to HF format in-place."""
|
||||
num_layers = get_max_layer_num(state_dict)
|
||||
for i in range(num_layers):
|
||||
convert_tt_layer_to_hf(state_dict, i)
|
||||
def conversion_chain(config) -> list[ConvOp]:
|
||||
ops: list[ConvOp] = []
|
||||
for i in range(config.num_hidden_layers):
|
||||
p = f"model.layers.{i}"
|
||||
ops.append(Rename(f"{p}.block_sparse_moe.gate.weight", f"{p}.mlp.router.gate.weight"))
|
||||
ops.append(Rename(f"{p}.block_sparse_moe.e_score_correction_bias", f"{p}.mlp.expert_bias"))
|
||||
ops.append(
|
||||
routed_experts_op(
|
||||
p,
|
||||
hf_experts="block_sparse_moe.experts",
|
||||
prime_experts="mlp.experts",
|
||||
proj_order=_MINIMAX_PROJ_ORDER,
|
||||
)
|
||||
)
|
||||
ops.append(Drop(f"{p}.mlp.tokens_per_expert"))
|
||||
return ops
|
||||
|
||||
@@ -16,12 +16,7 @@ from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
from prime_rl.trainer.models.minimax_m2.configuration_minimax_m2 import MiniMaxM2Config
|
||||
from prime_rl.trainer.models.minimax_m2.converting_minimax_m2 import (
|
||||
convert_hf_layer_to_tt,
|
||||
convert_hf_to_tt_moe,
|
||||
convert_tt_layer_to_hf,
|
||||
convert_tt_to_hf_moe,
|
||||
)
|
||||
from prime_rl.trainer.models.minimax_m2.converting_minimax_m2 import conversion_chain
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
@@ -112,24 +107,8 @@ class MiniMaxM2PreTrainedModel(PreTrainedModelPrimeRL):
|
||||
return any("mlp.experts.w1" in name for name in state_dict.keys())
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
convert_tt_to_hf_moe(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
convert_hf_to_tt_moe(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
convert_tt_layer_to_hf(state_dict, layer_idx)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
convert_hf_layer_to_tt(state_dict, layer_idx)
|
||||
return state_dict
|
||||
def conversion_chain(cls, config):
|
||||
return conversion_chain(config)
|
||||
|
||||
|
||||
@auto_docstring
|
||||
|
||||
@@ -1,176 +1,108 @@
|
||||
"""Weight conversion between HuggingFace and PrimeRL formats for NemotronH.
|
||||
"""Declarative HF<->prime conversion chain for NemotronH.
|
||||
|
||||
HF NemotronH uses a unified `mixer` attribute for all layer types:
|
||||
- Mamba layers: backbone.layers.{i}.mixer.{in_proj, conv1d, ...}
|
||||
- Attention layers: backbone.layers.{i}.mixer.{q_proj, k_proj, v_proj, o_proj}
|
||||
- MoE layers: backbone.layers.{i}.mixer.{gate, experts, shared_experts, fc1_latent_proj, fc2_latent_proj}
|
||||
|
||||
PrimeRL separates these into distinct namespaces:
|
||||
- Mamba layers: model.layers.{i}.mamba.*
|
||||
- Attention layers: model.layers.{i}.self_attn.*
|
||||
- MoE layers: model.layers.{i}.mlp.{router, experts, shared_expert, fc1_latent_proj, fc2_latent_proj}
|
||||
|
||||
Global renames:
|
||||
- HF: backbone.embeddings.weight <-> PrimeRL: model.embed_tokens.weight
|
||||
- HF: backbone.norm_f.weight <-> PrimeRL: model.norm.weight
|
||||
- HF uses "backbone." prefix, PrimeRL uses "model." prefix
|
||||
- HF mtp.* keys (multi-token prediction) are dropped during conversion
|
||||
NemotronH is the most involved conversion: a unified HF ``mixer`` namespace is
|
||||
split into prime's ``mamba`` / ``self_attn`` / ``mlp`` by layer type, the
|
||||
checkpoint uses a ``backbone.`` prefix, and the MoE router bias is shifted by
|
||||
its per-tensor min on the way in (and intentionally *not* restored on the way
|
||||
out — a lossy roundtrip the chain reproduces via a :class:`MapValue` whose
|
||||
backward is the identity). Experts are up/down only (no gate); a dummy ``w3``
|
||||
of shape ``(0,)`` is synthesised for expert-parallel compatibility.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import (
|
||||
Conditional,
|
||||
ConvOp,
|
||||
Drop,
|
||||
MapValue,
|
||||
PrefixRename,
|
||||
Rename,
|
||||
Stack,
|
||||
Synthetic,
|
||||
key_present,
|
||||
)
|
||||
|
||||
|
||||
def _rename_keys(state_dict: dict[str, Tensor], old_prefix: str, new_prefix: str):
|
||||
"""Rename all keys matching old_prefix to new_prefix in-place."""
|
||||
keys_to_rename = [k for k in state_dict if k.startswith(old_prefix)]
|
||||
for key in keys_to_rename:
|
||||
new_key = new_prefix + key[len(old_prefix) :]
|
||||
state_dict[new_key] = state_dict.pop(key)
|
||||
def _empty_w3(prefix: str):
|
||||
def factory(sd):
|
||||
w1 = f"{prefix}.mlp.experts.w1"
|
||||
device = sd[w1].device if w1 in sd else "cpu"
|
||||
return torch.empty(0, device=device)
|
||||
|
||||
return factory
|
||||
|
||||
|
||||
def convert_hf_layer_to_prime(state_dict: dict[str, Tensor], layer_idx: int, layer_type: str):
|
||||
"""Convert a single layer from HF to PrimeRL format in-place."""
|
||||
prefix = f"model.layers.{layer_idx}."
|
||||
|
||||
if layer_type == "moe":
|
||||
_convert_hf_moe_layer_to_prime(state_dict, prefix)
|
||||
elif layer_type == "attention":
|
||||
_convert_hf_attention_layer_to_prime(state_dict, prefix)
|
||||
elif layer_type == "mamba":
|
||||
_rename_keys(state_dict, f"{prefix}mixer.", f"{prefix}mamba.")
|
||||
|
||||
|
||||
def _convert_hf_moe_layer_to_prime(state_dict: dict[str, Tensor], prefix: str):
|
||||
"""Convert MoE layer: mixer.gate -> mlp.router, mixer.experts -> mlp.experts, etc."""
|
||||
mixer = f"{prefix}mixer."
|
||||
mlp = f"{prefix}mlp."
|
||||
|
||||
# Router: gate.weight -> router.gate (nn.Parameter), gate.e_score_correction_bias -> router.e_score_correction_bias
|
||||
if f"{mixer}gate.weight" in state_dict:
|
||||
state_dict[f"{mlp}router.gate"] = state_dict.pop(f"{mixer}gate.weight")
|
||||
if f"{mixer}gate.e_score_correction_bias" in state_dict:
|
||||
bias = state_dict.pop(f"{mixer}gate.e_score_correction_bias")
|
||||
# Shift by per-row min so values land in a range bf16 can represent without
|
||||
# collapsing. NemotronH biases sit ~57 with ~0.04 inter-expert spread, well
|
||||
# under bf16's ~0.4 step at that magnitude. topk(scores + bias) is invariant
|
||||
# to a constant shift of bias, and the returned routing weights are gathered
|
||||
# from raw sigmoid scores (not biased), so this does not change routing math.
|
||||
bias = bias - bias.min()
|
||||
state_dict[f"{mlp}router.e_score_correction_bias"] = bias
|
||||
|
||||
# Experts: check if stored as individual weights (experts.{i}.up_proj.weight)
|
||||
# or fused 3D tensors (experts.up_proj)
|
||||
individual_keys = [
|
||||
k
|
||||
for k in state_dict
|
||||
if k.startswith(f"{mixer}experts.") and k[len(f"{mixer}experts.") :].split(".")[0].isdigit()
|
||||
def _moe_layer_ops(prefix: str) -> list[ConvOp]:
|
||||
return [
|
||||
# Router: gate.weight -> router.gate (note: prime drops the .weight),
|
||||
# plus the load-balancing bias which is shifted by its min on the way in
|
||||
# and not undone on the way out (MapValue backward = identity).
|
||||
Rename(f"{prefix}.mixer.gate.weight", f"{prefix}.mlp.router.gate"),
|
||||
Rename(f"{prefix}.mixer.gate.e_score_correction_bias", f"{prefix}.mlp.router.e_score_correction_bias"),
|
||||
MapValue(
|
||||
f"{prefix}.mlp.router.e_score_correction_bias",
|
||||
forward=lambda x: x - x.min(),
|
||||
backward=lambda x: x,
|
||||
),
|
||||
# Experts: w1=up, w2=down (no gate). HF is either per-expert weights or
|
||||
# a 3-D fused-at-experts-level up_proj/down_proj. Backward always emits
|
||||
# per-expert (the predicate's HF key is absent in prime -> else branch).
|
||||
Conditional(
|
||||
predicate=key_present(f"{prefix}.mixer.experts.up_proj"),
|
||||
then=[
|
||||
Rename(f"{prefix}.mixer.experts.up_proj", f"{prefix}.mlp.experts.w1"),
|
||||
Rename(f"{prefix}.mixer.experts.down_proj", f"{prefix}.mlp.experts.w2"),
|
||||
],
|
||||
else_=[
|
||||
Stack(stacked=f"{prefix}.mlp.experts.w1", item=f"{prefix}.mixer.experts.{{e}}.up_proj.weight"),
|
||||
Stack(stacked=f"{prefix}.mlp.experts.w2", item=f"{prefix}.mixer.experts.{{e}}.down_proj.weight"),
|
||||
],
|
||||
),
|
||||
Synthetic(f"{prefix}.mlp.experts.w3", factory=_empty_w3(prefix)),
|
||||
PrefixRename(f"{prefix}.mixer.shared_experts.", f"{prefix}.mlp.shared_expert."),
|
||||
PrefixRename(f"{prefix}.mixer.fc1_latent_proj.", f"{prefix}.mlp.fc1_latent_proj."),
|
||||
PrefixRename(f"{prefix}.mixer.fc2_latent_proj.", f"{prefix}.mlp.fc2_latent_proj."),
|
||||
]
|
||||
|
||||
if individual_keys:
|
||||
expert_indices = sorted({int(k[len(f"{mixer}experts.") :].split(".")[0]) for k in individual_keys})
|
||||
|
||||
up_projs = [state_dict.pop(f"{mixer}experts.{i}.up_proj.weight") for i in expert_indices]
|
||||
state_dict[f"{mlp}experts.w1"] = torch.stack(up_projs)
|
||||
|
||||
down_projs = [state_dict.pop(f"{mixer}experts.{i}.down_proj.weight") for i in expert_indices]
|
||||
state_dict[f"{mlp}experts.w2"] = torch.stack(down_projs)
|
||||
else:
|
||||
# Fused 3D tensors
|
||||
if f"{mixer}experts.up_proj" in state_dict:
|
||||
state_dict[f"{mlp}experts.w1"] = state_dict.pop(f"{mixer}experts.up_proj")
|
||||
if f"{mixer}experts.down_proj" in state_dict:
|
||||
state_dict[f"{mlp}experts.w2"] = state_dict.pop(f"{mixer}experts.down_proj")
|
||||
|
||||
# Dummy w3 required by @expert_parallel decorator compatibility
|
||||
device = state_dict[f"{mlp}experts.w1"].device if f"{mlp}experts.w1" in state_dict else "cpu"
|
||||
state_dict[f"{mlp}experts.w3"] = torch.empty(0, device=device)
|
||||
|
||||
# Shared expert
|
||||
_rename_keys(state_dict, f"{mixer}shared_experts.", f"{mlp}shared_expert.")
|
||||
|
||||
# Latent projections
|
||||
_rename_keys(state_dict, f"{mixer}fc1_latent_proj.", f"{mlp}fc1_latent_proj.")
|
||||
_rename_keys(state_dict, f"{mixer}fc2_latent_proj.", f"{mlp}fc2_latent_proj.")
|
||||
def _layer_op(prefix: str) -> ConvOp:
|
||||
"""One uniform op for any layer: detect its type from a signature key and
|
||||
dispatch. No ``layers_block_type`` needed — the unified HF ``mixer.``
|
||||
namespace is disambiguated by which sub-key is present (and, on the way
|
||||
back, by which prime namespace is present, so the predicates work both
|
||||
directions). Mamba/attention keep a bulk ``PrefixRename`` (robust to params
|
||||
we didn't enumerate); MoE needs its specific ops (and the gated
|
||||
``Synthetic`` w3, which is why this is a Conditional rather than a plain
|
||||
catch-all)."""
|
||||
is_attention = lambda sd: ( # noqa: E731
|
||||
f"{prefix}.mixer.q_proj.weight" in sd or f"{prefix}.self_attn.q_proj.weight" in sd
|
||||
)
|
||||
is_moe = lambda sd: f"{prefix}.mixer.gate.weight" in sd or f"{prefix}.mlp.router.gate" in sd # noqa: E731
|
||||
return Conditional(
|
||||
is_attention,
|
||||
then=[PrefixRename(f"{prefix}.mixer.", f"{prefix}.self_attn.")],
|
||||
else_=[
|
||||
Conditional(
|
||||
is_moe,
|
||||
then=_moe_layer_ops(prefix),
|
||||
else_=[PrefixRename(f"{prefix}.mixer.", f"{prefix}.mamba.")],
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def _convert_hf_attention_layer_to_prime(state_dict: dict[str, Tensor], prefix: str):
|
||||
"""Convert attention layer: mixer.{q,k,v,o}_proj -> self_attn.{q,k,v,o}_proj."""
|
||||
_rename_keys(state_dict, f"{prefix}mixer.", f"{prefix}self_attn.")
|
||||
|
||||
|
||||
def convert_prime_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int, layer_type: str):
|
||||
"""Convert a single layer from PrimeRL to HF format in-place."""
|
||||
prefix = f"model.layers.{layer_idx}."
|
||||
|
||||
if layer_type == "moe":
|
||||
_convert_prime_moe_layer_to_hf(state_dict, prefix)
|
||||
elif layer_type == "attention":
|
||||
_rename_keys(state_dict, f"{prefix}self_attn.", f"{prefix}mixer.")
|
||||
elif layer_type == "mamba":
|
||||
_rename_keys(state_dict, f"{prefix}mamba.", f"{prefix}mixer.")
|
||||
|
||||
|
||||
def _convert_prime_moe_layer_to_hf(state_dict: dict[str, Tensor], prefix: str):
|
||||
"""Convert MoE layer back to HF format."""
|
||||
mlp = f"{prefix}mlp."
|
||||
mixer = f"{prefix}mixer."
|
||||
|
||||
# Router
|
||||
if f"{mlp}router.gate" in state_dict:
|
||||
state_dict[f"{mixer}gate.weight"] = state_dict.pop(f"{mlp}router.gate")
|
||||
if f"{mlp}router.e_score_correction_bias" in state_dict:
|
||||
state_dict[f"{mixer}gate.e_score_correction_bias"] = state_dict.pop(f"{mlp}router.e_score_correction_bias")
|
||||
|
||||
# Experts: unstack fused 3D tensors into individual expert weights
|
||||
if f"{mlp}experts.w1" in state_dict:
|
||||
w1 = state_dict.pop(f"{mlp}experts.w1")
|
||||
for i in range(w1.shape[0]):
|
||||
state_dict[f"{mixer}experts.{i}.up_proj.weight"] = w1[i]
|
||||
if f"{mlp}experts.w2" in state_dict:
|
||||
w2 = state_dict.pop(f"{mlp}experts.w2")
|
||||
for i in range(w2.shape[0]):
|
||||
state_dict[f"{mixer}experts.{i}.down_proj.weight"] = w2[i]
|
||||
# Remove dummy w3 (not present in HF format)
|
||||
state_dict.pop(f"{mlp}experts.w3", None)
|
||||
|
||||
# Shared expert
|
||||
_rename_keys(state_dict, f"{mlp}shared_expert.", f"{mixer}shared_experts.")
|
||||
|
||||
# Latent projections
|
||||
_rename_keys(state_dict, f"{mlp}fc1_latent_proj.", f"{mixer}fc1_latent_proj.")
|
||||
_rename_keys(state_dict, f"{mlp}fc2_latent_proj.", f"{mixer}fc2_latent_proj.")
|
||||
|
||||
|
||||
def convert_hf_to_prime(state_dict: dict[str, Tensor], layers_block_type: list[str]):
|
||||
"""Convert full model from HF to PrimeRL format in-place."""
|
||||
# Handle backbone.* -> model.* prefix (HF NemotronH uses "backbone" instead of "model")
|
||||
_rename_keys(state_dict, "backbone.", "model.")
|
||||
|
||||
# Drop multi-token prediction keys (not used in training)
|
||||
for key in [k for k in state_dict if k.startswith("mtp.")]:
|
||||
del state_dict[key]
|
||||
|
||||
# Global renames
|
||||
if "model.embeddings.weight" in state_dict:
|
||||
state_dict["model.embed_tokens.weight"] = state_dict.pop("model.embeddings.weight")
|
||||
if "model.norm_f.weight" in state_dict:
|
||||
state_dict["model.norm.weight"] = state_dict.pop("model.norm_f.weight")
|
||||
|
||||
for i, layer_type in enumerate(layers_block_type):
|
||||
convert_hf_layer_to_prime(state_dict, i, layer_type)
|
||||
|
||||
|
||||
def convert_prime_to_hf(state_dict: dict[str, Tensor], layers_block_type: list[str]):
|
||||
"""Convert full model from PrimeRL to HF format in-place."""
|
||||
# Global renames
|
||||
if "model.embed_tokens.weight" in state_dict:
|
||||
state_dict["model.embeddings.weight"] = state_dict.pop("model.embed_tokens.weight")
|
||||
if "model.norm.weight" in state_dict:
|
||||
state_dict["model.norm_f.weight"] = state_dict.pop("model.norm.weight")
|
||||
|
||||
for i, layer_type in enumerate(layers_block_type):
|
||||
convert_prime_layer_to_hf(state_dict, i, layer_type)
|
||||
|
||||
# Rename model.* -> backbone.* (HF checkpoint uses "backbone" prefix)
|
||||
_rename_keys(state_dict, "model.", "backbone.")
|
||||
def conversion_chain(config) -> list[ConvOp]:
|
||||
"""Uniform per-layer dispatch — no ``layers_block_type`` required."""
|
||||
ops: list[ConvOp] = [
|
||||
# Global. Listed first so the backbone<->model swap is played LAST on the
|
||||
# way back (everything must be in model.* form before re-prefixing).
|
||||
PrefixRename("backbone.", "model."),
|
||||
Drop("mtp.", is_prefix=True),
|
||||
Rename("model.embeddings.weight", "model.embed_tokens.weight"),
|
||||
Rename("model.norm_f.weight", "model.norm.weight"),
|
||||
]
|
||||
ops.extend(_layer_op(f"model.layers.{i}") for i in range(config.num_hidden_layers))
|
||||
return ops
|
||||
|
||||
@@ -25,12 +25,7 @@ from prime_rl.trainer.models.layers.moe import LatentMoE, NemotronHRouter, NonGa
|
||||
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.ulysses_attn import ULYSSES_PARAMS
|
||||
from prime_rl.trainer.models.nemotron_h.configuration_nemotron_h import NemotronHConfig
|
||||
from prime_rl.trainer.models.nemotron_h.converting_nemotron_h import (
|
||||
convert_hf_layer_to_prime,
|
||||
convert_hf_to_prime,
|
||||
convert_prime_layer_to_hf,
|
||||
convert_prime_to_hf,
|
||||
)
|
||||
from prime_rl.trainer.models.nemotron_h.converting_nemotron_h import conversion_chain
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
@@ -349,6 +344,10 @@ class NemotronHPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
_supports_sdpa = False
|
||||
_can_compile_fullgraph = False
|
||||
|
||||
@classmethod
|
||||
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
|
||||
return name.endswith(("mamba.A_log", "mamba.D", "mlp.router.e_score_correction_bias"))
|
||||
|
||||
def _init_weights(self, module):
|
||||
std = self.config.initializer_range
|
||||
if isinstance(module, nn.Linear):
|
||||
@@ -378,17 +377,8 @@ class NemotronHPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
# Need config to know layer types; infer from state dict keys
|
||||
layers_block_type = _infer_layers_block_type(state_dict)
|
||||
convert_prime_to_hf(state_dict, layers_block_type)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
layers_block_type = _infer_layers_block_type_from_hf(state_dict)
|
||||
convert_hf_to_prime(state_dict, layers_block_type)
|
||||
return state_dict
|
||||
def conversion_chain(cls, config):
|
||||
return conversion_chain(config)
|
||||
|
||||
@classmethod
|
||||
def convert_adapter_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
@@ -407,88 +397,6 @@ class NemotronHPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
state_dict[new_key] = state_dict.pop(old_key)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
from prime_rl.trainer.models.nemotron_h.converting_nemotron_h import _rename_keys
|
||||
|
||||
if layer_idx == -1:
|
||||
# Non-layer weights: rename global keys and model.* -> backbone.*
|
||||
if "model.embed_tokens.weight" in state_dict:
|
||||
state_dict["model.embeddings.weight"] = state_dict.pop("model.embed_tokens.weight")
|
||||
if "model.norm.weight" in state_dict:
|
||||
state_dict["model.norm_f.weight"] = state_dict.pop("model.norm.weight")
|
||||
_rename_keys(state_dict, "model.", "backbone.")
|
||||
else:
|
||||
layer_type = _infer_layer_type_prime(state_dict, layer_idx)
|
||||
convert_prime_layer_to_hf(state_dict, layer_idx, layer_type)
|
||||
_rename_keys(state_dict, "model.layers.", "backbone.layers.")
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
from prime_rl.trainer.models.nemotron_h.converting_nemotron_h import _rename_keys
|
||||
|
||||
# Handle backbone.* -> model.* prefix before layer conversion
|
||||
_rename_keys(state_dict, "backbone.", "model.")
|
||||
|
||||
if layer_idx == -1:
|
||||
# Non-layer weights: rename global keys
|
||||
if "model.embeddings.weight" in state_dict:
|
||||
state_dict["model.embed_tokens.weight"] = state_dict.pop("model.embeddings.weight")
|
||||
if "model.norm_f.weight" in state_dict:
|
||||
state_dict["model.norm.weight"] = state_dict.pop("model.norm_f.weight")
|
||||
else:
|
||||
layer_type = _infer_layer_type_hf(state_dict, layer_idx)
|
||||
convert_hf_layer_to_prime(state_dict, layer_idx, layer_type)
|
||||
return state_dict
|
||||
|
||||
|
||||
def _infer_layer_type_hf(state_dict: dict[str, Tensor], layer_idx: int) -> str:
|
||||
"""Infer layer type from HF state dict keys for a given layer."""
|
||||
# HF checkpoints may use either "model." or "backbone." prefix
|
||||
for root in ("model", "backbone"):
|
||||
prefix = f"{root}.layers.{layer_idx}.mixer."
|
||||
layer_keys = [k for k in state_dict if k.startswith(prefix)]
|
||||
if layer_keys:
|
||||
for k in layer_keys:
|
||||
suffix = k[len(prefix) :]
|
||||
if suffix.startswith("gate.") or suffix.startswith("experts."):
|
||||
return "moe"
|
||||
if suffix.startswith("q_proj") or suffix.startswith("k_proj"):
|
||||
return "attention"
|
||||
return "mamba"
|
||||
return "mamba" # fallback
|
||||
|
||||
|
||||
def _infer_layer_type_prime(state_dict: dict[str, Tensor], layer_idx: int) -> str:
|
||||
"""Infer layer type from PrimeRL state dict keys for a given layer."""
|
||||
prefix = f"model.layers.{layer_idx}."
|
||||
for k in state_dict:
|
||||
if not k.startswith(prefix):
|
||||
continue
|
||||
suffix = k[len(prefix) :]
|
||||
if suffix.startswith("mlp."):
|
||||
return "moe"
|
||||
if suffix.startswith("self_attn."):
|
||||
return "attention"
|
||||
if suffix.startswith("mamba."):
|
||||
return "mamba"
|
||||
return "mamba"
|
||||
|
||||
|
||||
def _infer_layers_block_type_from_hf(state_dict: dict[str, Tensor]) -> list[str]:
|
||||
"""Infer full layers_block_type list from HF state dict."""
|
||||
# HF checkpoints may use either "model." or "backbone." prefix
|
||||
layer_keys = [k for k in state_dict if k.startswith("model.layers.") or k.startswith("backbone.layers.")]
|
||||
max_layer = max(int(k.split(".")[2]) for k in layer_keys) + 1
|
||||
return [_infer_layer_type_hf(state_dict, i) for i in range(max_layer)]
|
||||
|
||||
|
||||
def _infer_layers_block_type(state_dict: dict[str, Tensor]) -> list[str]:
|
||||
"""Infer full layers_block_type list from PrimeRL state dict."""
|
||||
max_layer = max(int(k.split(".")[2]) for k in state_dict if k.startswith("model.layers.")) + 1
|
||||
return [_infer_layer_type_prime(state_dict, i) for i in range(max_layer)]
|
||||
|
||||
|
||||
class NemotronHModel(NemotronHPreTrainedModel):
|
||||
def __init__(self, config: NemotronHConfig):
|
||||
|
||||
@@ -139,6 +139,10 @@ class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
|
||||
"hidden_states": Qwen3_5DecoderLayer,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
|
||||
return name.endswith(("linear_attn.A_log", "linear_attn.norm.weight"))
|
||||
|
||||
def _check_and_adjust_attn_implementation(
|
||||
self, attn_implementation: str | None, is_init_check: bool = False, allow_all_kernels: bool = False
|
||||
) -> str:
|
||||
|
||||
@@ -1,122 +1,34 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
"""HF<->prime weight conversion for Qwen3.5-MoE, as a declarative op chain.
|
||||
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
Per layer: router ``mlp.gate.weight`` <-> ``mlp.router.gate.weight``, the routed
|
||||
experts (per-expert gate/down/up <-> stacked w1/w2/w3, with the fused
|
||||
transformers-v5 ``gate_up_proj`` input also accepted), the shared expert
|
||||
(``mlp.shared_expert.{gate,down,up}_proj`` <-> ``shared_expert.{w1,w2,w3}``) and
|
||||
its gate (``mlp.shared_expert_gate`` <-> ``shared_expert_gate``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import ConvOp, Rename, routed_experts_op
|
||||
|
||||
|
||||
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
|
||||
"""Convert a single layer from HF to PrimeRL format in-place.
|
||||
|
||||
Handles:
|
||||
- Router: mlp.gate.weight -> mlp.router.gate.weight
|
||||
- Routed experts: fused gate_up_proj/down_proj or per-expert -> w1/w2/w3
|
||||
- Shared expert: mlp.shared_expert.{gate,up,down}_proj.weight -> shared_expert.{w1,w3,w2}.weight
|
||||
- Shared expert gate: mlp.shared_expert_gate.weight -> shared_expert_gate.weight
|
||||
"""
|
||||
i = layer_idx
|
||||
|
||||
# Router: mlp.gate.weight -> mlp.router.gate.weight
|
||||
gate_key = f"model.layers.{i}.mlp.gate.weight"
|
||||
if gate_key not in state_dict:
|
||||
return
|
||||
|
||||
state_dict[f"model.layers.{i}.mlp.router.gate.weight"] = state_dict.pop(gate_key)
|
||||
|
||||
# Routed experts: convert to fused w1/w2/w3 format
|
||||
if f"model.layers.{i}.mlp.experts.gate_up_proj" in state_dict:
|
||||
# New fused format (transformers 5.0+): gate_up_proj shape (num_experts, 2*moe_dim, dim)
|
||||
gate_up_proj = state_dict.pop(f"model.layers.{i}.mlp.experts.gate_up_proj")
|
||||
down_proj = state_dict.pop(f"model.layers.{i}.mlp.experts.down_proj")
|
||||
|
||||
moe_dim = gate_up_proj.shape[1] // 2
|
||||
w1 = gate_up_proj[:, :moe_dim, :] # gate
|
||||
w3 = gate_up_proj[:, moe_dim:, :] # up
|
||||
w2 = down_proj # down
|
||||
else:
|
||||
# Old per-expert format
|
||||
num_experts = len([k for k in state_dict.keys() if f"model.layers.{i}.mlp.experts" in k and "gate_proj" in k])
|
||||
if num_experts == 0:
|
||||
return
|
||||
|
||||
dim, moe_dim = state_dict[f"model.layers.{i}.mlp.experts.0.down_proj.weight"].shape
|
||||
dtype = state_dict[f"model.layers.{i}.mlp.experts.0.down_proj.weight"].dtype
|
||||
w1 = torch.empty((num_experts, moe_dim, dim), dtype=dtype)
|
||||
w2 = torch.empty((num_experts, dim, moe_dim), dtype=dtype)
|
||||
w3 = torch.empty((num_experts, moe_dim, dim), dtype=dtype)
|
||||
for j in range(num_experts):
|
||||
w1[j].copy_(state_dict.pop(f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"))
|
||||
w2[j].copy_(state_dict.pop(f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"))
|
||||
w3[j].copy_(state_dict.pop(f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"))
|
||||
|
||||
state_dict[f"model.layers.{i}.mlp.experts.w1"] = w1
|
||||
state_dict[f"model.layers.{i}.mlp.experts.w2"] = w2
|
||||
state_dict[f"model.layers.{i}.mlp.experts.w3"] = w3
|
||||
|
||||
# Shared expert: mlp.shared_expert.{gate,up,down}_proj -> shared_expert.{w1,w3,w2}
|
||||
se_gate_key = f"model.layers.{i}.mlp.shared_expert.gate_proj.weight"
|
||||
if se_gate_key in state_dict:
|
||||
state_dict[f"model.layers.{i}.shared_expert.w1.weight"] = state_dict.pop(se_gate_key)
|
||||
state_dict[f"model.layers.{i}.shared_expert.w2.weight"] = state_dict.pop(
|
||||
f"model.layers.{i}.mlp.shared_expert.down_proj.weight"
|
||||
)
|
||||
state_dict[f"model.layers.{i}.shared_expert.w3.weight"] = state_dict.pop(
|
||||
f"model.layers.{i}.mlp.shared_expert.up_proj.weight"
|
||||
)
|
||||
|
||||
# Shared expert gate: mlp.shared_expert_gate.weight -> shared_expert_gate.weight
|
||||
seg_key = f"model.layers.{i}.mlp.shared_expert_gate.weight"
|
||||
if seg_key in state_dict:
|
||||
state_dict[f"model.layers.{i}.shared_expert_gate.weight"] = state_dict.pop(seg_key)
|
||||
def _conversion_chain(config, model_prefix: str) -> list[ConvOp]:
|
||||
ops: list[ConvOp] = []
|
||||
for i in range(config.num_hidden_layers):
|
||||
p = f"{model_prefix}.layers.{i}"
|
||||
# Router: mlp.gate.weight -> mlp.router.gate.weight
|
||||
ops.append(Rename(f"{p}.mlp.gate.weight", f"{p}.mlp.router.gate.weight"))
|
||||
# Routed experts: per-expert (gate/down/up) or fused gate_up_proj -> w1/w2/w3
|
||||
ops.append(routed_experts_op(p, hf_experts="mlp.experts", prime_experts="mlp.experts", fused=True))
|
||||
# Shared expert: mlp.shared_expert.{gate,down,up}_proj.weight -> shared_expert.{w1,w2,w3}.weight
|
||||
ops.append(Rename(f"{p}.mlp.shared_expert.gate_proj.weight", f"{p}.shared_expert.w1.weight"))
|
||||
ops.append(Rename(f"{p}.mlp.shared_expert.down_proj.weight", f"{p}.shared_expert.w2.weight"))
|
||||
ops.append(Rename(f"{p}.mlp.shared_expert.up_proj.weight", f"{p}.shared_expert.w3.weight"))
|
||||
# Shared expert gate
|
||||
ops.append(Rename(f"{p}.mlp.shared_expert_gate.weight", f"{p}.shared_expert_gate.weight"))
|
||||
return ops
|
||||
|
||||
|
||||
def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int):
|
||||
"""Convert a single layer from PrimeRL to HF format in-place."""
|
||||
i = layer_idx
|
||||
|
||||
# Router
|
||||
router_key = f"model.layers.{i}.mlp.router.gate.weight"
|
||||
if router_key not in state_dict:
|
||||
return
|
||||
|
||||
state_dict[f"model.layers.{i}.mlp.gate.weight"] = state_dict.pop(router_key)
|
||||
|
||||
# Routed experts: w1/w2/w3 -> per-expert format
|
||||
w1 = state_dict.pop(f"model.layers.{i}.mlp.experts.w1")
|
||||
w2 = state_dict.pop(f"model.layers.{i}.mlp.experts.w2")
|
||||
w3 = state_dict.pop(f"model.layers.{i}.mlp.experts.w3")
|
||||
|
||||
num_experts = w1.shape[0]
|
||||
for j in range(num_experts):
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"] = w1[j]
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"] = w2[j]
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"] = w3[j]
|
||||
|
||||
# Shared expert: shared_expert.{w1,w2,w3} -> mlp.shared_expert.{gate,down,up}_proj
|
||||
se_w1_key = f"model.layers.{i}.shared_expert.w1.weight"
|
||||
if se_w1_key in state_dict:
|
||||
state_dict[f"model.layers.{i}.mlp.shared_expert.gate_proj.weight"] = state_dict.pop(se_w1_key)
|
||||
state_dict[f"model.layers.{i}.mlp.shared_expert.down_proj.weight"] = state_dict.pop(
|
||||
f"model.layers.{i}.shared_expert.w2.weight"
|
||||
)
|
||||
state_dict[f"model.layers.{i}.mlp.shared_expert.up_proj.weight"] = state_dict.pop(
|
||||
f"model.layers.{i}.shared_expert.w3.weight"
|
||||
)
|
||||
|
||||
# Shared expert gate
|
||||
seg_key = f"model.layers.{i}.shared_expert_gate.weight"
|
||||
if seg_key in state_dict:
|
||||
state_dict[f"model.layers.{i}.mlp.shared_expert_gate.weight"] = state_dict.pop(seg_key)
|
||||
|
||||
|
||||
def convert_hf_to_tt_moe(state_dict: dict[str, Tensor]):
|
||||
"""Convert all MoE weights from HF to PrimeRL format in-place."""
|
||||
num_layers = get_max_layer_num(state_dict)
|
||||
for i in range(num_layers):
|
||||
convert_hf_layer_to_tt(state_dict, i)
|
||||
|
||||
|
||||
def convert_tt_to_hf_moe(state_dict: dict[str, Tensor]):
|
||||
"""Convert all MoE weights from PrimeRL to HF format in-place."""
|
||||
num_layers = get_max_layer_num(state_dict)
|
||||
for i in range(num_layers):
|
||||
convert_tt_layer_to_hf(state_dict, i)
|
||||
def conversion_chain(config) -> list[ConvOp]:
|
||||
text_config = getattr(config, "text_config", config)
|
||||
return _conversion_chain(text_config, "model") + _conversion_chain(text_config, "model.language_model")
|
||||
|
||||
@@ -32,12 +32,7 @@ from prime_rl.utils.cp import setup_cp_attention_params, shard_for_cp, shard_pos
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
from .configuration_qwen3_5_moe import Qwen3_5MoeConfig
|
||||
from .converting_qwen3_5_moe import (
|
||||
convert_hf_layer_to_tt,
|
||||
convert_hf_to_tt_moe,
|
||||
convert_tt_layer_to_hf,
|
||||
convert_tt_to_hf_moe,
|
||||
)
|
||||
from .converting_qwen3_5_moe import conversion_chain
|
||||
from .mrope import build_qwen3_5_mrope_position_ids
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
@@ -631,6 +626,10 @@ class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
"hidden_states": Qwen3_5MoeDecoderLayer,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def keep_in_fp32_for_weight_transfer(cls, name: str) -> bool:
|
||||
return name.endswith(("linear_attn.A_log", "linear_attn.norm.weight"))
|
||||
|
||||
def _check_and_adjust_attn_implementation(
|
||||
self, attn_implementation: str | None, is_init_check: bool = False, allow_all_kernels: bool = False
|
||||
) -> str:
|
||||
@@ -656,24 +655,8 @@ class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
return any("mlp.experts.w1" in name for name in state_dict.keys())
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
convert_tt_to_hf_moe(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
convert_hf_to_tt_moe(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
convert_tt_layer_to_hf(state_dict, layer_idx)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
convert_hf_layer_to_tt(state_dict, layer_idx)
|
||||
return state_dict
|
||||
def conversion_chain(cls, config):
|
||||
return conversion_chain(config)
|
||||
|
||||
|
||||
class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
|
||||
@@ -894,24 +877,6 @@ class Qwen3_5MoeVLMModel(nn.Module):
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _has_vlm_keys(state_dict: dict[str, Tensor]) -> bool:
|
||||
return any(k.startswith("model.language_model.") for k in state_dict)
|
||||
|
||||
|
||||
def _remap_lm_keys(state_dict: dict[str, Tensor], to_flat: bool = True) -> None:
|
||||
"""Remap language model keys between VLM and flat format for weight conversion.
|
||||
|
||||
to_flat=True: model.language_model.* -> model.*
|
||||
to_flat=False: model.* -> model.language_model.*
|
||||
|
||||
Vision keys (model.visual.*) are never touched.
|
||||
"""
|
||||
src = "model.language_model." if to_flat else "model."
|
||||
dst = "model." if to_flat else "model.language_model."
|
||||
for k in [k for k in list(state_dict.keys()) if k.startswith(src) and not k.startswith("model.visual.")]:
|
||||
state_dict[dst + k[len(src) :]] = state_dict.pop(k)
|
||||
|
||||
|
||||
class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin):
|
||||
"""Unified Qwen3.5 MoE model for both text-only and VLM configs.
|
||||
|
||||
@@ -972,46 +937,6 @@ class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin):
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return any("mlp.experts.w1" in name for name in state_dict)
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
vlm = _has_vlm_keys(state_dict)
|
||||
if vlm:
|
||||
_remap_lm_keys(state_dict, to_flat=True)
|
||||
convert_tt_to_hf_moe(state_dict)
|
||||
if vlm:
|
||||
_remap_lm_keys(state_dict, to_flat=False)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
vlm = _has_vlm_keys(state_dict)
|
||||
if vlm:
|
||||
_remap_lm_keys(state_dict, to_flat=True)
|
||||
convert_hf_to_tt_moe(state_dict)
|
||||
if vlm:
|
||||
_remap_lm_keys(state_dict, to_flat=False)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
vlm = _has_vlm_keys(state_dict)
|
||||
if vlm:
|
||||
_remap_lm_keys(state_dict, to_flat=True)
|
||||
convert_tt_layer_to_hf(state_dict, layer_idx)
|
||||
if vlm:
|
||||
_remap_lm_keys(state_dict, to_flat=False)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
vlm = _has_vlm_keys(state_dict)
|
||||
if vlm:
|
||||
_remap_lm_keys(state_dict, to_flat=True)
|
||||
convert_hf_layer_to_tt(state_dict, layer_idx)
|
||||
if vlm:
|
||||
_remap_lm_keys(state_dict, to_flat=False)
|
||||
return state_dict
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Forward
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@@ -1,97 +1,14 @@
|
||||
import torch
|
||||
from torch import Tensor
|
||||
"""HF<->PrimeRL weight conversion for Qwen3-MoE."""
|
||||
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
from __future__ import annotations
|
||||
|
||||
from prime_rl.trainer.models.conversion_ops import ConvOp, Rename, routed_experts_op
|
||||
|
||||
|
||||
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
|
||||
"""Convert a layer from HF to TT format in-place."""
|
||||
i = layer_idx
|
||||
|
||||
# Check if this is a MoE layer by looking for gate weight
|
||||
if f"model.layers.{i}.mlp.gate.weight" not in state_dict:
|
||||
return
|
||||
|
||||
state_dict[f"model.layers.{i}.mlp.router.gate.weight"] = state_dict[f"model.layers.{i}.mlp.gate.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.gate.weight"]
|
||||
|
||||
# Check if this is the new fused format (transformers 5.0+) or old per-expert format
|
||||
if f"model.layers.{i}.mlp.experts.gate_up_proj" in state_dict:
|
||||
# New fused format: gate_up_proj has shape (num_experts, 2*moe_dim, dim)
|
||||
gate_up_proj = state_dict[f"model.layers.{i}.mlp.experts.gate_up_proj"]
|
||||
down_proj = state_dict[f"model.layers.{i}.mlp.experts.down_proj"]
|
||||
|
||||
num_experts, fused_dim, dim = gate_up_proj.shape
|
||||
moe_dim = fused_dim // 2
|
||||
|
||||
# Split gate_up_proj into w1 (gate) and w3 (up)
|
||||
w1 = gate_up_proj[:, :moe_dim, :] # Gate: (num_experts, moe_dim, dim)
|
||||
w3 = gate_up_proj[:, moe_dim:, :] # Up: (num_experts, moe_dim, dim)
|
||||
w2 = down_proj # Down: (num_experts, dim, moe_dim)
|
||||
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.gate_up_proj"]
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.down_proj"]
|
||||
else:
|
||||
# Old per-expert format
|
||||
num_experts = len([j for j in state_dict.keys() if f"model.layers.{i}.mlp.experts" in j]) // 3
|
||||
if num_experts == 0:
|
||||
return
|
||||
|
||||
dim, moe_dim = state_dict[f"model.layers.{i}.mlp.experts.0.down_proj.weight"].shape
|
||||
w1 = torch.empty(
|
||||
(num_experts, moe_dim, dim), dtype=state_dict[f"model.layers.{i}.mlp.experts.0.down_proj.weight"].dtype
|
||||
) # Gate
|
||||
w2 = torch.empty(
|
||||
(num_experts, dim, moe_dim), dtype=state_dict[f"model.layers.{i}.mlp.experts.0.down_proj.weight"].dtype
|
||||
) # Down
|
||||
w3 = torch.empty(
|
||||
(num_experts, moe_dim, dim), dtype=state_dict[f"model.layers.{i}.mlp.experts.0.down_proj.weight"].dtype
|
||||
) # Up
|
||||
for j in range(num_experts):
|
||||
w1[j].copy_(state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"])
|
||||
w2[j].copy_(state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"])
|
||||
w3[j].copy_(state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"])
|
||||
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"]
|
||||
|
||||
state_dict[f"model.layers.{i}.mlp.experts.w1"] = w1
|
||||
state_dict[f"model.layers.{i}.mlp.experts.w2"] = w2
|
||||
state_dict[f"model.layers.{i}.mlp.experts.w3"] = w3
|
||||
|
||||
|
||||
def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_index: int):
|
||||
"""Convert a layer from TT to HF format in-place."""
|
||||
i = layer_index
|
||||
if f"model.layers.{i}.mlp.router.gate.weight" not in state_dict:
|
||||
return
|
||||
|
||||
# Gate / Router
|
||||
state_dict[f"model.layers.{i}.mlp.gate.weight"] = state_dict[f"model.layers.{i}.mlp.router.gate.weight"]
|
||||
del state_dict[f"model.layers.{i}.mlp.router.gate.weight"]
|
||||
|
||||
# Routed experts - convert to per-expert format (compatible with vLLM and transformers)
|
||||
w1 = state_dict.pop(f"model.layers.{i}.mlp.experts.w1") # (num_experts, moe_dim, dim)
|
||||
w2 = state_dict.pop(f"model.layers.{i}.mlp.experts.w2") # (num_experts, dim, moe_dim)
|
||||
w3 = state_dict.pop(f"model.layers.{i}.mlp.experts.w3") # (num_experts, moe_dim, dim)
|
||||
|
||||
num_experts = w1.shape[0]
|
||||
for j in range(num_experts):
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"] = w1[j]
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"] = w2[j]
|
||||
state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"] = w3[j]
|
||||
|
||||
|
||||
def convert_hf_to_tt_moe(state_dict: dict[str, Tensor]):
|
||||
"""Convert MoE weights from HF to TT format in-place."""
|
||||
num_layers = get_max_layer_num(state_dict)
|
||||
for i in range(num_layers):
|
||||
convert_hf_layer_to_tt(state_dict, i)
|
||||
|
||||
|
||||
def convert_tt_to_hf_moe(state_dict: dict[str, Tensor]):
|
||||
"""Convert MoE weights from TT to HF format in-place."""
|
||||
num_layers = get_max_layer_num(state_dict)
|
||||
for i in range(num_layers):
|
||||
convert_tt_layer_to_hf(state_dict, i)
|
||||
def conversion_chain(config) -> list[ConvOp]:
|
||||
ops: list[ConvOp] = []
|
||||
for layer_idx in range(config.num_hidden_layers):
|
||||
prefix = f"model.layers.{layer_idx}"
|
||||
ops.append(Rename(f"{prefix}.mlp.gate.weight", f"{prefix}.mlp.router.gate.weight"))
|
||||
ops.append(routed_experts_op(prefix, hf_experts="mlp.experts", prime_experts="mlp.experts", fused=True))
|
||||
return ops
|
||||
|
||||
@@ -34,12 +34,7 @@ from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
from prime_rl.trainer.models.qwen3_moe.configuration_qwen3_moe import Qwen3MoeConfig
|
||||
from prime_rl.trainer.models.qwen3_moe.converting_qwen3_moe import (
|
||||
convert_hf_layer_to_tt,
|
||||
convert_hf_to_tt_moe,
|
||||
convert_tt_layer_to_hf,
|
||||
convert_tt_to_hf_moe,
|
||||
)
|
||||
from prime_rl.trainer.models.qwen3_moe.converting_qwen3_moe import conversion_chain
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_seq_lens
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
@@ -147,28 +142,8 @@ class Qwen3MoePreTrainedModel(PreTrainedModelPrimeRL):
|
||||
return any("mlp.experts.w1" in module_name for module_name in state_dict.keys())
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
"""Convert MoE weights from PrimeRL training format to HuggingFace format in-place."""
|
||||
convert_tt_to_hf_moe(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
"""Convert MoE weights from HuggingFace format to PrimeRL training format in-place."""
|
||||
convert_hf_to_tt_moe(state_dict)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
"""Convert a single layer's MoE weights from PrimeRL format to HuggingFace format in-place."""
|
||||
convert_tt_layer_to_hf(state_dict, layer_idx)
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
|
||||
"""Convert a single layer's MoE weights from HuggingFace format to PrimeRL format in-place."""
|
||||
convert_hf_layer_to_tt(state_dict, layer_idx)
|
||||
return state_dict
|
||||
def conversion_chain(cls, config):
|
||||
return conversion_chain(config)
|
||||
|
||||
|
||||
@auto_docstring
|
||||
|
||||
@@ -3,17 +3,24 @@ from pathlib import Path
|
||||
import torch
|
||||
|
||||
from prime_rl.configs.trainer import LoRAConfig, WeightBroadcastConfig
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.trainer.rl.broadcast.base import WeightBroadcast
|
||||
from prime_rl.trainer.rl.broadcast.filesystem import FileSystemWeightBroadcast
|
||||
from prime_rl.trainer.rl.broadcast.nccl import NCCLWeightBroadcast
|
||||
from prime_rl.trainer.rl.broadcast.nixl import NIXLWeightBroadcast
|
||||
|
||||
|
||||
def setup_weight_broadcast(
|
||||
output_dir: Path, config: WeightBroadcastConfig, lora_config: LoRAConfig | None = None
|
||||
output_dir: Path,
|
||||
config: WeightBroadcastConfig,
|
||||
parallel_dims: ParallelDims,
|
||||
lora_config: LoRAConfig | None = None,
|
||||
) -> WeightBroadcast:
|
||||
if config.type == "nccl":
|
||||
return NCCLWeightBroadcast(output_dir, config, torch.cuda.current_device())
|
||||
elif config.type == "filesystem":
|
||||
return FileSystemWeightBroadcast(output_dir, config, lora_config)
|
||||
elif config.type == "nixl":
|
||||
return NIXLWeightBroadcast(output_dir, config, parallel_dims)
|
||||
else:
|
||||
raise ValueError(f"Invalid weight broadcast type: {config.type}")
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
"""NIXL weight broadcasting and transfer helpers."""
|
||||
|
||||
from prime_rl.trainer.rl.broadcast.nixl.nixl import NIXLWeightBroadcast
|
||||
|
||||
__all__ = ["NIXLWeightBroadcast"]
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Small NIXL adapter used by the trainer and vLLM workers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import socket
|
||||
import time
|
||||
from typing import Any, Callable, Sequence
|
||||
|
||||
from torch import Tensor
|
||||
|
||||
MemDesc = tuple[int, int, int]
|
||||
|
||||
|
||||
class NixlAgent:
|
||||
def __init__(self, name: str) -> None:
|
||||
try:
|
||||
from nixl_cu13._api import nixl_agent, nixl_agent_config # type: ignore[import-not-found]
|
||||
except ImportError:
|
||||
from nixl._api import nixl_agent, nixl_agent_config # type: ignore[import-not-found]
|
||||
|
||||
self.name = name
|
||||
self._agent = nixl_agent(name, nixl_agent_config(backends=["UCX"]))
|
||||
|
||||
def register_tensor(self, tensor: Tensor) -> None:
|
||||
self._agent.register_memory(tensor, backends=["UCX"])
|
||||
|
||||
def get_metadata(self) -> bytes:
|
||||
return self._agent.get_agent_metadata()
|
||||
|
||||
def add_remote_agent(self, metadata: bytes) -> str:
|
||||
return self._agent.add_remote_agent(metadata)
|
||||
|
||||
def make_connection(self, peer_name: str) -> None:
|
||||
self._agent.make_connection(peer_name)
|
||||
|
||||
def prepare_xfer_dlist(self, descs: Sequence[MemDesc], agent_name: str | None = None) -> Any:
|
||||
return self._agent.prep_xfer_dlist(
|
||||
agent_name=agent_name or "",
|
||||
xfer_list=list(descs),
|
||||
mem_type="cuda",
|
||||
backends=["UCX"],
|
||||
)
|
||||
|
||||
def post_read(self, local: Any, indices: Sequence[int], remote: Any) -> Any:
|
||||
handle = self._agent.make_prepped_xfer(
|
||||
operation="READ",
|
||||
local_xfer_side=local,
|
||||
local_indices=list(indices),
|
||||
remote_xfer_side=remote,
|
||||
remote_indices=list(indices),
|
||||
backends=["UCX"],
|
||||
)
|
||||
state = self._agent.transfer(handle)
|
||||
if state in ("ERR", "ERROR", "FAIL"):
|
||||
raise RuntimeError(f"NIXL READ post failed with state {state}")
|
||||
return handle
|
||||
|
||||
def wait(
|
||||
self,
|
||||
handle: Any,
|
||||
context: str = "",
|
||||
timeout: float | None = None,
|
||||
cancelled: Callable[[], bool] | None = None,
|
||||
) -> None:
|
||||
deadline = None if timeout is None else time.monotonic() + timeout
|
||||
while True:
|
||||
if cancelled is not None and cancelled():
|
||||
self._agent.release_xfer_handle(handle)
|
||||
raise RuntimeError(f"NIXL transfer cancelled, context={context!r}")
|
||||
state = self._agent.check_xfer_state(handle)
|
||||
if state in ("DONE", "SUCCESS"):
|
||||
self._agent.release_xfer_handle(handle)
|
||||
return
|
||||
if state in ("ERR", "ERROR", "FAIL"):
|
||||
self._agent.release_xfer_handle(handle)
|
||||
raise RuntimeError(f"NIXL transfer failed with state={state}, context={context!r}")
|
||||
if deadline is not None and time.monotonic() >= deadline:
|
||||
self._agent.release_xfer_handle(handle)
|
||||
raise TimeoutError(f"NIXL transfer timed out after {timeout}s, context={context!r}")
|
||||
time.sleep(0.0005)
|
||||
|
||||
|
||||
def make_agent_name(role: str, global_rank: int) -> str:
|
||||
return f"{role}-{socket.gethostname()}-r{global_rank}"
|
||||
|
||||
|
||||
def set_ucx_env_defaults() -> None:
|
||||
os.environ.setdefault("UCX_TLS", "rc_x,rc,dc_x,dc,cuda_copy")
|
||||
os.environ.setdefault("UCX_IB_GPU_DIRECT_RDMA", "y")
|
||||
os.environ.setdefault("UCX_RNDV_SCHEME", "get_zcopy")
|
||||
os.environ.setdefault("UCX_RNDV_THRESH", "0")
|
||||
os.environ.setdefault("UCX_MEMTYPE_CACHE", "n")
|
||||
os.environ.setdefault("UCX_WARN_UNUSED_ENV_VARS", "n")
|
||||
@@ -0,0 +1,78 @@
|
||||
"""CUDA memory sizing and a cudaMalloc-backed pool for NIXL arenas."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Iterator
|
||||
|
||||
try:
|
||||
ctypes.CDLL("libcudart.so", mode=ctypes.RTLD_GLOBAL)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
import torch # noqa: E402
|
||||
from torch.utils.cpp_extension import load_inline # noqa: E402
|
||||
|
||||
_pool: torch.cuda.MemPool | None = None
|
||||
_allocator: torch.cuda.memory.CUDAPluggableAllocator | None = None
|
||||
|
||||
|
||||
def size_cuda_buffers(
|
||||
buffer_bytes: int,
|
||||
max_buffers: int,
|
||||
device: torch.device,
|
||||
extra_headroom_bytes: int,
|
||||
) -> int:
|
||||
free_bytes, total_bytes = torch.cuda.mem_get_info(device)
|
||||
headroom_bytes = max(4 * 1024**3, int(total_bytes * 0.02)) + extra_headroom_bytes
|
||||
return max(1, min(max_buffers, (free_bytes - headroom_bytes) // buffer_bytes))
|
||||
|
||||
|
||||
def _get_pool() -> torch.cuda.MemPool:
|
||||
global _pool, _allocator
|
||||
if _pool is not None:
|
||||
return _pool
|
||||
module = load_inline(
|
||||
name="cuda_malloc_allocator",
|
||||
cpp_sources=[
|
||||
r"""
|
||||
#include <cuda_runtime.h>
|
||||
#include <cstddef>
|
||||
extern "C" {
|
||||
void* cuda_malloc(ptrdiff_t size, int device, void* stream) {
|
||||
(void) stream;
|
||||
int previous = -1;
|
||||
cudaGetDevice(&previous);
|
||||
cudaSetDevice(device);
|
||||
void* pointer = nullptr;
|
||||
cudaError_t error = cudaMalloc(&pointer, (size_t) size);
|
||||
if (previous >= 0) cudaSetDevice(previous);
|
||||
if (error != cudaSuccess) return nullptr;
|
||||
return pointer;
|
||||
}
|
||||
void cuda_free(void* pointer, ptrdiff_t size, int device, void* stream) {
|
||||
(void) size; (void) stream;
|
||||
int previous = -1;
|
||||
cudaGetDevice(&previous);
|
||||
cudaSetDevice(device);
|
||||
cudaFree(pointer);
|
||||
if (previous >= 0) cudaSetDevice(previous);
|
||||
}
|
||||
}
|
||||
"""
|
||||
],
|
||||
functions=[],
|
||||
extra_cflags=["-O2"],
|
||||
with_cuda=True,
|
||||
)
|
||||
_allocator = torch.cuda.memory.CUDAPluggableAllocator(str(Path(module.__file__)), "cuda_malloc", "cuda_free")
|
||||
_pool = torch.cuda.MemPool(_allocator.allocator())
|
||||
return _pool
|
||||
|
||||
|
||||
@contextmanager
|
||||
def use_cuda_malloc_pool() -> Iterator[None]:
|
||||
with torch.cuda.use_mem_pool(_get_pool()):
|
||||
yield
|
||||
@@ -0,0 +1,345 @@
|
||||
"""Trace, plan, and replay composed weight-loading graphs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Callable
|
||||
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.rl.broadcast.nixl.trainer_tensor_table import TrainerTensorTable
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TensorOperation:
|
||||
"""One replayable tensor method invocation."""
|
||||
|
||||
name: str
|
||||
args: tuple[Any, ...] = ()
|
||||
kwargs: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
OperationChain = tuple[TensorOperation, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TensorReplayPlan:
|
||||
"""Source view to pull directly and operations to replay locally."""
|
||||
|
||||
source_offset: int
|
||||
source_shape: tuple[int, ...]
|
||||
source_stride: tuple[int, ...]
|
||||
replay_ops: OperationChain
|
||||
|
||||
|
||||
SUPPORTED_OPS: dict[Any, str] = {
|
||||
torch.Tensor.narrow: "narrow",
|
||||
torch.Tensor.select: "select",
|
||||
torch.Tensor.view: "view",
|
||||
torch.Tensor.reshape: "reshape",
|
||||
torch.Tensor.__getitem__: "__getitem__",
|
||||
torch.Tensor.unsqueeze: "unsqueeze",
|
||||
torch.Tensor.squeeze: "squeeze",
|
||||
torch.Tensor.transpose: "transpose",
|
||||
torch.Tensor.t: "t",
|
||||
torch.Tensor.permute: "permute",
|
||||
torch.Tensor.flatten: "flatten",
|
||||
torch.Tensor.contiguous: "contiguous",
|
||||
torch.Tensor.chunk: "chunk",
|
||||
torch.Tensor.split: "split",
|
||||
torch.Tensor.unbind: "unbind",
|
||||
torch.Tensor.to: "to",
|
||||
torch.Tensor.float: "float",
|
||||
torch.Tensor.bfloat16: "bfloat16",
|
||||
}
|
||||
_SUPPORTED_DTYPES = (torch.bfloat16, torch.float32)
|
||||
|
||||
|
||||
class UnsupportedOpError(NotImplementedError):
|
||||
pass
|
||||
|
||||
|
||||
def apply_chain(value: Any, ops: OperationChain) -> torch.Tensor:
|
||||
"""Replay a recorded chain, including deferred dtype conversions."""
|
||||
# Invariant: LazyWeight records only operations from SUPPORTED_OPS and
|
||||
# follows tuple-returning methods with tuple_getitem, so every chain ends
|
||||
# in a tensor.
|
||||
result = value
|
||||
for operation in ops:
|
||||
if operation.name == "tuple_getitem":
|
||||
result = result[operation.args[0]]
|
||||
elif operation.name == "__getitem__":
|
||||
result = result[operation.args[0]]
|
||||
else:
|
||||
result = getattr(result, operation.name)(*operation.args, **operation.kwargs)
|
||||
return result
|
||||
|
||||
|
||||
def is_view_of(value: torch.Tensor, root: torch.Tensor) -> bool:
|
||||
"""Whether ``value`` is ``root`` or a view backed by ``root``."""
|
||||
if value is root:
|
||||
return True
|
||||
current = value
|
||||
seen: set[int] = set()
|
||||
while current._base is not None and id(current) not in seen:
|
||||
seen.add(id(current))
|
||||
current = current._base
|
||||
if current is root:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def plan_tensor_replay(shape: tuple[int, ...], dtype: torch.dtype, ops: OperationChain) -> TensorReplayPlan:
|
||||
"""Resolve a directly transferable source view and local replay suffix.
|
||||
|
||||
The prefix must remain a same-dtype view of the trainer root and can
|
||||
therefore be addressed by RDMA. The first materializing or dtype-changing
|
||||
operation and everything after it is replayed on the receive arena.
|
||||
"""
|
||||
root = torch.empty(shape, dtype=dtype, device="meta")
|
||||
prefix_len = 0
|
||||
source_view = root
|
||||
for candidate_len in range(1, len(ops) + 1):
|
||||
# Tuple-returning operations and their tuple_getitem are recorded as
|
||||
# one logical operation, so they must remain on the same side.
|
||||
if candidate_len < len(ops) and ops[candidate_len].name == "tuple_getitem":
|
||||
continue
|
||||
candidate = apply_chain(root, ops[:candidate_len])
|
||||
if candidate.dtype != dtype or not is_view_of(candidate, root):
|
||||
break
|
||||
prefix_len = candidate_len
|
||||
source_view = candidate
|
||||
return TensorReplayPlan(
|
||||
source_offset=source_view.storage_offset(),
|
||||
source_shape=tuple(source_view.shape),
|
||||
source_stride=tuple(source_view.stride()),
|
||||
replay_ops=ops[prefix_len:],
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class RecordedCopy:
|
||||
source_name: str
|
||||
ops: OperationChain
|
||||
destination_module: Any
|
||||
destination_name: str
|
||||
destination_offset: int
|
||||
destination_shape: tuple[int, ...]
|
||||
destination_stride: tuple[int, ...]
|
||||
is_persistent: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True, eq=False)
|
||||
class Destination:
|
||||
"""A vLLM destination tensor and its owning module attribute."""
|
||||
|
||||
module: Any
|
||||
name: str
|
||||
tensor: torch.Tensor
|
||||
|
||||
def storage_offset_of(self, tensor: torch.Tensor) -> int | None:
|
||||
base_addr = self.tensor.data_ptr()
|
||||
addr = tensor.data_ptr()
|
||||
nbytes = self.tensor.numel() * self.tensor.element_size()
|
||||
if base_addr <= addr < base_addr + nbytes:
|
||||
return (addr - base_addr) // self.tensor.element_size()
|
||||
return None
|
||||
|
||||
|
||||
@dataclass
|
||||
class WeightLoadRecorder:
|
||||
copies: list[RecordedCopy] = field(default_factory=list)
|
||||
active_destination: Destination | None = None
|
||||
destination_storage_ranges: list[Destination] = field(default_factory=list)
|
||||
|
||||
def register_destination_storage(self, destination: Destination) -> None:
|
||||
self.destination_storage_ranges.append(destination)
|
||||
|
||||
def resolve_destination(self, tensor: torch.Tensor) -> tuple[Destination, int] | None:
|
||||
if self.active_destination is not None:
|
||||
return self.active_destination, tensor.storage_offset()
|
||||
if tensor.is_meta:
|
||||
return None
|
||||
for destination in self.destination_storage_ranges:
|
||||
offset = destination.storage_offset_of(tensor)
|
||||
if offset is not None:
|
||||
return destination, offset
|
||||
return None
|
||||
|
||||
|
||||
class LazyWeight(torch.Tensor):
|
||||
"""Wrapper tensor that records views, casts, and terminal ``copy_`` calls."""
|
||||
|
||||
@staticmethod
|
||||
def __new__(
|
||||
cls,
|
||||
source_name: str,
|
||||
source_shape: torch.Size,
|
||||
source_dtype: torch.dtype,
|
||||
device: torch.device,
|
||||
recorder: WeightLoadRecorder,
|
||||
ops: OperationChain = (),
|
||||
) -> "LazyWeight":
|
||||
meta = apply_chain(torch.empty(source_shape, dtype=source_dtype, device="meta"), ops)
|
||||
value = torch.Tensor._make_wrapper_subclass(
|
||||
cls,
|
||||
meta.shape,
|
||||
strides=meta.stride(),
|
||||
storage_offset=meta.storage_offset(),
|
||||
dtype=meta.dtype,
|
||||
device=device,
|
||||
requires_grad=False,
|
||||
)
|
||||
value._source_name = source_name
|
||||
value._source_shape = torch.Size(source_shape)
|
||||
value._source_dtype = source_dtype
|
||||
value._ops = tuple(ops)
|
||||
value._recorder = recorder
|
||||
return value
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
f"LazyWeight(source_name={self._source_name!r}, shape={tuple(self.shape)}, "
|
||||
f"dtype={self.dtype}, ops={self._ops!r})"
|
||||
)
|
||||
|
||||
def _meta(self) -> torch.Tensor:
|
||||
source = torch.empty(self._source_shape, dtype=self._source_dtype, device="meta")
|
||||
return apply_chain(source, self._ops)
|
||||
|
||||
def _child(self, *ops: TensorOperation) -> "LazyWeight":
|
||||
return LazyWeight(
|
||||
self._source_name,
|
||||
self._source_shape,
|
||||
self._source_dtype,
|
||||
self.device,
|
||||
self._recorder,
|
||||
self._ops + ops,
|
||||
)
|
||||
|
||||
def _record_copy(self, destination: torch.Tensor) -> torch.Tensor:
|
||||
if isinstance(destination, LazyWeight):
|
||||
raise UnsupportedOpError("copy_ between lazy graph tensors is not supported")
|
||||
if tuple(destination.shape) != tuple(self.shape):
|
||||
raise UnsupportedOpError(
|
||||
f"copy_ shape mismatch for {self._source_name}: {tuple(self.shape)} -> {tuple(destination.shape)}"
|
||||
)
|
||||
if self.dtype not in _SUPPORTED_DTYPES or destination.dtype not in _SUPPORTED_DTYPES:
|
||||
raise UnsupportedOpError(
|
||||
f"NIXL lazy copies only support BF16/FP32 values, got "
|
||||
f"source={self.dtype}, destination={destination.dtype} for {self._source_name!r}"
|
||||
)
|
||||
|
||||
resolved_destination = self._recorder.resolve_destination(destination)
|
||||
if resolved_destination is not None:
|
||||
owner, destination_offset = resolved_destination
|
||||
self._recorder.copies.append(
|
||||
RecordedCopy(
|
||||
source_name=self._source_name,
|
||||
ops=self._ops,
|
||||
destination_module=owner.module,
|
||||
destination_name=owner.name,
|
||||
destination_offset=destination_offset,
|
||||
destination_shape=tuple(destination.shape),
|
||||
destination_stride=tuple(destination.stride()),
|
||||
is_persistent=not destination.is_meta,
|
||||
)
|
||||
)
|
||||
# Loaders use copy_ for its side effect; the trace must never mutate
|
||||
# live kernel storage or attempt a meta-to-device copy.
|
||||
return destination
|
||||
|
||||
@classmethod
|
||||
def __torch_function__(cls, func, types, args=(), kwargs=None):
|
||||
kwargs = kwargs or {}
|
||||
if func is torch.Tensor.copy_:
|
||||
destination = args[0]
|
||||
source = args[1] if len(args) > 1 else kwargs.get("src")
|
||||
if isinstance(source, cls):
|
||||
return source._record_copy(destination)
|
||||
|
||||
op_name = SUPPORTED_OPS.get(func)
|
||||
if op_name is not None and args and isinstance(args[0], cls):
|
||||
return cls._intercept(args[0], func, op_name, tuple(args[1:]), kwargs)
|
||||
|
||||
with torch._C.DisableTorchFunctionSubclass():
|
||||
return func(*args, **kwargs)
|
||||
|
||||
@classmethod
|
||||
def _intercept(
|
||||
cls,
|
||||
source: "LazyWeight",
|
||||
func: Callable,
|
||||
op_name: str,
|
||||
args: tuple[Any, ...],
|
||||
kwargs: dict[str, Any],
|
||||
):
|
||||
meta = source._meta()
|
||||
with torch._C.DisableTorchFunctionSubclass():
|
||||
result = func(meta, *args, **kwargs)
|
||||
operation = TensorOperation(name=op_name, args=args, kwargs=dict(kwargs))
|
||||
if isinstance(result, torch.Tensor):
|
||||
if result.dtype not in _SUPPORTED_DTYPES:
|
||||
raise UnsupportedOpError(
|
||||
f"NIXL lazy replay only supports BF16/FP32 values, got {result.dtype} "
|
||||
f"after {op_name!r} on {source._source_name!r}"
|
||||
)
|
||||
return source._child(operation)
|
||||
if isinstance(result, (tuple, list)) and all(
|
||||
isinstance(item, torch.Tensor) and item.dtype in _SUPPORTED_DTYPES for item in result
|
||||
):
|
||||
return tuple(
|
||||
source._child(
|
||||
operation,
|
||||
TensorOperation(name="tuple_getitem", args=(index,)),
|
||||
)
|
||||
for index, _ in enumerate(result)
|
||||
)
|
||||
raise UnsupportedOpError(f"operation {op_name!r} returned unsupported {type(result).__name__}")
|
||||
|
||||
@classmethod
|
||||
def __torch_dispatch__(cls, func, types, args=(), kwargs=None):
|
||||
kwargs = kwargs or {}
|
||||
for value in (*args, *kwargs.values()):
|
||||
if isinstance(value, cls):
|
||||
raise UnsupportedOpError(
|
||||
f"unsupported operation {func} on {value._source_name!r}, recorded chain={value._ops!r}"
|
||||
)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
|
||||
def make_hf_lazy_weights(
|
||||
table: TrainerTensorTable,
|
||||
*,
|
||||
device: torch.device,
|
||||
recorder: WeightLoadRecorder,
|
||||
hf_config,
|
||||
) -> list[tuple[str, LazyWeight]]:
|
||||
"""Create HF-named graph values rooted in trainer wire tensors.
|
||||
|
||||
The returned values retain their trainer root name and accumulated view
|
||||
chain. Passing them to ``vLLM.model.load_weights`` composes the second half
|
||||
of the graph without any handwritten vLLM kernel conversion.
|
||||
"""
|
||||
state: dict[str, LazyWeight] = {
|
||||
tensor.name: LazyWeight(
|
||||
tensor.name,
|
||||
torch.Size(tensor.shape),
|
||||
getattr(torch, tensor.wire_dtype),
|
||||
device,
|
||||
recorder,
|
||||
)
|
||||
for group in table.groups
|
||||
for tensor in group.tensors
|
||||
}
|
||||
|
||||
# TODO(matej): Figure out how to avoid depending on trainer code here.
|
||||
from prime_rl.trainer.models import get_custom_causal_lm_cls
|
||||
from prime_rl.trainer.models.conversion_ops import apply_prime_to_hf
|
||||
|
||||
model_cls = get_custom_causal_lm_cls(hf_config)
|
||||
apply_prime_to_hf(state, model_cls.conversion_chain(hf_config))
|
||||
|
||||
# AutoWeightsLoader groups adjacent names by module prefix. Stable sorting
|
||||
# matches normal checkpoint iterators and keeps every expert group intact.
|
||||
return sorted(state.items(), key=lambda item: item[0])
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Role-scoped synchronization over ModelExpress.
|
||||
|
||||
The policy session coordinates a complete weight update with the orchestrator.
|
||||
A separate layer session uses the same READY/INITIALIZING handshake to keep a
|
||||
bounded transfer arena live until every inference worker has acknowledged it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Literal
|
||||
|
||||
import grpc
|
||||
from modelexpress import p2p_pb2
|
||||
from modelexpress.client import MxClient
|
||||
|
||||
Role = Literal["trainer", "inference", "orchestrator"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class ModelExpressSession:
|
||||
client: MxClient
|
||||
role: Role
|
||||
rank: int
|
||||
session_id: str
|
||||
worker_id: str
|
||||
_source_id: str | None = field(init=False, default=None, repr=False)
|
||||
|
||||
@property
|
||||
def source_id(self) -> str:
|
||||
if self._source_id is None:
|
||||
raise RuntimeError("ModelExpress metadata must be published before updating status")
|
||||
return self._source_id
|
||||
|
||||
def identity(self, role: Role) -> p2p_pb2.SourceIdentity:
|
||||
return p2p_pb2.SourceIdentity(
|
||||
mx_version="0.3.0",
|
||||
mx_source_type=p2p_pb2.MX_SOURCE_TYPE_WEIGHTS,
|
||||
model_name="prime-rl-weights",
|
||||
extra_parameters={"role": role, "session_id": self.session_id},
|
||||
)
|
||||
|
||||
def _rpc(self, call: Callable[[], Any]) -> Any:
|
||||
"""Retry transient ModelExpress startup and transport failures."""
|
||||
deadline = time.monotonic() + 120.0
|
||||
while True:
|
||||
try:
|
||||
return call()
|
||||
except grpc.RpcError as exc:
|
||||
if (
|
||||
exc.code()
|
||||
not in (
|
||||
grpc.StatusCode.UNAVAILABLE,
|
||||
grpc.StatusCode.DEADLINE_EXCEEDED,
|
||||
)
|
||||
or time.monotonic() >= deadline
|
||||
):
|
||||
raise
|
||||
time.sleep(min(0.5, max(0.0, deadline - time.monotonic())))
|
||||
|
||||
def publish(self, *, nixl_metadata: bytes = b"") -> str:
|
||||
worker = p2p_pb2.WorkerMetadata(
|
||||
worker_rank=self.rank,
|
||||
nixl_metadata=nixl_metadata,
|
||||
)
|
||||
self._source_id = self._rpc(
|
||||
lambda: self.client.publish_metadata(self.identity(self.role), worker, self.worker_id)
|
||||
)
|
||||
return self._source_id
|
||||
|
||||
def set_status(self, status: int) -> None:
|
||||
if not self._rpc(lambda: self.client.update_status(self.source_id, self.worker_id, self.rank, status)):
|
||||
raise RuntimeError(f"failed to set ModelExpress status {status} for {self.role} rank {self.rank}")
|
||||
|
||||
def list_sources(self, role: Role, status: int | None) -> list[p2p_pb2.SourceInstanceRef]:
|
||||
response = self._rpc(lambda: self.client.list_sources(self.identity(role), status_filter=status))
|
||||
return list(response.instances)
|
||||
|
||||
def exists_role_with_status(self, role: Role, status: int) -> bool:
|
||||
return bool(self.list_sources(role, status))
|
||||
|
||||
def wait_for(
|
||||
self,
|
||||
role: Role,
|
||||
*,
|
||||
count: int,
|
||||
status: int | None,
|
||||
timeout: float,
|
||||
poll_interval: float = 0.05,
|
||||
cancelled: Callable[[], bool] | None = None,
|
||||
) -> list[p2p_pb2.SourceInstanceRef]:
|
||||
deadline = time.monotonic() + timeout
|
||||
expected_ranks = set(range(count))
|
||||
while True:
|
||||
if cancelled is not None and cancelled():
|
||||
raise RuntimeError(f"cancelled waiting for {count} {role} worker(s) in session {self.session_id!r}")
|
||||
refs = self.list_sources(role, status)
|
||||
by_rank = {ref.worker_rank: ref for ref in refs}
|
||||
if expected_ranks.issubset(by_rank):
|
||||
return [by_rank[rank] for rank in range(count)]
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError(
|
||||
f"timed out waiting for {count} {role} worker(s) in session {self.session_id!r} "
|
||||
f"with status={status}; found ranks={sorted(by_rank)}"
|
||||
)
|
||||
time.sleep(poll_interval)
|
||||
|
||||
def fetch(self, ref: p2p_pb2.SourceInstanceRef) -> p2p_pb2.WorkerMetadata:
|
||||
response = self._rpc(lambda: self.client.get_metadata(ref.mx_source_id, ref.worker_id))
|
||||
if not response.found:
|
||||
raise LookupError(f"ModelExpress worker {ref.worker_id!r} disappeared")
|
||||
return response.worker
|
||||
@@ -0,0 +1,470 @@
|
||||
"""Serve FP32 FSDP master shards through reusable typed NIXL arenas."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from math import prod
|
||||
from pathlib import Path
|
||||
from typing import cast
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.nn as nn
|
||||
from modelexpress import p2p_pb2
|
||||
from modelexpress.client import MxClient
|
||||
from torch.distributed.tensor import DTensor
|
||||
from torch.distributed.tensor._utils import compute_local_shape_and_global_offset
|
||||
|
||||
from prime_rl.configs.trainer import NIXLWeightBroadcastConfig
|
||||
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
from prime_rl.trainer.rl.broadcast.base import WeightBroadcast
|
||||
from prime_rl.trainer.rl.broadcast.nixl.agent import NixlAgent, make_agent_name, set_ucx_env_defaults
|
||||
from prime_rl.trainer.rl.broadcast.nixl.cuda_malloc_memory import (
|
||||
size_cuda_buffers,
|
||||
use_cuda_malloc_pool,
|
||||
)
|
||||
from prime_rl.trainer.rl.broadcast.nixl.model_express import ModelExpressSession
|
||||
from prime_rl.trainer.rl.broadcast.nixl.trainer_tensor_table import (
|
||||
TrainerAgent,
|
||||
TrainerGroup,
|
||||
TrainerShard,
|
||||
TrainerTensor,
|
||||
TrainerTensorTable,
|
||||
)
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
from prime_rl.trainer.utils import get_world
|
||||
|
||||
LAYER_RE = re.compile(r"(?:^|\.)layers\.(\d+)(?=\.|$)")
|
||||
BUFFER_POLL_INTERVAL = 0.01
|
||||
MAX_STAGING_BUFFER_COUNT = 8
|
||||
|
||||
|
||||
@dataclass
|
||||
class StagedTensorShard:
|
||||
name: str
|
||||
global_shape: tuple[int, ...]
|
||||
group_index: int
|
||||
tensor_offset: int
|
||||
source_tensor: torch.Tensor
|
||||
wire_dtype: torch.dtype
|
||||
staging_tensor: torch.Tensor | None = None
|
||||
|
||||
def assign_staging_tensor(self, arena: torch.Tensor, arena_offset: int) -> None:
|
||||
self.staging_tensor = arena.narrow(0, arena_offset, self.source_tensor.numel()).view(self.source_tensor.shape)
|
||||
|
||||
def copy_to_staging(self) -> None:
|
||||
assert self.staging_tensor is not None
|
||||
self.staging_tensor.copy_(self.source_tensor)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransferGroupIndex:
|
||||
group_names: list[str]
|
||||
layer_to_group: dict[int, int]
|
||||
|
||||
|
||||
class NIXLWeightBroadcast(WeightBroadcast):
|
||||
def __init__(self, output_dir: Path, config: NIXLWeightBroadcastConfig, parallel_dims: ParallelDims) -> None:
|
||||
super().__init__(output_dir)
|
||||
self.config = config
|
||||
self.parallel_dims = parallel_dims
|
||||
self.world = get_world()
|
||||
self.multi_run_manager = get_multi_run_manager()
|
||||
if self.is_serving_rank:
|
||||
set_ucx_env_defaults()
|
||||
self.nixl_agent = NixlAgent(make_agent_name("trainer", self.world.rank))
|
||||
self.initialized = False
|
||||
self.transfer_group_names: list[str] = []
|
||||
self.staged_shards: list[StagedTensorShard] = []
|
||||
self.staged_shards_by_group: dict[int, list[StagedTensorShard]] = {}
|
||||
self.staging_arenas: dict[torch.dtype, torch.Tensor] = {}
|
||||
self.staging_buffer_count: int
|
||||
|
||||
@property
|
||||
def is_serving_rank(self) -> bool:
|
||||
if self.parallel_dims.dp_replicate_enabled:
|
||||
return self.parallel_dims.get_mesh("dp_replicate").get_local_rank() == 0
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def build_transfer_group_index(state_dict: dict[str, torch.Tensor]) -> TransferGroupIndex:
|
||||
layer_numbers = sorted(
|
||||
{
|
||||
int(match.group(1))
|
||||
for name, value in state_dict.items()
|
||||
if value.is_floating_point() and (match := LAYER_RE.search(name)) is not None
|
||||
}
|
||||
)
|
||||
return TransferGroupIndex(
|
||||
group_names=["non_layer", *(f"layer.{layer}" for layer in layer_numbers)],
|
||||
layer_to_group={layer: group for group, layer in enumerate(layer_numbers, start=1)},
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def find_transfer_group_index(tensor_name: str, transfer_groups: TransferGroupIndex) -> int:
|
||||
match = LAYER_RE.search(tensor_name)
|
||||
return 0 if match is None else transfer_groups.layer_to_group[int(match.group(1))]
|
||||
|
||||
def collect_local_tensor_shards(
|
||||
self,
|
||||
state_dict: dict[str, torch.Tensor],
|
||||
transfer_groups: TransferGroupIndex,
|
||||
keep_in_fp32: Callable[[str], bool],
|
||||
) -> list[StagedTensorShard]:
|
||||
local_shards: list[StagedTensorShard] = []
|
||||
for name, value in state_dict.items():
|
||||
# Non-floating state is not part of model weight transfer.
|
||||
if not value.is_floating_point():
|
||||
continue
|
||||
full_shape = tuple(value.shape)
|
||||
group_index = self.find_transfer_group_index(name, transfer_groups)
|
||||
wire_dtype = torch.float32 if keep_in_fp32(name) else torch.bfloat16
|
||||
|
||||
# Unsharded tensors are identical on every rank, so rank 0 serves the only copy.
|
||||
if not isinstance(value, DTensor):
|
||||
if self.world.is_master:
|
||||
local_shards.append(
|
||||
StagedTensorShard(
|
||||
name=name,
|
||||
global_shape=full_shape,
|
||||
group_index=group_index,
|
||||
tensor_offset=0,
|
||||
source_tensor=value.detach(),
|
||||
wire_dtype=wire_dtype,
|
||||
)
|
||||
)
|
||||
continue
|
||||
|
||||
placements = value.placements
|
||||
local_shape, global_offset = compute_local_shape_and_global_offset(
|
||||
value.shape, value.device_mesh, placements
|
||||
)
|
||||
local = value.to_local().detach()
|
||||
if tuple(local.shape) != tuple(local_shape):
|
||||
local = local[tuple(slice(size) for size in local_shape)]
|
||||
|
||||
# Replicated DTensors are identical on every rank, so rank 0 serves the only copy.
|
||||
if all(placement.is_replicate() for placement in placements):
|
||||
if self.world.is_master:
|
||||
local_shards.append(
|
||||
StagedTensorShard(
|
||||
name=name,
|
||||
global_shape=full_shape,
|
||||
group_index=group_index,
|
||||
tensor_offset=0,
|
||||
source_tensor=local,
|
||||
wire_dtype=wire_dtype,
|
||||
)
|
||||
)
|
||||
continue
|
||||
|
||||
# FSDP DTensors contribute this rank's contiguous shard along tensor dimension 0.
|
||||
if local.numel():
|
||||
row_numel = prod(full_shape[1:]) if full_shape else 1
|
||||
offset = global_offset[0] * row_numel if full_shape else 0
|
||||
local_shards.append(
|
||||
StagedTensorShard(
|
||||
name=name,
|
||||
global_shape=full_shape,
|
||||
group_index=group_index,
|
||||
tensor_offset=offset,
|
||||
source_tensor=local,
|
||||
wire_dtype=wire_dtype,
|
||||
)
|
||||
)
|
||||
return local_shards
|
||||
|
||||
def choose_staging_buffer_count(self, largest_group_bytes: int) -> int:
|
||||
local_buffer_count = min(len(self.transfer_group_names), MAX_STAGING_BUFFER_COUNT)
|
||||
if self.is_serving_rank and largest_group_bytes:
|
||||
device = self.staged_shards[0].source_tensor.device
|
||||
allocated_bytes = torch.cuda.memory_allocated()
|
||||
peak_growth_bytes = max(0, torch.cuda.max_memory_allocated() - allocated_bytes)
|
||||
free_bytes, _ = torch.cuda.mem_get_info(device)
|
||||
max_buffers = local_buffer_count if peak_growth_bytes else 1
|
||||
if peak_growth_bytes or free_bytes < largest_group_bytes:
|
||||
torch.cuda.empty_cache()
|
||||
local_buffer_count = size_cuda_buffers(
|
||||
largest_group_bytes,
|
||||
max_buffers,
|
||||
device,
|
||||
extra_headroom_bytes=peak_growth_bytes,
|
||||
)
|
||||
|
||||
staging_buffer_count = torch.tensor(
|
||||
local_buffer_count,
|
||||
dtype=torch.int64,
|
||||
device=torch.device("cuda", torch.cuda.current_device()),
|
||||
)
|
||||
dist.all_reduce(staging_buffer_count, op=dist.ReduceOp.MIN)
|
||||
return int(staging_buffer_count.item())
|
||||
|
||||
def allocate_staging_arenas(self, largest_group_elements: dict[torch.dtype, int]) -> None:
|
||||
if not self.is_serving_rank or not any(largest_group_elements.values()):
|
||||
return
|
||||
|
||||
device = self.staged_shards[0].source_tensor.device
|
||||
with use_cuda_malloc_pool():
|
||||
self.staging_arenas = {
|
||||
dtype: torch.empty(
|
||||
self.staging_buffer_count * elements,
|
||||
dtype=dtype,
|
||||
device=device,
|
||||
)
|
||||
for dtype, elements in largest_group_elements.items()
|
||||
if elements
|
||||
}
|
||||
|
||||
offsets = {
|
||||
dtype: [
|
||||
(group % self.staging_buffer_count) * largest_group_elements[dtype]
|
||||
for group in range(len(self.transfer_group_names))
|
||||
]
|
||||
for dtype in self.staging_arenas
|
||||
}
|
||||
for shard in self.staged_shards:
|
||||
group_offsets = offsets[shard.wire_dtype]
|
||||
shard.assign_staging_tensor(
|
||||
self.staging_arenas[shard.wire_dtype],
|
||||
group_offsets[shard.group_index],
|
||||
)
|
||||
group_offsets[shard.group_index] += shard.source_tensor.numel()
|
||||
|
||||
for arena in self.staging_arenas.values():
|
||||
self.nixl_agent.register_tensor(arena)
|
||||
|
||||
def prepare_staging_buffers(self) -> None:
|
||||
group_elements = {dtype: [0] * len(self.transfer_group_names) for dtype in (torch.bfloat16, torch.float32)}
|
||||
for shard in self.staged_shards:
|
||||
group_elements[shard.wire_dtype][shard.group_index] += shard.source_tensor.numel()
|
||||
largest_group_elements = {dtype: max(elements, default=0) for dtype, elements in group_elements.items()}
|
||||
largest_group_bytes = sum(elements * dtype.itemsize for dtype, elements in largest_group_elements.items())
|
||||
self.staging_buffer_count = self.choose_staging_buffer_count(largest_group_bytes)
|
||||
self.allocate_staging_arenas(largest_group_elements)
|
||||
|
||||
grouped: dict[int, list[StagedTensorShard]] = defaultdict(list)
|
||||
for shard in self.staged_shards:
|
||||
grouped[shard.group_index].append(shard)
|
||||
self.staged_shards_by_group = dict(grouped)
|
||||
|
||||
def build_local_trainer_table_fragment(self) -> TrainerTensorTable:
|
||||
tensors_by_group: list[dict[str, TrainerTensor]] = [{} for _ in self.transfer_group_names]
|
||||
for shard in self.staged_shards:
|
||||
tensors = tensors_by_group[shard.group_index]
|
||||
tensor = tensors.setdefault(
|
||||
shard.name,
|
||||
TrainerTensor(
|
||||
name=shard.name,
|
||||
wire_dtype=str(shard.wire_dtype).removeprefix("torch."),
|
||||
shape=shard.global_shape,
|
||||
shards=[],
|
||||
),
|
||||
)
|
||||
tensor.shards.append(
|
||||
TrainerShard(
|
||||
agent=0,
|
||||
offset=shard.tensor_offset,
|
||||
numel=shard.source_tensor.numel(),
|
||||
addr=cast(torch.Tensor, shard.staging_tensor).data_ptr(),
|
||||
)
|
||||
)
|
||||
|
||||
return TrainerTensorTable(
|
||||
agents=[
|
||||
TrainerAgent(
|
||||
name=self.nixl_agent.name,
|
||||
metadata=self.nixl_agent.get_metadata(),
|
||||
device_id=torch.cuda.current_device(),
|
||||
)
|
||||
],
|
||||
staging_buffer_count=self.staging_buffer_count,
|
||||
groups=[
|
||||
TrainerGroup(name=group_name, tensors=list(tensors.values()))
|
||||
for group_name, tensors in zip(self.transfer_group_names, tensors_by_group)
|
||||
],
|
||||
)
|
||||
|
||||
def gather_trainer_table_fragments(self) -> list[bytes] | None:
|
||||
table_fragment = self.build_local_trainer_table_fragment().encode() if self.is_serving_rank else None
|
||||
gathered: list[bytes | None] | None = [None] * self.world.world_size if self.world.is_master else None
|
||||
dist.gather_object(table_fragment, gathered, dst=0)
|
||||
if gathered is None:
|
||||
return None
|
||||
return [fragment for fragment in gathered if fragment is not None]
|
||||
|
||||
def merge_trainer_table_fragments(self, table_fragments: list[bytes]) -> TrainerTensorTable:
|
||||
agents: list[TrainerAgent] = []
|
||||
tensors_by_group: list[dict[str, TrainerTensor]] = [{} for _ in self.transfer_group_names]
|
||||
for agent_index, encoded_fragment in enumerate(table_fragments):
|
||||
fragment = TrainerTensorTable.decode(encoded_fragment)
|
||||
agents.append(fragment.agents[0])
|
||||
for group_index, group in enumerate(fragment.groups):
|
||||
tensors = tensors_by_group[group_index]
|
||||
for fragment_tensor in group.tensors:
|
||||
tensor = tensors.setdefault(
|
||||
fragment_tensor.name,
|
||||
TrainerTensor(
|
||||
name=fragment_tensor.name,
|
||||
wire_dtype=fragment_tensor.wire_dtype,
|
||||
shape=fragment_tensor.shape,
|
||||
shards=[],
|
||||
),
|
||||
)
|
||||
tensor.shards.extend(
|
||||
TrainerShard(
|
||||
agent=agent_index,
|
||||
offset=shard.offset,
|
||||
numel=shard.numel,
|
||||
addr=shard.addr,
|
||||
)
|
||||
for shard in fragment_tensor.shards
|
||||
)
|
||||
|
||||
for tensors in tensors_by_group:
|
||||
for tensor in tensors.values():
|
||||
tensor.shards.sort(key=lambda shard: shard.offset)
|
||||
|
||||
return TrainerTensorTable(
|
||||
agents=agents,
|
||||
staging_buffer_count=self.staging_buffer_count,
|
||||
groups=[
|
||||
TrainerGroup(name=group_name, tensors=list(tensors.values()))
|
||||
for group_name, tensors in zip(self.transfer_group_names, tensors_by_group)
|
||||
],
|
||||
)
|
||||
|
||||
def initialize_transfer(self, model: nn.Module) -> None:
|
||||
if self.initialized:
|
||||
return
|
||||
model = cast(PreTrainedModelPrimeRL, model)
|
||||
state_dict = model.state_dict()
|
||||
transfer_groups = self.build_transfer_group_index(state_dict)
|
||||
self.transfer_group_names = transfer_groups.group_names
|
||||
if self.is_serving_rank:
|
||||
self.staged_shards = self.collect_local_tensor_shards(
|
||||
state_dict,
|
||||
transfer_groups,
|
||||
model.keep_in_fp32_for_weight_transfer,
|
||||
)
|
||||
self.prepare_staging_buffers()
|
||||
table_fragments = self.gather_trainer_table_fragments()
|
||||
|
||||
if table_fragments is not None:
|
||||
table = self.merge_trainer_table_fragments(table_fragments)
|
||||
server_url = f"{self.config.host}:{self.config.port}"
|
||||
client = MxClient(server_url=server_url)
|
||||
self.buffer_sessions = []
|
||||
for buffer_index in range(self.staging_buffer_count):
|
||||
session = ModelExpressSession(
|
||||
client=client,
|
||||
role="trainer",
|
||||
rank=0,
|
||||
session_id=f"{self.config.session_id}:layers:{buffer_index}",
|
||||
worker_id=f"trainer-buffer-{buffer_index}",
|
||||
)
|
||||
session.publish()
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
self.buffer_sessions.append(session)
|
||||
self.model_express = ModelExpressSession(
|
||||
client=client,
|
||||
role="trainer",
|
||||
rank=0,
|
||||
session_id=self.config.session_id,
|
||||
worker_id="trainer-table",
|
||||
)
|
||||
self.model_express.publish(nixl_metadata=table.encode())
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
tensor_count = sum(len(group.tensors) for group in table.groups)
|
||||
self.logger.info(
|
||||
f"Published {tensor_count} trainer tensors in {len(table.groups)} groups "
|
||||
f"from {len(table.agents)} agents with {self.staging_buffer_count} staging buffers"
|
||||
)
|
||||
self.initialized = True
|
||||
|
||||
def finish_staging_buffer_transfer(self, buffer_index: int) -> None:
|
||||
if self.world.is_master:
|
||||
session = self.buffer_sessions[buffer_index]
|
||||
session.wait_for(
|
||||
"inference",
|
||||
count=self.config.inference_world_size,
|
||||
status=p2p_pb2.SOURCE_STATUS_READY,
|
||||
timeout=self.config.timeout,
|
||||
poll_interval=BUFFER_POLL_INTERVAL,
|
||||
)
|
||||
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
session.wait_for(
|
||||
"inference",
|
||||
count=self.config.inference_world_size,
|
||||
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
|
||||
timeout=self.config.timeout,
|
||||
poll_interval=BUFFER_POLL_INTERVAL,
|
||||
)
|
||||
dist.barrier()
|
||||
|
||||
@torch.no_grad()
|
||||
def broadcast_weights(self, model: nn.Module, step: int) -> None:
|
||||
ready_runs = list(self.multi_run_manager.ready_to_update_idxs)
|
||||
self.initialize_transfer(model)
|
||||
start = time.perf_counter()
|
||||
|
||||
if self.world.is_master:
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_READY)
|
||||
self.model_express.wait_for(
|
||||
"orchestrator",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_READY,
|
||||
timeout=self.config.timeout,
|
||||
)
|
||||
self.model_express.wait_for(
|
||||
"inference",
|
||||
count=self.config.inference_world_size,
|
||||
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
|
||||
timeout=self.config.timeout,
|
||||
)
|
||||
|
||||
for group, group_name in enumerate(self.transfer_group_names):
|
||||
group_start = time.perf_counter()
|
||||
buffer_index = group % self.staging_buffer_count
|
||||
if group >= self.staging_buffer_count:
|
||||
self.finish_staging_buffer_transfer(buffer_index)
|
||||
|
||||
if self.is_serving_rank:
|
||||
for shard in self.staged_shards_by_group.get(group, ()):
|
||||
shard.copy_to_staging()
|
||||
torch.cuda.synchronize()
|
||||
dist.barrier()
|
||||
if self.world.is_master:
|
||||
self.buffer_sessions[buffer_index].set_status(p2p_pb2.SOURCE_STATUS_READY)
|
||||
self.logger.debug(
|
||||
f"NIXL+ModelExpress policy v{step} group {group_name} staged in buffer {buffer_index} in "
|
||||
f"{time.perf_counter() - group_start:.2f}s"
|
||||
)
|
||||
|
||||
first_pending_group = max(0, len(self.transfer_group_names) - self.staging_buffer_count)
|
||||
for group in range(first_pending_group, len(self.transfer_group_names)):
|
||||
buffer_index = group % self.staging_buffer_count
|
||||
self.finish_staging_buffer_transfer(buffer_index)
|
||||
|
||||
if self.world.is_master:
|
||||
self.model_express.wait_for(
|
||||
"inference",
|
||||
count=self.config.inference_world_size,
|
||||
status=p2p_pb2.SOURCE_STATUS_READY,
|
||||
timeout=self.config.timeout,
|
||||
)
|
||||
self.model_express.wait_for(
|
||||
"orchestrator",
|
||||
count=1,
|
||||
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
|
||||
timeout=self.config.timeout,
|
||||
)
|
||||
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
dist.barrier()
|
||||
for run_index in ready_runs:
|
||||
self.multi_run_manager.ready_to_update[run_index] = False
|
||||
self.logger.info(f"NIXL+ModelExpress policy v{step} synchronized in {time.perf_counter() - start:.2f}s")
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Route tensor replay sources onto sharded trainer memory."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.rl.broadcast.nixl.graph import TensorReplayPlan
|
||||
from prime_rl.trainer.rl.broadcast.nixl.trainer_tensor_table import TrainerTensor
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TensorRoute:
|
||||
agent: int
|
||||
source_addr: int
|
||||
destination_addr: int
|
||||
nbytes: int
|
||||
|
||||
|
||||
def route_sharded_tensor(
|
||||
plan: TensorReplayPlan,
|
||||
source: TrainerTensor,
|
||||
destination: torch.Tensor,
|
||||
) -> list[TensorRoute]:
|
||||
"""Route a strided trainer view into a contiguous destination tensor."""
|
||||
numel = 1
|
||||
for size in plan.source_shape:
|
||||
numel *= size
|
||||
if numel == 0:
|
||||
return []
|
||||
|
||||
dims = [(size, step) for size, step in zip(plan.source_shape, plan.source_stride) if size != 1]
|
||||
if any(step < 0 for _, step in dims):
|
||||
raise NotImplementedError("negative strides are not supported")
|
||||
|
||||
run_elements = 1
|
||||
split_at = len(dims)
|
||||
while split_at and dims[split_at - 1][1] == run_elements:
|
||||
run_elements *= dims[split_at - 1][0]
|
||||
split_at -= 1
|
||||
outer_dims = dims[:split_at]
|
||||
|
||||
routes: list[TensorRoute] = []
|
||||
itemsize = destination.element_size()
|
||||
destination_addr = destination.data_ptr()
|
||||
destination_offset = 0
|
||||
|
||||
def route_run(element_offset: int, element_count: int) -> None:
|
||||
nonlocal destination_offset
|
||||
position = element_offset
|
||||
remaining = element_count
|
||||
while remaining:
|
||||
shard = next(
|
||||
(shard for shard in source.shards if shard.offset <= position < shard.offset + shard.numel),
|
||||
None,
|
||||
)
|
||||
if shard is None:
|
||||
raise RuntimeError(f"no trainer shard owns element {position}")
|
||||
take = min(remaining, shard.offset + shard.numel - position)
|
||||
nbytes = take * itemsize
|
||||
routes.append(
|
||||
TensorRoute(
|
||||
agent=shard.agent,
|
||||
source_addr=shard.addr + (position - shard.offset) * itemsize,
|
||||
destination_addr=destination_addr + destination_offset,
|
||||
nbytes=nbytes,
|
||||
)
|
||||
)
|
||||
position += take
|
||||
remaining -= take
|
||||
destination_offset += nbytes
|
||||
|
||||
def route_dimension(dim: int, element_offset: int) -> None:
|
||||
if dim == len(outer_dims):
|
||||
route_run(element_offset, run_elements)
|
||||
return
|
||||
size, step = outer_dims[dim]
|
||||
for index in range(size):
|
||||
route_dimension(dim + 1, element_offset + index * step)
|
||||
|
||||
route_dimension(0, plan.source_offset)
|
||||
return routes
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Trainer tensor metadata published for one-sided NIXL weight pulls."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import msgspec
|
||||
|
||||
|
||||
class TrainerAgent(msgspec.Struct, frozen=True):
|
||||
"""One trainer rank's NIXL agent."""
|
||||
|
||||
name: str
|
||||
metadata: bytes
|
||||
device_id: int
|
||||
|
||||
|
||||
class TrainerShard(msgspec.Struct, frozen=True):
|
||||
"""One contiguous flat range of a logical trainer tensor.
|
||||
|
||||
``offset`` and ``numel`` describe the logical element range. ``addr`` is
|
||||
the remote address of its first wire-dtype element.
|
||||
"""
|
||||
|
||||
agent: int
|
||||
offset: int
|
||||
numel: int
|
||||
addr: int
|
||||
|
||||
|
||||
class TrainerTensor(msgspec.Struct):
|
||||
"""One trainer-format tensor served as typed wire shards.
|
||||
|
||||
``wire_dtype`` is BF16 by default and may be FP32 for model-declared
|
||||
precision-sensitive tensors. Shard addresses may overlap with addresses
|
||||
used by tensors in other transfer groups.
|
||||
"""
|
||||
|
||||
name: str
|
||||
wire_dtype: str
|
||||
shape: tuple[int, ...]
|
||||
shards: list[TrainerShard]
|
||||
|
||||
|
||||
class TrainerGroup(msgspec.Struct):
|
||||
"""One independently staged and acknowledged transfer unit."""
|
||||
|
||||
name: str
|
||||
tensors: list[TrainerTensor]
|
||||
|
||||
|
||||
class TrainerTensorTable(msgspec.Struct):
|
||||
agents: list[TrainerAgent]
|
||||
staging_buffer_count: int
|
||||
groups: list[TrainerGroup]
|
||||
|
||||
def encode(self) -> bytes:
|
||||
return msgspec.msgpack.encode(self)
|
||||
|
||||
@classmethod
|
||||
def decode(cls, data: bytes) -> TrainerTensorTable:
|
||||
return msgspec.msgpack.decode(data, type=cls)
|
||||
@@ -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
|
||||
@@ -186,7 +188,12 @@ def train(config: TrainerConfig):
|
||||
logger.info("Skipping weight broadcast setup (fake data mode)")
|
||||
else:
|
||||
logger.info(f"Initializing weight broadcast ({config.weight_broadcast})")
|
||||
weight_broadcast = setup_weight_broadcast(config.output_dir, config.weight_broadcast, config.model.lora)
|
||||
weight_broadcast = setup_weight_broadcast(
|
||||
config.output_dir,
|
||||
config.weight_broadcast,
|
||||
parallel_dims,
|
||||
config.model.lora,
|
||||
)
|
||||
|
||||
if parallel_dims.cp_enabled:
|
||||
cp_group = parallel_dims.world_mesh["cp"].get_group()
|
||||
@@ -264,13 +271,13 @@ def train(config: TrainerConfig):
|
||||
logger.debug(f"Starting training step {progress.step}")
|
||||
step_start_time = time.perf_counter()
|
||||
|
||||
# With NCCL, broadcast the incoming policy (v{progress.step-1}) before waiting for its
|
||||
# rollouts: #2896 broadcasts at the END of a step, so the first step would otherwise block
|
||||
# on rollouts the paused inference engines cannot produce until they receive
|
||||
# v{progress.step-1}. Filesystem broadcast needs no startup rendezvous (fresh: base model
|
||||
# = v0; resume: the orchestrator reads its checkpoint dir), and a one-shot startup
|
||||
# broadcast would miss multi-run runs registered after the first step.
|
||||
if progress.step == start_step and weight_broadcast is not None and config.weight_broadcast.type == "nccl":
|
||||
# In-memory transfers broadcast the incoming policy (v{progress.step-1}) before waiting
|
||||
# for its rollouts so the trainer and inference pool join the same update lifecycle.
|
||||
if (
|
||||
progress.step == start_step
|
||||
and weight_broadcast is not None
|
||||
and config.weight_broadcast.type in ("nccl", "nixl")
|
||||
):
|
||||
logger.info(f"Broadcasting startup policy weights (v{progress.step - 1}) to inference engines")
|
||||
multi_run_manager.wait_for_run(0)
|
||||
for idx in multi_run_manager.used_idxs:
|
||||
@@ -577,19 +584,17 @@ def train(config: TrainerConfig):
|
||||
forward_backward_time = time.perf_counter() - forward_backward_start_time
|
||||
|
||||
# Broadcast the model just produced (policy v{progress.step}) so the orchestrator can
|
||||
# sample its next step from it. Skip the final NCCL broadcasts: with a 1-step async barrier
|
||||
# the orchestrator's last step uses the trainer's penultimate ckpt, so they have no receiver
|
||||
# (the inference NCCL group is torn down). Filesystem broadcast still writes them so we can
|
||||
# resume from the broadcast directory.
|
||||
# sample its next step from it. In-memory transports retain their two-step shutdown
|
||||
# window; filesystem broadcast still writes every version for resume.
|
||||
if weight_broadcast is None:
|
||||
broadcast_weights_time = 0
|
||||
else:
|
||||
nccl_broadcast_unused = (
|
||||
config.weight_broadcast.type == "nccl"
|
||||
broadcast_unused = (
|
||||
config.weight_broadcast.type in ("nccl", "nixl")
|
||||
and config.max_steps is not None
|
||||
and progress.step >= config.max_steps - 1
|
||||
)
|
||||
if not nccl_broadcast_unused:
|
||||
if not broadcast_unused:
|
||||
broadcast_weights_start_time = time.perf_counter()
|
||||
weight_broadcast.broadcast_weights(model, step=progress.step)
|
||||
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -568,6 +568,38 @@ async def init_nccl_broadcast(
|
||||
)
|
||||
|
||||
|
||||
async def init_nixl_broadcast(
|
||||
admin_clients: list[AsyncClient],
|
||||
host: str,
|
||||
port: int,
|
||||
timeout: int,
|
||||
inference_world_size: int,
|
||||
session_id: str,
|
||||
) -> None:
|
||||
"""Configure every vLLM worker for NIXL + ModelExpress pulls."""
|
||||
workers_per_server = inference_world_size // len(admin_clients)
|
||||
|
||||
async def initialize(admin_client: AsyncClient, rank_offset: int) -> None:
|
||||
await _admin_post(
|
||||
admin_client,
|
||||
"/init_broadcaster",
|
||||
timeout_s=max(ADMIN_TIMEOUT_S, timeout),
|
||||
json={
|
||||
"host": host,
|
||||
"port": port,
|
||||
"rank_offset": rank_offset,
|
||||
"inference_world_size": inference_world_size,
|
||||
"timeout": timeout,
|
||||
"quantize_in_weight_transfer": False,
|
||||
"session_id": session_id,
|
||||
},
|
||||
)
|
||||
|
||||
await asyncio.gather(
|
||||
*[initialize(admin_client, index * workers_per_server) for index, admin_client in enumerate(admin_clients)]
|
||||
)
|
||||
|
||||
|
||||
async def prefill_logprobs(openai: AsyncOpenAI, model: str, token_ids: list[int]) -> list[float]:
|
||||
"""Prefill-score ``token_ids`` under ``model`` via ``/inference/v1/generate``
|
||||
+ ``prompt_logprobs`` (the prime-rl server-side extension in
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -70,7 +70,7 @@ def get_model_pairs():
|
||||
with torch.no_grad():
|
||||
state_dict = hf_model.state_dict()
|
||||
prime_state_keys = prime_model.state_dict().keys()
|
||||
NemotronHForCausalLM.convert_to_prime(state_dict)
|
||||
prime_model.convert_to_prime(state_dict)
|
||||
prime_model.load_state_dict(state_dict)
|
||||
|
||||
inject_prime_lm_head(prime_model, chunk_size=None)
|
||||
@@ -130,7 +130,7 @@ def test_nemotron_h_reverse():
|
||||
|
||||
with torch.no_grad():
|
||||
sd = prime_model.state_dict()
|
||||
NemotronHForCausalLM.convert_to_hf(sd)
|
||||
prime_model.convert_to_hf(sd)
|
||||
# convert_to_hf produces checkpoint format with "backbone." prefix;
|
||||
# the HF model uses "model." prefix for its state dict
|
||||
keys_to_rename = [k for k in sd if k.startswith("backbone.")]
|
||||
@@ -211,9 +211,9 @@ def test_nemotron_h_weight_conversion_roundtrip():
|
||||
original_sd = {k: v.clone() for k, v in model.state_dict().items()}
|
||||
|
||||
sd = model.state_dict()
|
||||
NemotronHForCausalLM.convert_to_hf(sd)
|
||||
model.convert_to_hf(sd)
|
||||
assert NemotronHForCausalLM.is_hf_state_dict(sd)
|
||||
NemotronHForCausalLM.convert_to_prime(sd)
|
||||
model.convert_to_prime(sd)
|
||||
assert NemotronHForCausalLM.is_prime_state_dict(sd)
|
||||
|
||||
for key in original_sd:
|
||||
|
||||
@@ -79,15 +79,15 @@ def test_qwen3_5_moe_roundtrip():
|
||||
prime_sd = prime_model.state_dict()
|
||||
|
||||
# Convert PrimeRL → per-expert HF format
|
||||
converted_hf_sd = PrimeRLQwen3_5MoeForCausalLM.convert_to_hf(dict(prime_sd))
|
||||
converted_hf_sd = prime_model.convert_to_hf(dict(prime_sd))
|
||||
|
||||
# Also convert original HF (fused) to per-expert format for comparison
|
||||
|
||||
# First convert original HF → PrimeRL, then back to per-expert HF
|
||||
orig_prime_sd = dict(original_hf_sd)
|
||||
PrimeRLQwen3_5MoeForCausalLM.convert_to_prime(orig_prime_sd)
|
||||
prime_model.convert_to_prime(orig_prime_sd)
|
||||
orig_roundtripped = dict(orig_prime_sd)
|
||||
PrimeRLQwen3_5MoeForCausalLM.convert_to_hf(orig_roundtripped)
|
||||
prime_model.convert_to_hf(orig_roundtripped)
|
||||
|
||||
# All non-expert keys should match exactly, expert keys should match after roundtrip
|
||||
for key in orig_roundtripped:
|
||||
|
||||
@@ -169,6 +169,7 @@ def test_vlm_weight_roundtrip():
|
||||
config = _tiny_vlm_config()
|
||||
with torch.device("cuda"), default_dtype(torch.bfloat16):
|
||||
hf_model = HFQwen3_5MoeVLM._from_config(config)
|
||||
prime_model = Qwen3_5MoeForCausalLM(config)
|
||||
|
||||
hf_sd = hf_model.state_dict()
|
||||
original_vision_key = "model.visual.blocks.0.mlp.linear_fc1.weight"
|
||||
@@ -176,18 +177,18 @@ def test_vlm_weight_roundtrip():
|
||||
|
||||
# HF -> PrimeRL
|
||||
prime_sd = dict(hf_sd)
|
||||
Qwen3_5MoeForCausalLM.convert_to_prime(prime_sd)
|
||||
prime_model.convert_to_prime(prime_sd)
|
||||
assert any("language_model" in k and "mlp.experts.w1" in k for k in prime_sd)
|
||||
assert original_vision_key in prime_sd
|
||||
|
||||
# PrimeRL -> HF
|
||||
roundtripped = dict(prime_sd)
|
||||
Qwen3_5MoeForCausalLM.convert_to_hf(roundtripped)
|
||||
prime_model.convert_to_hf(roundtripped)
|
||||
|
||||
# Original HF also needs roundtrip for expert format normalization
|
||||
orig_rt = dict(hf_sd)
|
||||
Qwen3_5MoeForCausalLM.convert_to_prime(orig_rt)
|
||||
Qwen3_5MoeForCausalLM.convert_to_hf(orig_rt)
|
||||
prime_model.convert_to_prime(orig_rt)
|
||||
prime_model.convert_to_hf(orig_rt)
|
||||
|
||||
for key in orig_rt:
|
||||
assert key in roundtripped, f"Missing key: {key}"
|
||||
|
||||
Reference in New Issue
Block a user