Compare commits

...
Author SHA1 Message Date
S1ro1 390e2cef48 feat(weight-transfer): add generation-safe NIXL pull backend
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-15 16:18:15 -07:00
S1ro1 0bafbd7c28 feat(weight-transfer): compose model conversion with lazy pull plans 2026-07-15 16:07:36 -07:00
S1ro1andClaude Opus 4.8 662f1ee4b8 test(models): restore HF<->prime roundtrip tests on the new instance API
Brings back the per-model conversion roundtrip tests that predated the
declarative refactor (qwen3_5_moe, nemotron_h reverse + roundtrip, qwen3_5 VLM),
rewritten to call `convert_to_hf` / `convert_to_prime` on a model instance
(playing the declarative chain) instead of the removed classmethods. The
NemotronH reverse test keeps its pre-existing xfail (HF now uses fused expert
tensors). gpu-marked.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 16:00:50 -07:00
S1ro1andClaude Opus 4.8 2fddd88884 refactor(models): make the declarative conversion chain the only path
Each model defines `conversion_chain(config)` in its `converting_<model>.py`;
the `PreTrainedModelPrimeRL` base has a single set of `convert_to_hf` /
`convert_to_prime` / `convert_layer_*` implementations that play the chain
forward and backward. Because every op is present-guarded, the same chain
works over a full state dict, one layer's keys, or a local shard.

Removes the now-redundant scaffolding:
- per-model imperative `convert_hf_to_tt` / `convert_tt_to_hf` functions
- the standalone `conversion_chain.py` builders and the `conversion_chains` registry
- the mock equivalence tests (superseded by the 20-step math KL-mismatch
  validation in PR #2797) and the obsolete classmethod roundtrip tests

Net -2.2k lines. Validated end-to-end: qwen3_moe/qwen3_5_moe/nemotron_h/glm4_moe
mean KL mismatch < 0.0015 over 20 steps on math.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 16:00:29 -07:00
S1ro1andClaude Fable 5 a059509de4 refactor(models): collapse NemotronH layer-type branching into a uniform dispatch
A single per-layer Conditional detects layer type from a signature key (present
in either HF or prime form, so it works both directions) and dispatches:
attention/mamba keep bulk PrefixRename(mixer.->{self_attn,mamba}.), MoE uses its
specific ops (incl. the gated Synthetic w3). Drops the layers_block_type
argument — build_nemotron_h_chain(num_layers) now matches every other model's
signature. Equivalence to the imperative converter (which still uses
layers_block_type) unchanged: 43 tests green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 15:59:04 -07:00
S1ro1andClaude Fable 5 fb013c6fb6 refactor(models): move build_qwen3_moe_chain into models/qwen3_moe/conversion_chain.py
Consistency: every model's chain now lives in its own package; conversion_chains.py
holds only the shared helpers (_routed_experts_op, _GATE_DOWN_UP) and the registry.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 15:59:04 -07:00
S1ro1andClaude Fable 5 686260561d refactor(models): decompose MoEExperts/FusedGateUp into general Stack/SplitConcat base-ops
Replace the two MoE-specific value ops with orthogonal primitives:
- Stack: stack/unstack a variable {e}-indexed group along a new dim (index_offset
  for shard-local global numbering)
- SplitConcat: split/concat fixed parts along an existing dim
- Sequence: bundle ops into one (lets the routed-experts helper stay a single op)

The MoE-ness now lives only in the _routed_experts_op composition helper (Stack
per proj + a Conditional that splits the fused gate_up input), not in the op
vocabulary. NemotronH's fused case collapses to a plain Rename. All 43
equivalence tests unchanged and green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 15:59:04 -07:00
S1ro1andClaude Fable 5 e138ea5d9d feat(models): declarative conversion chains for all models + mock equivalence tests
Encode every model's HF<->prime conversion as an invertible op chain
(conversion_chains.py + models/<name>/conversion_chain.py), registered by
model_type and reachable via PreTrainedModelPrimeRL.conversion_ops. Covers
qwen3_moe, qwen3_5_moe, glm4_moe, glm_moe_dsa, minimax_m2, laguna, afmoe,
nemotron_h, and gpt_oss (identity).

Each chain is verified against the legacy imperative convert_* functions on
mock state dicts (forward, backward, and roundtrip where lossless) — 43
passing tests in tests/unit/train/models/conversions. The ops are
sharding-aware (name ops are value-agnostic; the expert stack/unstack takes
a global-expert offset) and never gather.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 15:59:04 -07:00
S1ro1andClaude Fable 5 537dc8c768 feat(models): declarative conversion chain for qwen3_moe + mock equivalence test
Proves the framework: forward (per-expert & fused), backward, and roundtrip
all match the legacy imperative convert_hf_to_tt_moe/convert_tt_to_hf_moe.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 15:59:04 -07:00
S1ro1andClaude Fable 5 919dfbb637 feat(models): declarative invertible conversion-op framework
ConvOp vocabulary (Rename, PrefixRename, Drop, MoEExperts+FusedGateUp,
Synthetic, MapValue, SqueezeLeading, Conditional) + apply_hf_to_tt /
apply_tt_to_hf runners. Sharding-aware (name ops are value-agnostic; the
expert stack/unstack takes a global-expert offset for shard-local
operation), no gathers in the ops themselves.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 15:59:04 -07:00
51 changed files with 2900 additions and 1482 deletions
@@ -82,9 +82,16 @@ class ModelConfig(BaseModelConfig):
class WeightBroadcastConfig(BaseConfig):
type: Literal["nccl", "filesystem"] = "filesystem"
type: Literal["nccl", "filesystem", "nixl"] = "filesystem"
"""Weight broadcast transport."""
host: str = "modelexpress"
port: int = 8001
timeout: int = 1200
inference_world_size: int = Field(1, ge=1)
session_id: str = ""
model_name: str = ""
class CPUOffloadTier(BaseConfig):
num_bytes: int = Field(..., gt=0)
@@ -416,8 +416,19 @@ class NCCLWeightBroadcastConfig(BaseConfig):
"""Total inference GPUs across all servers. Used by ``init_nccl_broadcast`` to compute per-server rank offsets."""
class NIXLWeightBroadcastConfig(BaseConfig):
type: Literal["nixl"] = "nixl"
host: str = "modelexpress"
port: int = 8001
timeout: int = 1200
inference_world_size: int = Field(1, ge=1)
session_id: str = ""
model_name: str = ""
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig, Field(discriminator="type")
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
Field(discriminator="type"),
]
@@ -1,4 +1,5 @@
import warnings
from hashlib import sha256
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
@@ -12,6 +13,9 @@ 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,
)
@@ -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,
@@ -111,11 +118,11 @@ class SharedModelConfig(BaseConfig):
class SharedWeightBroadcastConfig(BaseConfig):
type: Literal["nccl", "filesystem"] = "nccl"
type: Literal["nccl", "filesystem", "nixl"] = "nccl"
"""Weight broadcast transport."""
port: int = 29501
"""Port for NCCL weight broadcast."""
port: int | None = None
"""Transport service port. Defaults to 29501 for NCCL and 8001 for NIXL."""
timeout: int = 1200
"""Timeout in seconds for NCCL weight broadcast."""
@@ -123,6 +130,12 @@ class SharedWeightBroadcastConfig(BaseConfig):
quantize_in_weight_transfer: bool = False
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
host: str = "modelexpress"
"""ModelExpress service host for NIXL weight transfer."""
session_id: str | None = None
"""Optional ModelExpress namespace. Defaults to a stable digest of ``output_dir``."""
class BaseDeploymentConfig(BaseConfig):
gpus_per_node: int = 8
@@ -357,24 +370,45 @@ class RLConfig(BaseConfig):
)
if self.weight_broadcast.type == "nccl":
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
port = self.weight_broadcast.port or 29501
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
type=self.weight_broadcast.type,
inference_world_size=inference_world_size,
port=self.weight_broadcast.port,
port=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,
port=self.weight_broadcast.port,
port=port,
timeout=self.weight_broadcast.timeout,
inference_world_size=inference_world_size,
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
)
elif self.weight_broadcast.type == "nixl":
if self.trainer.model.lora is not None:
raise ValueError("LoRA training is not yet supported with NIXL weight broadcast.")
if self.inference is None:
raise ValueError("NIXL weight broadcast requires an inference config.")
if self.inference.enable_eplb:
raise ValueError("NIXL weight broadcast does not support EPLB because it changes the baked expert map.")
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp
session_id = self.weight_broadcast.session_id or sha256(str(self.trainer.output_dir).encode()).hexdigest()[:16]
common = {
"host": self.weight_broadcast.host,
"port": self.weight_broadcast.port or 8001,
"timeout": self.weight_broadcast.timeout,
"inference_world_size": inference_world_size,
"session_id": session_id,
"model_name": self.trainer.model.name,
}
self.trainer.weight_broadcast = TrainerNIXLWeightBroadcastConfig(**common)
self.orchestrator.weight_broadcast = OrchestratorNIXLWeightBroadcastConfig(**common)
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type="nixl", **common)
elif self.weight_broadcast.type == "filesystem":
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
if self.inference is not None:
if self.inference is not None and self.weight_broadcast.type != "nixl":
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
validate_shared_weight_broadcast(self.trainer, self.orchestrator, self.inference)
@@ -616,7 +650,7 @@ 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":
if self.weight_broadcast is not None and self.weight_broadcast.type in ("nccl", "nixl"):
# Every allocated inference GPU is a NCCL rank in the weight broadcast.
# 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
@@ -625,11 +659,14 @@ class RLConfig(BaseConfig):
# factor count twice and NCCL 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
if self.inference is not None:
self.inference.weight_broadcast.inference_world_size = total_infer_workers
return self
@@ -659,11 +696,12 @@ 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
self.inference.weight_broadcast.inference_world_size = total_infer_gpus
return self
@@ -504,8 +504,30 @@ class NCCLWeightBroadcastConfig(BaseWeightBroadcastConfig):
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
class NIXLWeightBroadcastConfig(BaseWeightBroadcastConfig):
type: Literal["nixl"] = "nixl"
host: str = "modelexpress"
"""ModelExpress service host."""
port: int = 8001
"""ModelExpress service port."""
timeout: int = 1200
"""Timeout in seconds for publication, pull, and acknowledgement."""
inference_world_size: int = Field(1, ge=1)
"""Total number of inference workers expected to acknowledge each update."""
session_id: str = ""
"""Stable identifier shared by all processes in one training run."""
model_name: str = ""
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig, Field(discriminator="type")
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
Field(discriminator="type"),
]
@@ -652,11 +674,16 @@ class TrainerConfig(BaseConfig):
raise ValueError("Optimizer CPU offload is not supported with max_concurrent_runs > 1")
return self
@model_validator(mode="after")
def validate_nixl_single_run(self):
if self.weight_broadcast.type == "nixl" and self.max_concurrent_runs != 1:
raise ValueError("NIXL weight broadcast currently supports max_concurrent_runs = 1.")
return self
@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(f"{self.weight_broadcast.type.upper()} weight broadcast does not support LoRA yet.")
return self
@model_validator(mode="after")
+17 -2
View File
@@ -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",
}
@@ -87,7 +88,10 @@ async def resume(request: Request):
@router.post("/update_weights")
async def update_weights(request: Request):
data = await request.json()
await engine_client(request).collective_rpc("update_weights_from_path", args=(data.get("weight_dir"),))
await engine_client(request).collective_rpc(
"update_weights_from_path",
args=(data.get("weight_dir"), data.get("step", 0)),
)
return {"status": "ok"}
@@ -143,9 +147,20 @@ 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", "")
model_name = data.get("model_name", "")
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,
model_name,
),
)
return {"status": "ok"}
@@ -25,7 +25,7 @@ class FileSystemWeightUpdateWorker(Worker):
"""No-op RPC used by the API server liveness endpoint."""
return None
def update_weights_from_path(self, weight_path: str) -> None:
def update_weights_from_path(self, weight_path: str, step: int = 0) -> None:
"""Update weights from a specified path in shared filesystem containing a HF-compatible checkpoint."""
# Get vLLM model runner and model
# When enforce_eager=True, model isn't wrapped by torch.compile so no .runnable attr
+3 -1
View File
@@ -100,6 +100,8 @@ class NCCLWeightUpdateWorker(Worker):
inference_world_size: int,
timeout: int,
quantize_in_weight_transfer: bool = False,
session_id: str = "",
model_name: str = "",
) -> None:
"""Initialize the NCCL broadcast receiver.
@@ -133,7 +135,7 @@ class NCCLWeightUpdateWorker(Worker):
"""No-op RPC used by the API server liveness endpoint."""
return None
def update_weights_from_path(self, weight_dir: str) -> None:
def update_weights_from_path(self, weight_dir: str, step: int = 0) -> None:
"""Update weights with the nccl communicator."""
model_runner = self.model_runner
if hasattr(model_runner.model, "runnable"):
+353
View File
@@ -0,0 +1,353 @@
"""vLLM worker extension for sharded, pull-based NIXL weight updates."""
from __future__ import annotations
import time
from collections import defaultdict
from math import prod
from typing import TYPE_CHECKING, Any
import torch
import torch.nn as nn
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.weight_transfer.chains import region_elem_runs, resolve_chain_region
from prime_rl.weight_transfer.cuda_pool import classic_cuda_alloc
from prime_rl.weight_transfer.lazy import BakeRecorder, LazyWeight, RecordedCopy
from prime_rl.weight_transfer.mx import MxChannel
from prime_rl.weight_transfer.nixl import NixlAgent, agent_name, configure_ucx
from prime_rl.weight_transfer.publication import route_published_region
from prime_rl.weight_transfer.sharding import zip_source_destination
from prime_rl.weight_transfer.wire import (
PublishedTensor,
SyncSignal,
WeightManifest,
decode_manifest,
decode_signal,
encode_signal,
)
if TYPE_CHECKING:
from vllm.v1.worker.gpu_worker import Worker
else:
Worker = object
logger = init_logger("vllm.inference.vllm.worker_nixl")
def _torch_dtype(name: str) -> torch.dtype:
dtype = getattr(torch, name.removeprefix("torch."), None)
if not isinstance(dtype, torch.dtype):
raise ValueError(f"unsupported published dtype {name!r}")
return dtype
class _BakedGroup:
def __init__(self, layer: nn.Module, copies: list[RecordedCopy]) -> None:
self.layer = layer
self.copies = copies
self.param_names = sorted({copy.param_name for copy in copies})
self.arena_offsets: dict[int, int] = {}
self.pull_specs: list[tuple[Any, Any, list[int]]] = []
self.num_bytes = 0
class NIXLWeightUpdateWorker(Worker):
@property
def raw_model(self) -> nn.Module:
model = self.model_runner.model
model = model.runnable if hasattr(model, "runnable") else model
if not isinstance(model, nn.Module):
raise TypeError(f"expected a torch module, got {type(model).__name__}")
return 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 = "",
model_name: str = "",
) -> None:
if self.vllm_config.parallel_config.enable_eplb:
raise NotImplementedError("NIXL weight broadcast does not support EPLB")
if quantize_in_weight_transfer:
raise ValueError("NIXL uses vLLM layerwise processing; configure inference quantization instead")
local_rank = self.device.index or 0
self._rank = rank_offset + local_rank
self._world_size = inference_world_size
self._timeout = timeout
self._session_id = session_id
self._model_name = model_name or self.model_runner.model_config.model
self._mx = MxChannel(
f"{host}:{port}",
session_id,
self._model_name,
"inference",
"sync",
self._rank,
)
self._initialized = False
logger.info(f"NIXL pull worker configured: rank={self._rank}, session={session_id}")
@torch.no_grad()
def _lazy_init(self) -> None:
if self._initialized:
return
started = time.perf_counter()
def valid_manifest(payload: bytes) -> bool:
manifest = decode_manifest(payload)
return manifest.session_id == self._session_id and manifest.model == self._model_name
payloads = self._mx.wait_for("trainer", "manifest", 1, valid_manifest, self._timeout)
self._manifest = decode_manifest(next(iter(payloads.values())))
configure_ucx(self.device.index or 0)
self._agent = NixlAgent(agent_name("inference", self._rank, f"{self._session_id}-{self._manifest.epoch}"))
self._groups = self._bake(self._manifest)
self._allocate_arena(self._groups)
self._build_pull_plans(self._manifest, self._groups)
self._initialized = True
logger.info(
f"NIXL pull plan baked in {time.perf_counter() - started:.2f}s: "
f"rank={self._rank}, groups={len(self._groups)}, bytes={self._total_pull_bytes:,}"
)
def _bake(self, manifest: WeightManifest) -> list[_BakedGroup]:
from vllm.model_executor.model_loader.reload.layerwise import (
LAYERWISE_INFO,
_get_original_loader,
_place_kernel_tensors,
initialize_layerwise_reload,
)
from vllm.model_executor.model_loader.reload.utils import get_layer_size, get_layer_tensors
recorder = BakeRecorder()
model = self.raw_model
with torch.device(self.device), set_current_vllm_config(self.vllm_config):
initialize_layerwise_reload(model)
for module in model.modules():
for name, tensor in get_layer_tensors(module).items():
loader = getattr(tensor, "weight_loader", None)
if loader is not None:
tensor.weight_loader = self._stamp(recorder, module, name, _get_original_loader(tensor))
weights = (
(
tensor.name,
LazyWeight(
tensor.name,
torch.Size(tensor.shape),
_torch_dtype(tensor.dtype),
self.device,
recorder,
),
)
for tensor in manifest.tensors
)
model.load_weights(weights)
copies_by_layer: dict[int, list[RecordedCopy]] = defaultdict(list)
layers: dict[int, nn.Module] = {}
for copy in recorder.copies:
copies_by_layer[id(copy.layer)].append(copy)
layers[id(copy.layer)] = copy.layer
groups: list[_BakedGroup] = []
for layer_id, copies in copies_by_layer.items():
layer = layers[layer_id]
covered = sum(prod(copy.shape) for copy in copies)
expected = get_layer_size(layer)
if covered < expected:
raise RuntimeError(
f"NIXL bake covered {covered}/{expected} elements of {type(layer).__name__}; "
"partial reloads are not allowed"
)
groups.append(_BakedGroup(layer, copies))
self._param_layout: dict[tuple[int, str], tuple[torch.Size, torch.dtype]] = {}
for group in groups:
for name in group.param_names:
parameter = getattr(group.layer, name)
self._param_layout[(id(group.layer), name)] = (parameter.shape, parameter.dtype)
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
if not groups:
raise RuntimeError("vLLM consumed no published weights during the NIXL bake")
return groups
@staticmethod
def _stamp(recorder: BakeRecorder, layer: nn.Module, name: str, loader: Any):
def stamped(*args, **kwargs):
recorder.current = (layer, name)
try:
return loader(*args, **kwargs)
finally:
recorder.current = None
return stamped
def _allocate_arena(self, groups: list[_BakedGroup]) -> None:
max_bytes = 0
for group in groups:
offset = 0
for index, copy in enumerate(group.copies):
dtype = self._param_layout[(id(group.layer), copy.param_name)][1]
offset = (offset + 255) // 256 * 256
group.arena_offsets[index] = offset
offset += prod(copy.shape) * dtype.itemsize
group.num_bytes = offset
max_bytes = max(max_bytes, offset)
with classic_cuda_alloc():
self._arena = torch.empty(max_bytes, dtype=torch.uint8, device=self.device)
self._agent.register_tensor(self._arena)
def _build_pull_plans(self, manifest: WeightManifest, groups: list[_BakedGroup]) -> None:
tensors = {tensor.name: tensor for tensor in manifest.tensors}
remote_names: dict[int, str] = {}
for index, descriptor in enumerate(manifest.agents):
remote_name = self._agent.add_remote_agent(descriptor.metadata)
self._agent.connect(remote_name)
remote_names[index] = remote_name
agent_devices: dict[int, int] = {}
for tensor in manifest.tensors:
for segment in tensor.segments:
previous = agent_devices.setdefault(segment.agent, segment.device_id)
if previous != segment.device_id:
raise ValueError(f"trainer agent {segment.agent} published multiple CUDA device ids")
self._total_pull_bytes = 0
for group in groups:
local: dict[int, list[tuple[int, int, int]]] = defaultdict(list)
remote: dict[int, list[tuple[int, int, int]]] = defaultdict(list)
for index, copy in enumerate(group.copies):
tensor = tensors.get(copy.src_name)
if tensor is None:
raise KeyError(f"vLLM requested unpublished HF tensor {copy.src_name!r}")
source_dtype = _torch_dtype(tensor.dtype)
destination_dtype = self._param_layout[(id(group.layer), copy.param_name)][1]
if source_dtype != destination_dtype:
raise ValueError(
f"dtype mismatch for {copy.src_name!r}: source={source_dtype}, destination={destination_dtype}"
)
offset, shape, stride = resolve_chain_region(tensor.shape, source_dtype, copy.ops)
source = route_published_region(
tensor,
region_elem_runs(offset, shape, stride),
source_dtype.itemsize,
)
arena_address = self._arena.data_ptr() + group.arena_offsets[index]
num_bytes = prod(copy.shape) * source_dtype.itemsize
for agent, source_address, destination_address, length in zip_source_destination(
source,
[(arena_address, num_bytes)],
):
local[agent].append((destination_address, length, self.device.index or 0))
remote[agent].append((source_address, length, agent_devices[agent]))
self._total_pull_bytes += length
for agent, descriptors in sorted(remote.items()):
local_prepared = self._agent.prepare_local(local[agent])
remote_prepared = self._agent.prepare_remote(remote_names[agent], descriptors)
group.pull_specs.append((local_prepared, remote_prepared, list(range(len(descriptors)))))
@torch.no_grad()
def update_weights_from_path(self, weight_dir: str | None = None, step: int = 0) -> None:
self._lazy_init()
manifest = self._manifest
def ready(payload: bytes) -> bool:
signal = decode_signal(payload)
return (
signal.session_id == manifest.session_id
and signal.epoch == manifest.epoch
and signal.step == step
and signal.phase == "trainer_ready"
and signal.fingerprint == manifest.fingerprint
)
self._mx.wait_for("trainer", "sync", 1, ready, self._timeout)
started = time.perf_counter()
self._reload_groups()
update_mla_absorbed_weights(self.raw_model)
torch.cuda.synchronize(self.device)
self._mx.publish(
encode_signal(
SyncSignal(
session_id=manifest.session_id,
epoch=manifest.epoch,
step=step,
phase="inference_applied",
rank=self._rank,
fingerprint=manifest.fingerprint,
)
)
)
logger.info(
f"NIXL weight update v{step}: {self._total_pull_bytes / 1e9:.2f} GB pulled and processed "
f"in {time.perf_counter() - started:.2f}s"
)
def _reload_groups(self) -> 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,
)
model = self.raw_model
with torch.device(self.device), set_current_vllm_config(self.vllm_config):
initialize_layerwise_reload(model)
for group in self._groups:
handles = [
self._agent.read(local, indices, remote, indices)
for local, remote, indices in group.pull_specs
]
for handle in handles:
self._agent.wait(handle, context=f"{type(group.layer).__name__} weight pull")
for name in group.param_names:
shape, dtype = self._param_layout[(id(group.layer), name)]
setattr(group.layer, name, nn.Parameter(torch.empty(shape, dtype=dtype, device=self.device), False))
for index, copy in enumerate(group.copies):
dtype = self._param_layout[(id(group.layer), copy.param_name)][1]
num_bytes = prod(copy.shape) * dtype.itemsize
source = self._arena.narrow(0, group.arena_offsets[index], num_bytes).view(dtype).view(copy.shape)
destination = getattr(group.layer, copy.param_name).as_strided(
copy.shape,
copy.stride,
copy.offset,
)
destination.copy_(source)
quant_method = getattr(group.layer, "quant_method", None)
if isinstance(quant_method, QuantizeMethodBase):
if hasattr(group.layer, "_already_called_process_weights_after_loading"):
delattr(group.layer, "_already_called_process_weights_after_loading")
quant_method.process_weights_after_loading(group.layer)
info = LAYERWISE_INFO.get(group.layer)
if info is not None and info.kernel_tensors is not None:
_copy_and_restore_kernel_tensors(group.layer, info)
if info is not None:
info.reset()
finalize_layerwise_reload(model, self.model_runner.model_config)
+18 -9
View File
@@ -71,7 +71,7 @@ from prime_rl.orchestrator.watcher import WeightWatcher
from prime_rl.trainer.model import setup_tokenizer
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_weight_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
@@ -298,14 +298,16 @@ class Orchestrator:
await self.inference_metrics.start()
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
if config.weight_broadcast.type == "nccl":
await init_nccl_broadcast(
if config.weight_broadcast.type in ("nccl", "nixl"):
await init_weight_broadcast(
self.policy_inference.admin_clients,
config.weight_broadcast.host,
config.weight_broadcast.port,
config.weight_broadcast.timeout,
inference_world_size=config.weight_broadcast.inference_world_size,
quantize_in_weight_transfer=config.weight_broadcast.quantize_in_weight_transfer,
quantize_in_weight_transfer=getattr(config.weight_broadcast, "quantize_in_weight_transfer", False),
session_id=getattr(config.weight_broadcast, "session_id", ""),
model_name=getattr(config.weight_broadcast, "model_name", config.model.name),
)
get_logger().info(f"Initializing training batch sender ({config.rollout_transport})")
@@ -327,13 +329,20 @@ class Orchestrator:
# 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":
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"
check_exists = config.weight_broadcast.type not in ("nccl", "nixl")
# 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
weights_path = (
None
if config.weight_broadcast.type == "nixl"
else get_weight_dir(
config.output_dir,
sync_version,
check_exists=check_exists,
wait_timeout=wait_timeout,
)
)
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=sync_version)
if self.lora_name is not None:
@@ -833,7 +842,7 @@ class Orchestrator:
# 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"
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
)
+29 -6
View File
@@ -14,6 +14,8 @@ from prime_rl.utils.client import InferencePool
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import get_broadcast_dir, get_step_path, wait_for_path
from prime_rl.utils.utils import get_latest_ckpt_step
from prime_rl.weight_transfer.mx import MxChannel
from prime_rl.weight_transfer.wire import decode_signal
class WeightWatcher:
@@ -45,12 +47,26 @@ class WeightWatcher:
self.task: asyncio.Task | None = None
self.update_lock = asyncio.Lock()
self.stopped = asyncio.Event()
self.mx_channel = None
if config.weight_broadcast.type == "nixl":
self.mx_channel = MxChannel(
f"{config.weight_broadcast.host}:{config.weight_broadcast.port}",
config.weight_broadcast.session_id,
config.weight_broadcast.model_name,
"orchestrator",
"sync",
0,
)
async def start(self) -> None:
self.task = asyncio.current_task()
try:
while not self.stopped.is_set():
next_step = self.compute_next_ckpt_step()
next_step = (
await asyncio.to_thread(self.compute_next_ckpt_step)
if self.mx_channel is not None
else self.compute_next_ckpt_step()
)
if next_step > self.ckpt_step:
await self.apply_policy_update(next_step)
await asyncio.sleep(self.poll_interval)
@@ -67,8 +83,15 @@ class WeightWatcher:
"""Next checkpoint to adopt — at least ``policy.version`` (we stay
one step ahead of the trainer) plus anything fresher already
published in ``broadcasts/``."""
broadcast_dir = get_broadcast_dir(self.config.output_dir)
latest_ckpt_step = get_latest_ckpt_step(broadcast_dir) or 0
if self.mx_channel is not None:
latest_ckpt_step = 0
for payload in self.mx_channel.payloads("trainer", "sync").values():
signal = decode_signal(payload)
if signal.phase == "trainer_ready" and signal.session_id == self.config.weight_broadcast.session_id:
latest_ckpt_step = max(latest_ckpt_step, signal.step)
else:
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)
async def apply_policy_update(self, next_step: int) -> None:
@@ -78,9 +101,9 @@ class WeightWatcher:
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():
weights_path = None if self.mx_channel is not None else get_step_path(broadcast_dir, next_step)
stable_marker = None if weights_path is None else weights_path / "STABLE"
if stable_marker is not None and not stable_marker.exists():
get_logger().info(
f"Orchestrator paused: waiting for trainer to broadcast checkpoint {next_step}. "
"Training is progressing normally."
@@ -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
@@ -36,12 +36,7 @@ from prime_rl.trainer.models.layers.rotary_emb import (
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
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
@@ -412,25 +407,8 @@ class AfmoePreTrainedModel(PreTrainedModelPrimeRL):
def is_prime_state_dict(cls, state_dict: dict[str, torch.Tensor]) -> bool:
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(self):
return conversion_chain(self.config)
class AfmoeModel(AfmoePreTrainedModel):
+28 -44
View File
@@ -51,57 +51,41 @@ 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(self) -> "list":
"""Declarative HF<->prime conversion as a list of
:class:`~prime_rl.trainer.models.conversion_ops.ConvOp`.
This is used when saving checkpoints or broadcasting weights to inference engines
that expect HuggingFace-compatible format.
Each model defines this in its ``converting_<model>.py`` and the model
class returns it here (using ``self.config``). The ``convert_*`` methods
below play it forward (HF -> prime) or backward (prime -> HF); since
every op is present-guarded, the same chain works on a full state dict,
a single layer's keys, or a local shard. Models whose HF and prime
layouts coincide return an empty chain."""
raise NotImplementedError(f"conversion_chain is not implemented for {self.__class__.__name__}")
Args:
state_dict: The state dict to convert (modified in-place).
"""
raise NotImplementedError(f"convert_to_hf is not implemented for {cls.__name__}")
def convert_to_hf(self, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
"""Convert a state dict from PrimeRL training format to HuggingFace
format in-place (saving checkpoints, broadcasting to inference)."""
from prime_rl.trainer.models.conversion_ops import apply_tt_to_hf
@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.
return apply_tt_to_hf(state_dict, self.conversion_chain())
This is used when loading pretrained HuggingFace models for training with
PrimeRL-specific optimizations.
def convert_to_prime(self, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
"""Convert a state dict from HuggingFace format to PrimeRL training
format in-place (loading pretrained HF models)."""
from prime_rl.trainer.models.conversion_ops import apply_hf_to_tt
Args:
state_dict: The state dict to convert (modified in-place).
"""
raise NotImplementedError(f"convert_to_prime is not implemented for {cls.__name__}")
return apply_hf_to_tt(state_dict, self.conversion_chain())
@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.
def convert_layer_to_hf(self, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
"""Per-layer PrimeRL -> HuggingFace (NCCL broadcast). Present-guarded
ops make playing the full chain over a single layer's keys equivalent
to converting just that layer."""
return self.convert_to_hf(state_dict)
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]:
"""Per-layer HuggingFace -> PrimeRL (see :meth:`convert_layer_to_hf`)."""
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,361 @@
"""Declarative, invertible state-dict conversion operators.
Every prime-rl model converts between the HuggingFace checkpoint layout and
prime-rl's training ("tt") 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_tt``): HF checkpoint -> prime training layout
backward (``tt_to_hf``): prime training layout -> HF checkpoint
A model declares a flat list of ``ConvOp``\\ s (with concrete, fully-templated
keys). :func:`apply_hf_to_tt` plays them in order; :func:`apply_tt_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_tt(self, sd: StateDict) -> None: ...
@abstractmethod
def tt_to_hf(self, sd: StateDict) -> None: ...
def apply_hf_to_tt(sd: StateDict, ops: list[ConvOp]) -> StateDict:
"""Play the chain forward (HF -> prime), in place."""
for op in ops:
op.hf_to_tt(sd)
return sd
def apply_tt_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.tt_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, ``tt`` the prime name."""
hf: str
tt: str
def hf_to_tt(self, sd: StateDict) -> None:
if self.hf in sd:
sd[self.tt] = sd.pop(self.hf)
def tt_to_hf(self, sd: StateDict) -> None:
if self.tt in sd:
sd[self.hf] = sd.pop(self.tt)
@dataclass
class PrefixRename(ConvOp):
"""Rename every key under a prefix (e.g. ``backbone.`` <-> ``model.``,
``mixer.`` <-> ``mamba.``, ``block_sparse_moe.`` <-> ``mlp.``)."""
hf: str
tt: 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_tt(self, sd: StateDict) -> None:
self._swap(sd, self.hf, self.tt)
def tt_to_hf(self, sd: StateDict) -> None:
self._swap(sd, self.tt, 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_tt(self, sd: StateDict) -> None:
self._drop(sd)
def tt_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_tt(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 tt_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_tt(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 tt_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)."""
tt: str
factory: Callable[[StateDict], Tensor]
def hf_to_tt(self, sd: StateDict) -> None:
sd[self.tt] = self.factory(sd)
def tt_to_hf(self, sd: StateDict) -> None:
sd.pop(self.tt, 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)."""
tt: str # the prime-side key the value lives under (after any rename)
forward: Callable[[Tensor], Tensor]
backward: Callable[[Tensor], Tensor]
def hf_to_tt(self, sd: StateDict) -> None:
if self.tt in sd:
sd[self.tt] = self.forward(sd[self.tt])
def tt_to_hf(self, sd: StateDict) -> None:
if self.tt in sd:
sd[self.tt] = self.backward(sd[self.tt])
@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_tt(self, sd: StateDict) -> None:
return None
def tt_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_tt`` sees HF keys, ``tt_to_hf`` sees prime
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_tt(self, sd: StateDict) -> None:
apply_hf_to_tt(sd, self.then if self.predicate(sd) else self.else_)
def tt_to_hf(self, sd: StateDict) -> None:
branch = self.then if self.predicate(sd) else self.else_
apply_tt_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_tt(self, sd: StateDict) -> None:
apply_hf_to_tt(sd, self.ops)
def tt_to_hf(self, sd: StateDict) -> None:
apply_tt_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,
tt_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``/``tt_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}.{tt_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}.{tt_experts}.w1", None), (f"{prefix}.{tt_experts}.w3", None)],
dim=1,
),
Rename(f"{prefix}.{hf_experts}.down_proj", f"{prefix}.{tt_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<->tt 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<->tt 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",
tt_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_tt_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
@@ -143,29 +138,8 @@ class Glm4MoePreTrainedModel(PreTrainedModelPrimeRL):
"""Check if the state dict contains MoE layers in PrimeRL training format."""
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(self):
return conversion_chain(self.config)
@auto_docstring
@@ -1,146 +1,33 @@
"""HF<->prime weight conversion for GLM-MoE-DSA.
GLM-MoE-DSA's hf<->tt MoE conversion is identical to GLM-4 MoE (router rename,
expert-bias rename, fused-or-per-expert routed experts, shared experts with the
same backward leading-dim squeeze, and dropping the prime-only
``tokens_per_expert`` buffer), so :func:`conversion_chain` reuses
:func:`prime_rl.trainer.models.glm4_moe.converting_glm4_moe.glm_moe_layer_ops`.
The attention / MLA (DSA) weights (e.g. ``self_attn.q_a_proj.weight``,
``self_attn.kv_a_proj_with_mqa.weight``) are *not* renamed in the hf<->tt
direction — they pass through untouched. The ``convert_tt_layer_to_vllm_kernel``
fusion below is a separate, lossy terminal path (FP8/MLA) and is intentionally
not encoded in the declarative chain.
"""
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 i in range(config.num_hidden_layers):
ops.extend(glm_moe_layer_ops(i))
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
@@ -145,25 +142,8 @@ class GlmMoeDsaPreTrainedModel(PreTrainedModelPrimeRL):
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
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(self):
return conversion_chain(self.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,
)
@@ -192,13 +191,8 @@ class GptOssPreTrainedModel(PreTrainedModelPrimeRL):
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
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(self):
return conversion_chain(self.config)
@auto_docstring
@@ -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", tt_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
@@ -16,12 +16,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, SDPAAttention
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
@@ -305,25 +300,8 @@ class LagunaPreTrainedModel(PreTrainedModelPrimeRL):
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]:
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(self):
return conversion_chain(self.config)
class LagunaModel(LagunaPreTrainedModel):
@@ -127,25 +127,8 @@ class LlamaPreTrainedModel(PreTrainedModelPrimeRL):
"""Check if the state dict is in PrimeRL training format."""
return True
@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."""
return state_dict
@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."""
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 state dict from PrimeRL format to HuggingFace format in-place."""
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 state dict from HuggingFace format to PrimeRL format in-place."""
return state_dict
def conversion_chain(self):
return []
@auto_docstring
@@ -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",
tt_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_position_ids
logger = logging.get_logger(__name__)
@@ -111,25 +106,8 @@ class MiniMaxM2PreTrainedModel(PreTrainedModelPrimeRL):
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
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(self):
return conversion_chain(self.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_position_ids
logger = logging.get_logger(__name__)
@@ -373,18 +368,8 @@ class NemotronHPreTrainedModel(PreTrainedModelPrimeRL):
for name in state_dict
)
@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(self):
return conversion_chain(self.config)
@classmethod
def convert_adapter_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
@@ -403,88 +388,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):
@@ -111,21 +111,8 @@ class Qwen3PreTrainedModel(PreTrainedModelPrimeRL):
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return True
@classmethod
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
return state_dict
@classmethod
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
return state_dict
@classmethod
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
return state_dict
@classmethod
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
return state_dict
def conversion_chain(self):
return []
@auto_docstring
@@ -157,21 +157,8 @@ class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return True
@classmethod
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
return state_dict
@classmethod
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
return state_dict
@classmethod
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
return state_dict
@classmethod
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
return state_dict
def conversion_chain(self):
return []
class Qwen3_5Model(Qwen3_5PreTrainedModel):
@@ -1,122 +1,29 @@
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 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]:
ops: list[ConvOp] = []
for i in range(config.num_hidden_layers):
p = f"model.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", tt_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
@@ -28,12 +28,7 @@ from prime_rl.trainer.models.layers.ulysses_attn import ULYSSES_PARAMS
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids, 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
# Flash linear attention imports (for GatedDeltaNet fast path)
@@ -830,25 +825,8 @@ class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
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(self):
return conversion_chain(self.config)
class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
@@ -1135,42 +1113,23 @@ 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]:
def conversion_chain(self):
return conversion_chain(self.config.text_config if self._is_vlm else self.config)
def convert_to_hf(self, 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)
super().convert_to_hf(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]:
def convert_to_prime(self, 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)
super().convert_to_prime(state_dict)
if vlm:
_remap_lm_keys(state_dict, to_flat=False)
return state_dict
@@ -1,97 +1,19 @@
import torch
from torch import Tensor
"""HF<->prime weight conversion for Qwen3-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`` and the
routed experts (per-expert gate/down/up <-> stacked w1/w2/w3, with the fused
transformers-v5 ``gate_up_proj`` input also accepted). No shared experts.
"""
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 i in range(config.num_hidden_layers):
p = f"model.layers.{i}"
ops.append(Rename(f"{p}.mlp.gate.weight", f"{p}.mlp.router.gate.weight"))
ops.append(routed_experts_op(p, hf_experts="mlp.experts", tt_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_position_ids
logger = logging.get_logger(__name__)
@@ -146,29 +141,8 @@ class Qwen3MoePreTrainedModel(PreTrainedModelPrimeRL):
"""Check if the state dict contains MoE layers in PrimeRL training format."""
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(self):
return conversion_chain(self.config)
@auto_docstring
@@ -9,11 +9,17 @@ from prime_rl.trainer.rl.broadcast.nccl import NCCLWeightBroadcast
def setup_weight_broadcast(
output_dir: Path, config: WeightBroadcastConfig, lora_config: LoRAConfig | None = None
output_dir: Path,
config: WeightBroadcastConfig,
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":
from prime_rl.trainer.rl.broadcast.nixl import NIXLWeightBroadcast
return NIXLWeightBroadcast(output_dir, config)
else:
raise ValueError(f"Invalid weight broadcast type: {config.type}")
+264
View File
@@ -0,0 +1,264 @@
"""Trainer-side sharded source for pull-based NIXL weight updates."""
from __future__ import annotations
import time
import uuid
from dataclasses import dataclass
from hashlib import sha256
from pathlib import Path
import msgspec
import torch
import torch.distributed as dist
import torch.nn as nn
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 import PreTrainedModelPrimeRL
from prime_rl.trainer.rl.broadcast.base import WeightBroadcast
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.trainer.world import get_world
from prime_rl.weight_transfer.mx import MxChannel
from prime_rl.weight_transfer.nixl import NixlAgent, agent_name, configure_ucx
from prime_rl.weight_transfer.ownership import ShardCandidate, select_shard_owners, select_source_tensors
from prime_rl.weight_transfer.publication import publish_hf_tensors
from prime_rl.weight_transfer.cuda_pool import classic_cuda_alloc
from prime_rl.weight_transfer.wire import (
AgentDescriptor,
SyncSignal,
WeightManifest,
decode_signal,
encode_manifest,
encode_signal,
)
SERVING_DTYPE = torch.bfloat16
@dataclass
class _LocalShard:
candidate: ShardCandidate
source: torch.Tensor
buffer: torch.Tensor | None = None
@property
def key(self) -> tuple[int, str, tuple[int, ...], tuple[int, ...]]:
return (
self.candidate.rank,
self.candidate.name,
self.candidate.global_offset,
self.candidate.shape,
)
def allocate(self, device: torch.device) -> None:
if self.source.dtype == SERVING_DTYPE and self.source.is_cuda and self.source.is_contiguous():
self.buffer = self.source
else:
with classic_cuda_alloc():
self.buffer = torch.empty(self.source.shape, dtype=SERVING_DTYPE, device=device)
def refresh(self) -> None:
if self.buffer is None:
raise RuntimeError(f"source buffer for {self.candidate.name!r} has not been allocated")
if self.buffer is self.source:
if self.buffer.data_ptr() != self.candidate.address:
raise RuntimeError(f"live source storage for {self.candidate.name!r} moved after NIXL registration")
return
self.buffer.copy_(self.source, non_blocking=True)
def finalized_candidate(self) -> ShardCandidate:
if self.buffer is None:
raise RuntimeError(f"source buffer for {self.candidate.name!r} has not been allocated")
return ShardCandidate(
rank=self.candidate.rank,
name=self.candidate.name,
dtype=SERVING_DTYPE,
full_shape=self.candidate.full_shape,
global_offset=self.candidate.global_offset,
shape=self.candidate.shape,
address=self.buffer.data_ptr(),
device_id=self.buffer.device.index or 0,
)
class NIXLWeightBroadcast(WeightBroadcast):
def __init__(self, output_dir: Path, config: NIXLWeightBroadcastConfig) -> None:
super().__init__(output_dir)
self.config = config
self.world = get_world()
self.multi_run_manager = get_multi_run_manager()
self.epoch = 0
self.agent: NixlAgent | None = None
self.local_shards: list[_LocalShard] = []
self.manifest: WeightManifest | None = None
self.initialized = False
def _local_candidates(self, model: nn.Module) -> list[_LocalShard]:
local: list[_LocalShard] = []
for name, value in model.state_dict().items():
if isinstance(value, DTensor):
full_shape = tuple(value.shape)
tensor = value.to_local().detach()
local_shape, global_offset = compute_local_shape_and_global_offset(
value.shape,
value._spec.mesh,
value._spec.placements,
)
shape = tuple(local_shape)
offset = tuple(global_offset)
if not shape or shape[0] == 0:
continue
tensor = tensor[tuple(slice(0, size) for size in shape)]
else:
tensor = value.detach()
full_shape = tuple(tensor.shape)
if not full_shape or full_shape[0] == 0:
continue
shape = full_shape
offset = (0,) * len(full_shape)
candidate = ShardCandidate(
rank=self.world.rank,
name=name,
dtype=SERVING_DTYPE,
full_shape=full_shape,
global_offset=offset,
shape=shape,
address=tensor.data_ptr(),
device_id=tensor.device.index or 0,
)
local.append(_LocalShard(candidate, tensor))
return local
def _all_gather_objects(self, value):
gathered = [None] * self.world.world_size
dist.all_gather_object(gathered, value)
return gathered
@torch.no_grad()
def _initialize(self, model: nn.Module) -> None:
if self.initialized:
return
if not isinstance(model, PreTrainedModelPrimeRL):
raise TypeError("NIXL weight broadcast requires a PrimeRL model with a declarative conversion chain")
epoch_box = [uuid.uuid4().int & ((1 << 63) - 1) if self.world.is_master else 0]
dist.broadcast_object_list(epoch_box, src=0)
self.epoch = epoch_box[0]
local = self._local_candidates(model)
candidate_groups = self._all_gather_objects(tuple(shard.candidate for shard in local))
all_candidates = tuple(candidate for group in candidate_groups for candidate in group)
selected = select_shard_owners(all_candidates)
selected_keys = {(
candidate.rank,
candidate.name,
candidate.global_offset,
candidate.shape,
) for candidate in selected}
self.local_shards = [shard for shard in local if shard.key in selected_keys]
agent_payload = None
if self.local_shards:
device = torch.device("cuda", torch.cuda.current_device())
configure_ucx(device.index or 0)
self.agent = NixlAgent(agent_name("trainer", self.world.rank, f"{self.config.session_id}-{self.epoch}"))
registered: set[tuple[int, int]] = set()
for shard in self.local_shards:
shard.allocate(device)
shard.refresh()
assert shard.buffer is not None
region = (shard.buffer.data_ptr(), shard.buffer.numel() * shard.buffer.element_size())
if region not in registered:
self.agent.register_tensor(shard.buffer)
registered.add(region)
torch.cuda.synchronize(device)
agent_payload = (
self.world.rank,
AgentDescriptor(self.agent.name, self.agent.metadata()),
tuple(shard.finalized_candidate() for shard in self.local_shards),
)
agent_groups = self._all_gather_objects(agent_payload)
if self.world.is_master:
active = sorted((payload for payload in agent_groups if payload is not None), key=lambda payload: payload[0])
agents = tuple(payload[1] for payload in active)
rank_to_agent = {payload[0]: index for index, payload in enumerate(active)}
finalized = tuple(candidate for payload in active for candidate in payload[2])
sources = select_source_tensors(finalized, rank_to_agent)
tensors = publish_hf_tensors(model, sources)
fingerprint = sha256(msgspec.msgpack.encode(tensors)).hexdigest()
self.manifest = WeightManifest(
session_id=self.config.session_id,
epoch=self.epoch,
model=self.config.model_name,
fingerprint=fingerprint,
agents=agents,
tensors=tensors,
)
MxChannel(
f"{self.config.host}:{self.config.port}",
self.config.session_id,
self.config.model_name,
"trainer",
"manifest",
0,
).publish(encode_manifest(self.manifest))
self.logger.info(
f"Published {len(tensors)} HF logical tensors over {len(agents)} trainer NIXL agents"
)
self.initialized = True
@torch.no_grad()
def broadcast_weights(self, model: nn.Module, step: int) -> None:
started = time.perf_counter()
self._initialize(model)
for shard in self.local_shards:
shard.refresh()
if self.local_shards:
torch.cuda.synchronize()
dist.barrier()
if self.world.is_master:
assert self.manifest is not None
signal = SyncSignal(
session_id=self.config.session_id,
epoch=self.epoch,
step=step,
phase="trainer_ready",
rank=0,
fingerprint=self.manifest.fingerprint,
)
channel = MxChannel(
f"{self.config.host}:{self.config.port}",
self.config.session_id,
self.config.model_name,
"trainer",
"sync",
0,
)
channel.publish(encode_signal(signal))
def applied(payload: bytes) -> bool:
candidate = decode_signal(payload)
return (
candidate.session_id == signal.session_id
and candidate.epoch == signal.epoch
and candidate.step == signal.step
and candidate.phase == "inference_applied"
and candidate.fingerprint == signal.fingerprint
)
channel.wait_for(
"inference",
"sync",
self.config.inference_world_size,
applied,
self.config.timeout,
)
for index in self.multi_run_manager.used_idxs:
self.multi_run_manager.ready_to_update[index] = False
dist.barrier()
self.logger.info(f"NIXL weight update v{step} completed in {time.perf_counter() - started:.2f}s")
+6 -2
View File
@@ -272,7 +272,11 @@ def train(config: TrainerConfig):
# 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":
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,7 +581,7 @@ def train(config: TrainerConfig):
broadcast_weights_time = 0
else:
nccl_broadcast_unused = (
config.weight_broadcast.type == "nccl"
config.weight_broadcast.type in ("nccl", "nixl")
and config.max_steps is not None
and progress.step >= config.max_steps - 1
)
+11 -7
View File
@@ -434,7 +434,7 @@ async def update_weights(
_admin_post(
admin_client,
"/update_weights",
json={"weight_dir": weight_dir_posix},
json={"weight_dir": weight_dir_posix, "step": step},
timeout_s=UPDATE_WEIGHTS_TIMEOUT_S,
)
for admin_client in admin_clients
@@ -512,15 +512,17 @@ async def unload_lora_adapter(admin_clients: list[AsyncClient], lora_name: str)
await asyncio.gather(*[_unload_lora_adapter(admin_client) for admin_client in admin_clients])
async def init_nccl_broadcast(
async def init_weight_broadcast(
admin_clients: list[AsyncClient],
host: str,
port: int,
timeout: int,
inference_world_size: int | None = None,
quantize_in_weight_transfer: bool = False,
session_id: str = "",
model_name: str = "",
) -> None:
"""Initialize NCCL broadcast on all inference servers.
"""Initialize a live weight-transfer backend on all inference servers.
Each admin client represents one vLLM server. The function computes
per-server rank_offset and gpus_per_server so that every inference GPU
@@ -537,11 +539,11 @@ async def init_nccl_broadcast(
gpus_per_server = inference_world_size // len(admin_clients)
logger.info(
f"Initializing NCCL broadcast: {len(admin_clients)} servers, "
f"Initializing weight broadcast: {len(admin_clients)} servers, "
f"inference_world_size={inference_world_size}, gpus_per_server={gpus_per_server}"
)
async def _init_nccl_broadcast(admin_client: AsyncClient, rank_offset: int) -> None:
async def _init_weight_broadcast(admin_client: AsyncClient, rank_offset: int) -> None:
try:
response = await admin_client.post(
"/init_broadcaster",
@@ -552,17 +554,19 @@ async def init_nccl_broadcast(
"inference_world_size": inference_world_size,
"timeout": timeout,
"quantize_in_weight_transfer": quantize_in_weight_transfer,
"session_id": session_id,
"model_name": model_name,
},
)
response.raise_for_status()
except httpx.HTTPStatusError as e:
if e.response.status_code == 404:
logger.warning("The route /init_broadcaster does not exist. Skipping NCCL broadcast initialization.")
logger.warning("The route /init_broadcaster does not exist. Skipping weight broadcast initialization.")
return
await asyncio.gather(
*[
_init_nccl_broadcast(admin_client, client_num * gpus_per_server)
_init_weight_broadcast(admin_client, client_num * gpus_per_server)
for client_num, admin_client in enumerate(admin_clients)
]
)
+180
View File
@@ -0,0 +1,180 @@
"""Op chains: the slice language produced by the lazy-tensor bake.
During the bake, vLLM's weight loaders run against zero-storage
:class:`~prime_rl.weight_transfer.lazy.LazyWeight` placeholders and each
allowlisted view/slice op is recorded as an :data:`OpSpec`. The worker then
*resolves* every recorded chain into a strided region of the trainer's
published source tensor, so the slice can be pulled with raw RDMA READs —
no replay, no staging, no conversion.
Ops are restricted to a closed allowlist of pure view / shape ops so a chain
can never compute on (and silently corrupt) weight data. Anything outside the
allowlist raises during the bake — loud failure over wrong bytes.
"""
from __future__ import annotations
from typing import Any
import torch
# A single recorded op: (op_name, positional_args, kwargs).
OpSpec = tuple[str, tuple[Any, ...], dict[str, Any]]
OpChain = tuple[OpSpec, ...]
# torch.Tensor methods that map to pure-view / shape-only operations. Every
# entry maps `torch.Tensor.fn` to the name used to reach the method via
# getattr on resolution. Anything that escapes this set (arithmetic,
# .to/.float, .item, .data, bool-mask indexing) raises during the bake.
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",
}
SUPPORTED_OP_NAMES = frozenset(SUPPORTED_OPS.values())
# Bound on RDMA descriptors for a single recorded copy. A region whose
# innermost dimension is non-contiguous decomposes into per-element runs;
# this cap turns that pathology into a loud error instead of a transfer
# plan with millions of descriptors.
MAX_RUNS_PER_COPY = 1 << 16
class UnsupportedOpError(NotImplementedError):
"""A weight loader used an op (or op argument) outside the allowlist."""
def apply_chain(tensor: torch.Tensor, ops: OpChain) -> torch.Tensor:
"""Apply a recorded op chain to a tensor.
Multi-return ops (``chunk``) yield a tuple; the recorded chain always
follows them with an integer ``__getitem__``, which plain ``getattr``
dispatch handles on the tuple as well.
"""
result: Any = tensor
for name, args, kwargs in ops:
if name not in SUPPORTED_OP_NAMES:
raise UnsupportedOpError(f"op {name!r} is not in the supported op set {sorted(SUPPORTED_OP_NAMES)}")
result = getattr(result, name)(*args, **kwargs)
if not isinstance(result, torch.Tensor):
raise UnsupportedOpError(f"op chain produced a non-tensor ({type(result).__name__})")
return result
def resolve_chain_region(
shape: tuple[int, ...], dtype: torch.dtype, ops: OpChain
) -> tuple[int, tuple[int, ...], tuple[int, ...]]:
"""Resolve an op chain to a strided region of its root tensor.
Simulates the chain on a meta tensor and verifies the result is still a
*view* of the root (shares its zero-byte storage). Returns
``(storage_offset_elems, shape, stride)`` of the resulting view. A chain
that breaks view-ness (e.g. ``contiguous()`` on a non-contiguous
intermediate, which would allocate) cannot be expressed as raw RDMA over
the source tensor and raises.
"""
root = torch.empty(shape, dtype=dtype, device="meta")
result = apply_chain(root, ops)
if result is not root and result._base is not root:
raise UnsupportedOpError(
f"op chain {ops!r} on shape {shape} does not resolve to a view of the source tensor "
"(an op materialized a copy); this loader cannot be served by RDMA pulls"
)
return result.storage_offset(), tuple(result.shape), tuple(result.stride())
def region_elem_runs(
offset_elems: int,
shape: tuple[int, ...],
stride: tuple[int, ...],
) -> list[tuple[int, int]]:
"""Decompose a strided region into ``(elem_offset, num_elems)`` runs.
Runs are emitted in C iteration order of the region, i.e. the element
order of a ``.contiguous()`` materialization of the same logical tensor.
Two regions of one ``copy_`` (source and destination) therefore produce
byte streams that correspond element by element. Offsets are in element
units relative to the root tensor's storage origin, addresses left to the
caller (the source tensor is sharded; the destination is a live view).
"""
numel = 1
for s in shape:
numel *= s
if numel == 0:
return []
dims = [(s, st) for s, st in zip(shape, stride) if s != 1]
if any(st < 0 for _, st in dims):
raise UnsupportedOpError("negative strides are not supported for RDMA regions")
if not dims:
return [(offset_elems, 1)]
# Fold the contiguous suffix of dims into one run.
run_elems = 1
k = len(dims)
while k > 0 and dims[k - 1][1] == run_elems:
run_elems *= dims[k - 1][0]
k -= 1
outer = dims[:k]
num_runs = 1
for size, _ in outer:
num_runs *= size
if num_runs > MAX_RUNS_PER_COPY:
raise UnsupportedOpError(
f"region of shape {shape} / stride {stride} decomposes into {num_runs} runs (max {MAX_RUNS_PER_COPY})"
)
runs: list[tuple[int, int]] = []
def emit(dim: int, offset: int) -> None:
if dim == len(outer):
runs.append((offset, run_elems))
return
size, stride_ = outer[dim]
for i in range(size):
emit(dim + 1, offset + i * stride_)
emit(0, offset_elems)
return runs
def tensor_runs(view: torch.Tensor) -> list[tuple[int, int]]:
"""``(device_addr, num_bytes)`` runs for a live tensor view, in C order."""
esize = view.element_size()
base = view.data_ptr()
return [(base + off * esize, n * esize) for off, n in region_elem_runs(0, tuple(view.shape), tuple(view.stride()))]
def match_runs(src_runs: list[tuple[int, int]], dst_runs: list[tuple[int, int]]) -> list[tuple[int, int, int]]:
"""Zip two run decompositions of the same byte stream into transfer pairs.
Returns ``(src_addr, dst_addr, num_bytes)`` triples, splitting runs at
each other's boundaries. Both inputs must cover the same total length.
"""
pairs: list[tuple[int, int, int]] = []
i = j = 0
src_off = dst_off = 0
while i < len(src_runs) and j < len(dst_runs):
length = min(src_runs[i][1] - src_off, dst_runs[j][1] - dst_off)
pairs.append((src_runs[i][0] + src_off, dst_runs[j][0] + dst_off, length))
src_off += length
dst_off += length
if src_off == src_runs[i][1]:
i += 1
src_off = 0
if dst_off == dst_runs[j][1]:
j += 1
dst_off = 0
if i != len(src_runs) or j != len(dst_runs):
raise ValueError(f"run length mismatch: src={sum(n for _, n in src_runs)}B dst={sum(n for _, n in dst_runs)}B")
return pairs
+98
View File
@@ -0,0 +1,98 @@
"""Classic ``cudaMalloc``-backed CUDA MemPool for NIXL-registered buffers.
With ``PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True"`` (the default in
the prime-rl trainer SLURM templates) PyTorch's caching allocator hands out
VMM-backed (``cuMemCreate`` + ``cuMemMap``) virtual ranges. ``ibv_reg_mr``
on such ranges succeeds, but the mlx5 HCA's MMU walk at WRITE time fails
with ``syndrome 0x4`` ("Local protection"), because ``nvidia_peermem``'s
``get_pages`` cannot pin a VA that spans multiple ``cuMemCreate`` handles.
UCX tears the endpoint down and NIXL surfaces it as ``REMOTE_DISCONNECT``.
Tensors handed to ``nixl_agent.register_memory`` must therefore come from a
classic, contiguous ``cudaMalloc`` block. This module exposes a ``MemPool``
backed by a ``CUDAPluggableAllocator`` calling ``cudaMalloc``/``cudaFree``
directly, plus :func:`classic_cuda_alloc` to scope specific allocations into
the pool. Everything else in the process keeps using the default caching
allocator.
"""
from __future__ import annotations
import ctypes
from contextlib import contextmanager
from pathlib import Path
from typing import Iterator
# TileLang ships a libcudart stub that proxies to the real CUDA runtime via
# dlsym(RTLD_DEFAULT, ...). If the stub's own symbols are found first
# (nothing has loaded the real libcudart globally yet) its self-check fails
# and the stub aborts — which is what we hit the moment we enter the
# classic-cudaMalloc MemPool. Preloading the real library with RTLD_GLOBAL
# makes dlsym find it first.
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
_SOURCE = r"""
#include <cuda_runtime.h>
#include <cstddef>
extern "C" {
void* prime_rl_classic_alloc(ptrdiff_t size, int device, void* stream) {
(void) stream;
int prev = -1;
cudaGetDevice(&prev);
cudaSetDevice(device);
void* ptr = nullptr;
cudaError_t err = cudaMalloc(&ptr, (size_t) size);
if (prev >= 0) cudaSetDevice(prev);
if (err != cudaSuccess) return nullptr;
return ptr;
}
void prime_rl_classic_free(void* ptr, ptrdiff_t size, int device, void* stream) {
(void) size; (void) stream;
int prev = -1;
cudaGetDevice(&prev);
cudaSetDevice(device);
cudaFree(ptr);
if (prev >= 0) cudaSetDevice(prev);
}
}
"""
_pool: "torch.cuda.MemPool | None" = None
_allocator_wrapper: "torch.cuda.memory.CUDAPluggableAllocator | None" = None
def _get_pool() -> "torch.cuda.MemPool":
global _pool, _allocator_wrapper
if _pool is not None:
return _pool
module = load_inline(
name="prime_rl_classic_cuda_alloc",
cpp_sources=[_SOURCE],
functions=[],
extra_cflags=["-O2"],
with_cuda=True,
)
so_path = Path(module.__file__)
_allocator_wrapper = torch.cuda.memory.CUDAPluggableAllocator(
str(so_path), "prime_rl_classic_alloc", "prime_rl_classic_free"
)
_pool = torch.cuda.MemPool(_allocator_wrapper.allocator())
return _pool
@contextmanager
def classic_cuda_alloc() -> Iterator[None]:
"""Scope CUDA allocations into the classic-``cudaMalloc`` MemPool.
Use when the resulting tensor's address must be a contiguous
``cudaMalloc`` block — currently only the NIXL-registered staging buffers.
"""
pool = _get_pool()
with torch.cuda.use_mem_pool(pool):
yield
+207
View File
@@ -0,0 +1,207 @@
"""Zero-storage lazy weight placeholders for the NIXL bake.
Mimics the lazy-tensor mechanism of vLLM PR #43375 (sharded RDT weight
transfer): a *recording dry run* through vLLM's own layerwise-reload path.
``model.load_weights`` is driven once with one :class:`LazyWeight` per HF
checkpoint tensor; vLLM's loaders (fused QKV, merged gate/up, FusedMoE expert
routing) call their usual ``narrow``/``view``/``__getitem__``/... on the
placeholder — each op is appended to the placeholder's chain — and finally
``copy_`` it into a view of a (meta) parameter. That ``copy_`` is the
recording sink: it captures the source op chain plus the destination's owning
``(module, param_name)`` and its ``offset/shape/stride``, and moves no data.
The destination is recorded against the param layout that exists at *load*
time — i.e. before ``process_weights_after_loading``. For an online-fp8 model
that layout is bf16, so per sync the worker materializes bf16 params, fills
them with the pulled slices, and re-runs ``process_weights_after_loading`` to
re-quantize to fp8 — exactly as a normal vLLM weight reload.
Any op outside the allowlist (arithmetic, ``.to``/``.float``, ``.item``,
``.data``, bool-mask indexing) raises :class:`UnsupportedOpError` — a loud
failure instead of silently transferring the wrong bytes.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Callable
import torch
from prime_rl.weight_transfer.chains import SUPPORTED_OPS, OpChain, OpSpec, UnsupportedOpError
@dataclass
class RecordedCopy:
"""One recorded ``copy_``: the source slice ``apply_chain(src_name, ops)``
lands in ``param_name`` of ``layer`` at the strided destination
``(offset, shape, stride)`` (captured from the meta destination view, valid
without storage)."""
src_name: str
ops: OpChain
layer: Any
param_name: str
offset: int
shape: tuple[int, ...]
stride: tuple[int, ...]
@dataclass
class BakeRecorder:
"""Collects every ``copy_`` issued during one dry-run ``load_weights`` pass.
``current`` is the ``(module, param_name)`` stamp the engine sets around
each param's loader so the lazy ``copy_`` can attribute its destination; a
``copy_`` with no stamp is left unattributed (its group falls back)."""
copies: list[RecordedCopy] = field(default_factory=list)
current: "tuple[Any, str] | None" = None
class LazyWeight(torch.Tensor):
"""Zero-storage tensor that records how a weight slice is consumed.
Built via ``_make_wrapper_subclass`` so ``.shape``/``.dtype``/``.device``/
``.size()``/``.dim()`` work without allocating storage. Every supported op
returns a child ``LazyWeight`` with the op appended to its chain; ``copy_``
with a lazy source records a :class:`RecordedCopy` on the shared
:class:`BakeRecorder` and performs no data movement.
"""
_name: str
_ops: OpChain
_recorder: BakeRecorder
@staticmethod
def __new__(
cls,
name: str,
shape: torch.Size,
dtype: torch.dtype,
device: torch.device,
recorder: BakeRecorder,
ops: OpChain = (),
) -> "LazyWeight":
t = torch.Tensor._make_wrapper_subclass(
cls,
shape,
dtype=dtype,
device=device,
requires_grad=False,
)
t._name = name
t._ops = tuple(ops)
t._recorder = recorder
return t
def __repr__(self) -> str: # noqa: D105 — repr must not touch storage
return f"LazyWeight(name={self._name!r}, shape={tuple(self.shape)}, dtype={self.dtype}, ops={self._ops!r})"
@property
def source_name(self) -> str:
return self._name
@property
def op_chain(self) -> OpChain:
return self._ops
def _make_child(self, new_shape: torch.Size, new_dtype: torch.dtype, *new_ops: OpSpec) -> "LazyWeight":
return LazyWeight(
name=self._name,
shape=new_shape,
dtype=new_dtype,
device=self.device,
recorder=self._recorder,
ops=self._ops + new_ops,
)
def _meta(self) -> torch.Tensor:
"""A meta tensor of this lazy's shape/dtype, used to infer post-op
shapes via PyTorch itself instead of reimplementing shape rules."""
return torch.empty(self.shape, dtype=self.dtype, device="meta")
@classmethod
def __torch_function__(cls, func, types, args=(), kwargs=None):
kwargs = kwargs or {}
# copy_ with a lazy source is the recording sink.
if func is torch.Tensor.copy_:
dst = args[0]
src = args[1] if len(args) > 1 else kwargs.get("src")
if isinstance(src, cls):
if isinstance(dst, cls):
raise UnsupportedOpError(f"copy_ between two lazy weights ({src._name!r} -> {dst._name!r})")
if tuple(dst.shape) != tuple(src.shape):
raise UnsupportedOpError(
f"copy_ shape mismatch for {src._name!r}: src {tuple(src.shape)} vs dst {tuple(dst.shape)}"
)
current = src._recorder.current
if current is not None:
layer, param_name = current
src._recorder.copies.append(
RecordedCopy(
src_name=src._name,
ops=src._ops,
layer=layer,
param_name=param_name,
offset=dst.storage_offset(),
shape=tuple(dst.shape),
stride=tuple(dst.stride()),
)
)
# Fire a meta copy_ so layerwise's load-numel counter still
# advances (otherwise the layer never reaches "fully loaded").
meta_src = torch.empty(src.shape, dtype=src.dtype, device="meta")
with torch._C.DisableTorchFunctionSubclass():
return dst.copy_(meta_src)
# Allowlisted view/slice/shape ops: append to the chain, return a child.
op_name = SUPPORTED_OPS.get(func)
if op_name is not None:
self_ = args[0]
if isinstance(self_, cls):
return cls._intercept(self_, func, op_name, tuple(args[1:]), kwargs)
# Everything else falls through. Pure metadata reads (.shape, .size(),
# .dim(), .numel()) never reach dispatch because the wrapper subclass
# stored them at construction; ops that need data land in
# __torch_dispatch__ below and raise.
with torch._C.DisableTorchFunctionSubclass():
return func(*args, **kwargs)
@classmethod
def _intercept(cls, self_: "LazyWeight", func: Callable, op_name: str, args: tuple, kwargs: dict):
"""Append the op and return a child (or tuple of children for chunk)."""
meta = self_._meta()
with torch._C.DisableTorchFunctionSubclass():
meta_result = func(meta, *args, **kwargs)
base_op: OpSpec = (op_name, args, dict(kwargs))
if isinstance(meta_result, torch.Tensor):
return self_._make_child(meta_result.shape, meta_result.dtype, base_op)
# Multi-return ops (chunk): one child per output, each chain followed
# by an integer __getitem__ so the replay can index the tuple result.
if isinstance(meta_result, (tuple, list)):
return tuple(
self_._make_child(m.shape, m.dtype, base_op, ("__getitem__", (i,), {}))
for i, m in enumerate(meta_result)
)
raise UnsupportedOpError(f"op {op_name!r} returned a non-tensor ({type(meta_result).__name__}); cannot defer")
@classmethod
def __torch_dispatch__(cls, func, types, args=(), kwargs=None):
kwargs = kwargs or {}
for value in list(args) + list(kwargs.values()):
if isinstance(value, cls):
raise UnsupportedOpError(
f"unsupported op {func} reached __torch_dispatch__ on lazy weight "
f"{value._name!r} (chain={value._ops!r}). Supported ops: "
f"{sorted(set(SUPPORTED_OPS.values()))}, plus copy_ as the sink. "
"Loaders that need .to(), .float(), .item(), arithmetic, bool-mask "
"indexing, or .data access are not supported by the NIXL weight broadcast."
)
return func(*args, **kwargs)
+83
View File
@@ -0,0 +1,83 @@
"""Session-scoped metadata and synchronization channels over ModelExpress."""
from __future__ import annotations
import time
from dataclasses import dataclass
from typing import Callable, Literal
from modelexpress import p2p_pb2
from modelexpress.client import MxClient
Role = Literal["trainer", "inference", "orchestrator"]
@dataclass
class MxChannel:
server_url: str
session_id: str
model: str
role: Role
channel: str
rank: int
def __post_init__(self) -> None:
self.client = MxClient(server_url=self.server_url)
self.worker_id = f"{self.session_id}:{self.role}:{self.channel}:{self.rank}"
self._source_id: str | None = None
def _identity(self, role: Role, channel: str) -> p2p_pb2.SourceIdentity:
return p2p_pb2.SourceIdentity(
mx_version="0.3.0",
mx_source_type=p2p_pb2.MX_SOURCE_TYPE_WEIGHTS,
model_name=self.model,
backend_framework=p2p_pb2.BACKEND_FRAMEWORK_VLLM,
dtype="bfloat16",
extra_parameters={
"session_id": self.session_id,
"role": role,
"channel": channel,
},
)
def publish(self, payload: bytes) -> str:
worker = p2p_pb2.WorkerMetadata(worker_rank=self.rank, nixl_metadata=payload)
self._source_id = self.client.publish_metadata(
self._identity(self.role, self.channel),
worker,
self.worker_id,
)
return self._source_id
def payloads(self, role: Role, channel: str) -> dict[int, bytes]:
refs = self.client.list_sources(self._identity(role, channel)).instances
payloads: dict[int, bytes] = {}
for ref in refs:
response = self.client.get_metadata(ref.mx_source_id, ref.worker_id)
if response.found:
payloads[response.worker.worker_rank] = response.worker.nixl_metadata
return payloads
def wait_for(
self,
role: Role,
channel: str,
expected: int,
predicate: Callable[[bytes], bool],
timeout: float,
poll_interval: float = 0.05,
) -> dict[int, bytes]:
deadline = time.monotonic() + timeout
while True:
matched = {rank: payload for rank, payload in self.payloads(role, channel).items() if predicate(payload)}
if len(matched) == expected:
return matched
if len(matched) > expected:
raise RuntimeError(
f"ModelExpress channel {role}/{channel} returned {len(matched)} matches; expected {expected}"
)
if time.monotonic() >= deadline:
raise TimeoutError(
f"timed out waiting for {expected} messages on {role}/{channel}; received {len(matched)}"
)
time.sleep(poll_interval)
+103
View File
@@ -0,0 +1,103 @@
"""Small NIXL adapter used by the pull-based weight-transfer backend."""
from __future__ import annotations
import os
import socket
import time
from typing import Any, Sequence
from torch import Tensor
MemoryDescriptor = tuple[int, int, int]
class NixlAgent:
def __init__(self, name: str, backends: Sequence[str] = ("UCX",)) -> None:
from nixl._api import nixl_agent, nixl_agent_config
self.name = name
self.backends = tuple(backends)
self._agent = nixl_agent(name, nixl_agent_config(backends=list(self.backends)))
def register_tensor(self, tensor: Tensor) -> None:
if not tensor.is_cuda or not tensor.is_contiguous():
raise ValueError(
f"NIXL source tensors must be contiguous CUDA tensors, got device={tensor.device}, "
f"shape={tuple(tensor.shape)}, stride={tuple(tensor.stride())}"
)
self._agent.register_memory(tensor, backends=list(self.backends))
def 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 connect(self, remote_name: str) -> None:
self._agent.make_connection(remote_name)
def prepare_local(self, descriptors: Sequence[MemoryDescriptor]) -> Any:
return self._agent.prep_xfer_dlist(
agent_name="",
xfer_list=list(descriptors),
mem_type="cuda",
backends=list(self.backends),
)
def prepare_remote(self, remote_name: str, descriptors: Sequence[MemoryDescriptor]) -> Any:
return self._agent.prep_xfer_dlist(
agent_name=remote_name,
xfer_list=list(descriptors),
mem_type="cuda",
backends=list(self.backends),
)
def read(
self,
local_descriptors: Any,
local_indices: Sequence[int],
remote_descriptors: Any,
remote_indices: Sequence[int],
) -> Any:
handle = self._agent.make_prepped_xfer(
operation="READ",
local_xfer_side=local_descriptors,
local_indices=list(local_indices),
remote_xfer_side=remote_descriptors,
remote_indices=list(remote_indices),
backends=list(self.backends),
)
state = self._agent.transfer(handle)
if state in {"ERR", "ERROR", "FAIL"}:
raise RuntimeError(f"NIXL READ submission failed with state {state}")
return handle
def wait(self, handle: Any, context: str = "") -> None:
while True:
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}")
time.sleep(0.0005)
def agent_name(role: str, rank: int, session_id: str) -> str:
return f"prime-rl-{session_id}-{role}-{socket.gethostname()}-{rank}"
def configure_ucx(local_device: int) -> None:
"""Apply topology-aware NIC pinning without overriding operator settings."""
from modelexpress.ucx_utils import apply_nic_pin_for_device
apply_nic_pin_for_device(local_device)
os.environ.setdefault("UCX_TLS", "rc_mlx5,ud,cuda_copy")
os.environ.setdefault("UCX_IB_GPU_DIRECT_RDMA", "y")
os.environ.setdefault("UCX_RNDV_SCHEME", "put_zcopy")
os.environ.setdefault("UCX_RNDV_THRESH", "8192")
os.environ.setdefault("UCX_MEMTYPE_CACHE", "n")
os.environ.setdefault("UCX_WARN_UNUSED_ENV_VARS", "n")
+109
View File
@@ -0,0 +1,109 @@
"""Select one serving owner for replicated trainer tensor shards."""
from __future__ import annotations
from dataclasses import dataclass
from hashlib import sha256
import torch
from prime_rl.weight_transfer.publication import SourceTensor
from prime_rl.weight_transfer.sharding import SourceShard, validate_dim0_shards
@dataclass(frozen=True)
class ShardCandidate:
"""A local trainer tensor region that a rank can expose through NIXL."""
rank: int
name: str
dtype: torch.dtype
full_shape: tuple[int, ...]
global_offset: tuple[int, ...]
shape: tuple[int, ...]
address: int
device_id: int
@property
def region(self) -> tuple[tuple[int, ...], tuple[int, ...]]:
return self.global_offset, self.shape
def _choose_owner(name: str, region: tuple[tuple[int, ...], tuple[int, ...]], candidates: list[ShardCandidate]):
ordered = sorted(candidates, key=lambda candidate: candidate.rank)
digest = sha256(f"{name}:{region}".encode()).digest()
return ordered[int.from_bytes(digest[:8], "big") % len(ordered)]
def select_shard_owners(candidates: tuple[ShardCandidate, ...]) -> tuple[ShardCandidate, ...]:
"""Deduplicate replicas and select a deterministic serving rank per region.
HSDP, CP, and replicated parameters can produce several candidates for the
same logical region. Exactly one owner is selected deterministically, with
different regions spread across available ranks. Trainer and inference
topology are intentionally absent from this decision.
"""
by_tensor: dict[str, list[ShardCandidate]] = {}
for candidate in candidates:
by_tensor.setdefault(candidate.name, []).append(candidate)
selected_all: list[ShardCandidate] = []
for name, tensor_candidates in sorted(by_tensor.items()):
first = tensor_candidates[0]
for candidate in tensor_candidates[1:]:
if candidate.dtype != first.dtype or candidate.full_shape != first.full_shape:
raise ValueError(
f"inconsistent source metadata for {name!r}: "
f"{first.dtype}/{first.full_shape} != {candidate.dtype}/{candidate.full_shape}"
)
by_region: dict[tuple[tuple[int, ...], tuple[int, ...]], list[ShardCandidate]] = {}
for candidate in tensor_candidates:
by_region.setdefault(candidate.region, []).append(candidate)
selected = [_choose_owner(name, region, replicas) for region, replicas in sorted(by_region.items())]
validation_shards = tuple(
SourceShard(
agent=candidate.rank,
global_offset=candidate.global_offset,
shape=candidate.shape,
address=candidate.address,
device_id=candidate.device_id,
)
for candidate in selected
)
validate_dim0_shards(first.full_shape, validation_shards)
selected_all.extend(selected)
return tuple(selected_all)
def select_source_tensors(
candidates: tuple[ShardCandidate, ...], rank_to_agent: dict[int, int]
) -> tuple[SourceTensor, ...]:
"""Build logical source tensors from the selected registered candidates."""
selected = select_shard_owners(candidates)
by_tensor: dict[str, list[ShardCandidate]] = {}
for candidate in selected:
by_tensor.setdefault(candidate.name, []).append(candidate)
sources: list[SourceTensor] = []
for name, tensor_candidates in sorted(by_tensor.items()):
first = tensor_candidates[0]
shards: list[SourceShard] = []
for candidate in tensor_candidates:
if candidate.rank not in rank_to_agent:
raise KeyError(f"selected trainer rank {candidate.rank} has no published NIXL agent")
shards.append(
SourceShard(
agent=rank_to_agent[candidate.rank],
global_offset=candidate.global_offset,
shape=candidate.shape,
address=candidate.address,
device_id=candidate.device_id,
)
)
sources.append(SourceTensor(name, first.dtype, first.full_shape, tuple(shards)))
return tuple(sources)
+162
View File
@@ -0,0 +1,162 @@
"""Build HF logical weights directly over sharded Prime trainer storage."""
from __future__ import annotations
from dataclasses import dataclass
from math import prod
from typing import Protocol
import torch
from prime_rl.weight_transfer.chains import region_elem_runs, resolve_chain_region
from prime_rl.weight_transfer.lazy import BakeRecorder, LazyWeight
from prime_rl.weight_transfer.sharding import SourceShard, route_source_region
from prime_rl.weight_transfer.wire import PublishedTensor, TensorSegment
class WeightConverter(Protocol):
def convert_to_hf(self, state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]: ...
@dataclass(frozen=True)
class SourceTensor:
"""A full logical Prime tensor backed by selected trainer shards."""
name: str
dtype: torch.dtype
shape: tuple[int, ...]
shards: tuple[SourceShard, ...]
def _coalesce_segments(segments: list[TensorSegment], itemsize: int) -> tuple[TensorSegment, ...]:
coalesced: list[TensorSegment] = []
for segment in segments:
if coalesced:
previous = coalesced[-1]
contiguous = (
previous.agent == segment.agent
and previous.device_id == segment.device_id
and previous.logical_offset + previous.numel == segment.logical_offset
and previous.address + previous.numel * itemsize == segment.address
)
if contiguous:
coalesced[-1] = TensorSegment(
agent=previous.agent,
logical_offset=previous.logical_offset,
numel=previous.numel + segment.numel,
address=previous.address,
device_id=previous.device_id,
)
continue
coalesced.append(segment)
return tuple(coalesced)
def _segments_for_view(source: SourceTensor, view: LazyWeight) -> tuple[TensorSegment, ...]:
itemsize = torch.empty((), dtype=source.dtype).element_size()
offset, shape, stride = resolve_chain_region(source.shape, source.dtype, view.op_chain)
if shape != tuple(view.shape):
raise ValueError(f"symbolic conversion shape mismatch for {view.source_name}: {shape} != {tuple(view.shape)}")
pieces = route_source_region(
region_elem_runs(offset, shape, stride),
source.shape,
source.shards,
itemsize,
)
logical_offset = 0
segments: list[TensorSegment] = []
for agent, address, num_bytes, device_id in pieces:
if num_bytes % itemsize:
raise ValueError(f"unaligned source segment for {view.source_name}: {num_bytes} bytes")
numel = num_bytes // itemsize
segments.append(
TensorSegment(
agent=agent,
logical_offset=logical_offset,
numel=numel,
address=address,
device_id=device_id,
)
)
logical_offset += numel
if logical_offset != prod(view.shape):
raise ValueError(
f"published segments for {view.source_name} cover {logical_offset} elements; expected {prod(view.shape)}"
)
return _coalesce_segments(segments, itemsize)
def publish_hf_tensors(converter: WeightConverter, sources: tuple[SourceTensor, ...]) -> tuple[PublishedTensor, ...]:
"""Run the real Prime->HF conversion chain symbolically over source shards.
The result contains HF names and logical shapes, with each logical element
mapped directly to registered trainer memory. No tensor values are read and
no full model tensor is allocated.
"""
recorder = BakeRecorder()
by_name = {source.name: source for source in sources}
if len(by_name) != len(sources):
raise ValueError("source tensor names must be unique")
state_dict: dict[str, torch.Tensor] = {
source.name: LazyWeight(
name=source.name,
shape=torch.Size(source.shape),
dtype=source.dtype,
device=torch.device("meta"),
recorder=recorder,
)
for source in sources
}
converted = converter.convert_to_hf(state_dict)
published: list[PublishedTensor] = []
for name, value in sorted(converted.items()):
if not isinstance(value, LazyWeight):
raise TypeError(
f"Prime->HF conversion for {name!r} materialized {type(value).__name__}; "
"NIXL publication only supports symbolic layout operations"
)
source = by_name.get(value.source_name)
if source is None:
raise KeyError(f"converted tensor {name!r} references unknown source {value.source_name!r}")
published.append(
PublishedTensor(
name=name,
dtype=str(value.dtype),
shape=tuple(value.shape),
segments=_segments_for_view(source, value),
)
)
return tuple(published)
def route_published_region(
tensor: PublishedTensor,
region_runs: list[tuple[int, int]],
itemsize: int,
) -> list[tuple[int, int, int]]:
"""Route logical HF element runs to trainer ``(agent, address, bytes)``."""
segments = sorted(tensor.segments, key=lambda segment: segment.logical_offset)
pieces: list[tuple[int, int, int]] = []
for elem_offset, numel in region_runs:
position = elem_offset
remaining = numel
while remaining:
segment = next(
(
candidate
for candidate in segments
if candidate.logical_offset <= position < candidate.logical_offset + candidate.numel
),
None,
)
if segment is None:
raise ValueError(f"published tensor {tensor.name!r} has no segment for logical element {position}")
within = position - segment.logical_offset
take = min(remaining, segment.numel - within)
pieces.append((segment.agent, segment.address + within * itemsize, take * itemsize))
position += take
remaining -= take
return pieces
+116
View File
@@ -0,0 +1,116 @@
"""Map logical tensor regions onto trainer-owned registered memory."""
from __future__ import annotations
from dataclasses import dataclass
from math import prod
@dataclass(frozen=True)
class SourceShard:
"""One rectangular shard of a full logical Prime tensor.
The wire representation already supports arbitrary source segmentation.
The first implementation accepts only dim-0 shards because current FSDP
and expert-parallel parameters use that layout. Keeping offsets and shapes
as tuples makes extending the planner independent of the wire protocol.
"""
agent: int
global_offset: tuple[int, ...]
shape: tuple[int, ...]
address: int
device_id: int
def validate_dim0_shards(full_shape: tuple[int, ...], shards: tuple[SourceShard, ...]) -> None:
if not full_shape:
raise ValueError("scalar source tensors are not supported")
ordered = sorted(shards, key=lambda shard: shard.global_offset[0])
next_row = 0
for shard in ordered:
if len(shard.shape) != len(full_shape) or len(shard.global_offset) != len(full_shape):
raise ValueError(f"source shard rank does not match full shape {full_shape}: {shard}")
if shard.global_offset[0] != next_row:
raise ValueError(f"dim-0 shards must tile without gaps or overlap; expected row {next_row}: {shard}")
if any(offset != 0 for offset in shard.global_offset[1:]):
raise ValueError(f"only dim-0 source sharding is supported: {shard}")
if shard.shape[1:] != full_shape[1:]:
raise ValueError(f"only dim-0 source sharding is supported: {shard}")
next_row += shard.shape[0]
if next_row != full_shape[0]:
raise ValueError(f"source shards cover {next_row} of {full_shape[0]} dim-0 rows")
def route_source_region(
region_runs: list[tuple[int, int]],
full_shape: tuple[int, ...],
shards: tuple[SourceShard, ...],
itemsize: int,
) -> list[tuple[int, int, int, int]]:
"""Route full-tensor element runs to ``(agent, address, bytes, device)``."""
validate_dim0_shards(full_shape, shards)
row_numel = prod(full_shape[1:])
bounds = [
(
shard.global_offset[0] * row_numel,
(shard.global_offset[0] + shard.shape[0]) * row_numel,
shard,
)
for shard in sorted(shards, key=lambda shard: shard.global_offset[0])
]
pieces: list[tuple[int, int, int, int]] = []
for elem_offset, numel in region_runs:
position = elem_offset
remaining = numel
while remaining:
match = next(((lo, hi, shard) for lo, hi, shard in bounds if lo <= position < hi), None)
if match is None:
raise ValueError(f"no source shard owns logical element {position}")
lower, upper, shard = match
take = min(remaining, upper - position)
address = shard.address + (position - lower) * itemsize
pieces.append((shard.agent, address, take * itemsize, shard.device_id))
position += take
remaining -= take
return pieces
def zip_source_destination(
source: list[tuple[int, int, int]], destination: list[tuple[int, int]]
) -> list[tuple[int, int, int, int]]:
"""Zip source byte pieces with destination byte runs.
Returns ``(agent, source_address, destination_address, num_bytes)``.
"""
units: list[tuple[int, int, int, int]] = []
source_index = destination_index = 0
source_offset = destination_offset = 0
while source_index < len(source) and destination_index < len(destination):
agent, source_address, source_length = source[source_index]
destination_address, destination_length = destination[destination_index]
length = min(source_length - source_offset, destination_length - destination_offset)
units.append(
(
agent,
source_address + source_offset,
destination_address + destination_offset,
length,
)
)
source_offset += length
destination_offset += length
if source_offset == source_length:
source_index += 1
source_offset = 0
if destination_offset == destination_length:
destination_index += 1
destination_offset = 0
source_total = sum(length for _, _, length in source)
destination_total = sum(length for _, length in destination)
if source_total != destination_total or source_index != len(source) or destination_index != len(destination):
raise ValueError(f"source/destination byte mismatch: source={source_total}, destination={destination_total}")
return units
+89
View File
@@ -0,0 +1,89 @@
"""Versioned metadata exchanged for pull-based weight transfer."""
from typing import Literal
import msgspec
PROTOCOL_VERSION = 1
class AgentDescriptor(msgspec.Struct, frozen=True):
"""A trainer-side NIXL agent that owns registered source memory."""
name: str
metadata: bytes
class TensorSegment(msgspec.Struct, frozen=True):
"""A contiguous portion of a logical HF tensor served by one agent.
``logical_offset`` and ``numel`` describe the segment in the tensor's
contiguous logical element stream. ``address`` points at the same elements
in registered trainer memory. Segments need not follow the trainer's
parallel layout; together they must tile the logical tensor exactly once.
"""
agent: int
logical_offset: int
numel: int
address: int
device_id: int
class PublishedTensor(msgspec.Struct, frozen=True):
"""One HF-named tensor exposed to inference consumers."""
name: str
dtype: str
shape: tuple[int, ...]
segments: tuple[TensorSegment, ...]
class WeightManifest(msgspec.Struct, frozen=True):
"""Static, session-scoped description of all pullable model weights."""
session_id: str
epoch: int
model: str
fingerprint: str
agents: tuple[AgentDescriptor, ...]
tensors: tuple[PublishedTensor, ...]
protocol_version: int = PROTOCOL_VERSION
class SyncSignal(msgspec.Struct, frozen=True):
"""Generation-aware control message for one synchronized update."""
session_id: str
epoch: int
step: int
phase: Literal["trainer_ready", "inference_applied"]
rank: int
fingerprint: str
protocol_version: int = PROTOCOL_VERSION
def encode_manifest(manifest: WeightManifest) -> bytes:
return msgspec.msgpack.encode(manifest)
def decode_manifest(data: bytes) -> WeightManifest:
manifest = msgspec.msgpack.decode(data, type=WeightManifest)
if manifest.protocol_version != PROTOCOL_VERSION:
raise ValueError(
f"unsupported weight-transfer protocol {manifest.protocol_version}; expected {PROTOCOL_VERSION}"
)
return manifest
def encode_signal(signal: SyncSignal) -> bytes:
return msgspec.msgpack.encode(signal)
def decode_signal(data: bytes) -> SyncSignal:
signal = msgspec.msgpack.decode(data, type=SyncSignal)
if signal.protocol_version != PROTOCOL_VERSION:
raise ValueError(
f"unsupported weight-transfer protocol {signal.protocol_version}; expected {PROTOCOL_VERSION}"
)
return signal
+6 -8
View File
@@ -63,7 +63,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)
@@ -122,10 +122,9 @@ def test_nemotron_h_reverse():
inject_prime_lm_head(prime_model, chunk_size=None)
with torch.no_grad():
sd = prime_model.state_dict()
NemotronHForCausalLM.convert_to_hf(sd)
# convert_to_hf produces checkpoint format with "backbone." prefix;
# the HF model uses "model." prefix for its state dict
# PrimeRL -> HF (plays the chain backward); convert_to_hf emits the "backbone."
# checkpoint prefix, while the HF model's state dict uses "model.".
sd = prime_model.convert_to_hf(dict(prime_model.state_dict()))
keys_to_rename = [k for k in sd if k.startswith("backbone.")]
for key in keys_to_rename:
sd["model." + key[len("backbone.") :]] = sd.pop(key)
@@ -202,10 +201,9 @@ def test_nemotron_h_weight_conversion_roundtrip():
model = NemotronHForCausalLM(prime_config).to("cuda")
original_sd = {k: v.clone() for k, v in model.state_dict().items()}
sd = model.state_dict()
NemotronHForCausalLM.convert_to_hf(sd)
sd = model.convert_to_hf(dict(model.state_dict()))
assert NemotronHForCausalLM.is_hf_state_dict(sd)
NemotronHForCausalLM.convert_to_prime(sd)
sd = model.convert_to_prime(sd)
assert NemotronHForCausalLM.is_prime_state_dict(sd)
for key in original_sd:
+5 -11
View File
@@ -69,22 +69,16 @@ def test_qwen3_5_moe_roundtrip():
"""Verify HF → PrimeRL → HF weight conversion is lossless at the state_dict level."""
hf_model, prime_model = get_model_pairs()
# Get original HF state_dict and the PrimeRL-converted version
original_hf_sd = hf_model.state_dict()
prime_sd = prime_model.state_dict()
# Convert PrimeRL → per-expert HF format
converted_hf_sd = PrimeRLQwen3_5MoeForCausalLM.convert_to_hf(dict(prime_sd))
# PrimeRL → per-expert HF format (plays the chain backward).
converted_hf_sd = prime_model.convert_to_hf(dict(prime_sd))
# Also convert original HF (fused) to per-expert format for comparison
# Original HF (fused) → PrimeRL → per-expert HF, for a like-for-like comparison.
orig_prime_sd = prime_model.convert_to_prime(dict(original_hf_sd))
orig_roundtripped = prime_model.convert_to_hf(dict(orig_prime_sd))
# 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)
orig_roundtripped = dict(orig_prime_sd)
PrimeRLQwen3_5MoeForCausalLM.convert_to_hf(orig_roundtripped)
# All non-expert keys should match exactly, expert keys should match after roundtrip
for key in orig_roundtripped:
assert key in converted_hf_sd, f"Missing key: {key}"
assert torch.equal(orig_roundtripped[key], converted_hf_sd[key]), f"Mismatch at {key}"
@@ -135,6 +135,7 @@ def test_vlm_weight_load_from_hf():
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFQwen3_5MoeVLM._from_config(config)
prime_model = Qwen3_5MoeForCausalLM(config)
prime_model = Qwen3_5MoeForCausalLM(config)
# Copy weights: HF -> PrimeRL (with MoE conversion)
with torch.no_grad():
@@ -167,19 +168,15 @@ def test_vlm_weight_roundtrip():
original_vision_weight = hf_sd[original_vision_key].clone()
# HF -> PrimeRL
prime_sd = dict(hf_sd)
Qwen3_5MoeForCausalLM.convert_to_prime(prime_sd)
prime_sd = prime_model.convert_to_prime(dict(hf_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)
roundtripped = prime_model.convert_to_hf(dict(prime_sd))
# 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)
# Original HF also needs a roundtrip for expert-format normalization (fused <-> per-expert).
orig_rt = prime_model.convert_to_hf(prime_model.convert_to_prime(dict(hf_sd)))
for key in orig_rt:
assert key in roundtripped, f"Missing key: {key}"
@@ -0,0 +1,147 @@
import ctypes
from types import SimpleNamespace
import torch
from prime_rl.trainer.models.conversion_ops import apply_tt_to_hf
from prime_rl.trainer.models.nemotron_h.converting_nemotron_h import conversion_chain
from prime_rl.weight_transfer.chains import region_elem_runs, resolve_chain_region, tensor_runs
from prime_rl.weight_transfer.lazy import BakeRecorder, LazyWeight
from prime_rl.weight_transfer.ownership import ShardCandidate, select_source_tensors
from prime_rl.weight_transfer.publication import SourceTensor, publish_hf_tensors, route_published_region
from prime_rl.weight_transfer.sharding import SourceShard, zip_source_destination
from prime_rl.weight_transfer.wire import AgentDescriptor, WeightManifest, decode_manifest, encode_manifest
EXPERTS = 4
INTERMEDIATE = 6
HIDDEN = 8
class NemotronConverter:
def __init__(self) -> None:
self.ops = conversion_chain(SimpleNamespace(num_hidden_layers=1))
def convert_to_hf(self, state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
return apply_tt_to_hf(state_dict, self.ops)
def make_source(name: str, tensor: torch.Tensor) -> tuple[SourceTensor, tuple[torch.Tensor, ...]]:
split = (tensor.shape[0] + 1) // 2
buffers = tuple(part.contiguous() for part in tensor.split(split, dim=0))
shards: list[SourceShard] = []
row = 0
for agent, buffer in enumerate(buffers):
shards.append(
SourceShard(
agent=agent,
global_offset=(row,) + (0,) * (tensor.ndim - 1),
shape=tuple(buffer.shape),
address=buffer.data_ptr(),
device_id=0,
)
)
row += buffer.shape[0]
return SourceTensor(name, tensor.dtype, tuple(tensor.shape), tuple(shards)), buffers
def test_nemotron_symbolic_conversion_and_mismatched_expert_pull() -> None:
torch.manual_seed(0)
prime = {
"model.layers.0.mlp.experts.w1": torch.randn(EXPERTS, INTERMEDIATE, HIDDEN, dtype=torch.bfloat16),
"model.layers.0.mlp.experts.w2": torch.randn(EXPERTS, HIDDEN, INTERMEDIATE, dtype=torch.bfloat16),
"model.layers.0.mlp.router.gate": torch.randn(EXPERTS, HIDDEN, dtype=torch.bfloat16),
}
sources: list[SourceTensor] = []
keepalive: list[torch.Tensor] = []
for name, tensor in prime.items():
source, buffers = make_source(name, tensor)
sources.append(source)
keepalive.extend(buffers)
published = publish_hf_tensors(NemotronConverter(), tuple(sources))
by_name = {tensor.name: tensor for tensor in published}
assert "backbone.layers.0.mixer.experts.1.up_proj.weight" in by_name
assert "backbone.layers.0.mixer.experts.3.down_proj.weight" in by_name
assert by_name["backbone.layers.0.mixer.experts.1.up_proj.weight"].segments[0].agent == 0
assert by_name["backbone.layers.0.mixer.experts.3.up_proj.weight"].segments[0].agent == 1
recorder = BakeRecorder()
weights = {
tensor.name: LazyWeight(
tensor.name,
torch.Size(tensor.shape),
torch.bfloat16,
torch.device("cpu"),
recorder,
)
for tensor in published
}
local_experts = {1: 0, 3: 1}
w13_meta = torch.empty(2, INTERMEDIATE, HIDDEN, dtype=torch.bfloat16, device="meta")
w2_meta = torch.empty(2, HIDDEN, INTERMEDIATE, dtype=torch.bfloat16, device="meta")
for global_expert, local_expert in local_experts.items():
up = weights[f"backbone.layers.0.mixer.experts.{global_expert}.up_proj.weight"]
down = weights[f"backbone.layers.0.mixer.experts.{global_expert}.down_proj.weight"]
recorder.current = (object(), "w13")
w13_meta[local_expert].copy_(up)
recorder.current = (object(), "w2")
w2_meta[local_expert].copy_(down)
recorder.current = None
destinations = {
"w13": torch.zeros_like(w13_meta, device="cpu"),
"w2": torch.zeros_like(w2_meta, device="cpu"),
}
for copy in recorder.copies:
tensor = by_name[copy.src_name]
offset, shape, stride = resolve_chain_region(tensor.shape, torch.bfloat16, copy.ops)
source = route_published_region(tensor, region_elem_runs(offset, shape, stride), itemsize=2)
destination = destinations[copy.param_name].as_strided(copy.shape, copy.stride, copy.offset)
for _, source_address, destination_address, num_bytes in zip_source_destination(source, tensor_runs(destination)):
ctypes.memmove(destination_address, source_address, num_bytes)
for global_expert, local_expert in local_experts.items():
assert torch.equal(destinations["w13"][local_expert], prime["model.layers.0.mlp.experts.w1"][global_expert])
assert torch.equal(destinations["w2"][local_expert], prime["model.layers.0.mlp.experts.w2"][global_expert])
def test_manifest_round_trip() -> None:
tensor = torch.arange(16, dtype=torch.bfloat16).reshape(2, 8)
source, keepalive = make_source("model.weight", tensor)
published = publish_hf_tensors(NemotronConverter(), (source,))
manifest = WeightManifest(
session_id="session",
epoch=1,
model="nemotron",
fingerprint="fingerprint",
agents=(AgentDescriptor("trainer-0", b"metadata-0"), AgentDescriptor("trainer-1", b"metadata-1")),
tensors=published,
)
assert decode_manifest(encode_manifest(manifest)) == manifest
assert keepalive
def test_replica_ownership_is_deduplicated_and_balanced() -> None:
candidates: list[ShardCandidate] = []
for name in ("model.a", "model.b"):
for rank in range(4):
row = rank % 2
candidates.append(
ShardCandidate(
rank=rank,
name=name,
dtype=torch.bfloat16,
full_shape=(4, 8),
global_offset=(row * 2, 0),
shape=(2, 8),
address=10_000 * rank + 1_000 * row,
device_id=rank,
)
)
sources = select_source_tensors(tuple(candidates), {rank: rank for rank in range(4)})
assert len(sources) == 2
for source in sources:
assert len(source.shards) == 2
assert {shard.global_offset[0] for shard in source.shards} == {0, 2}
assert len({shard.agent for source in sources for shard in source.shards}) > 1