Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ce65f38fc0 |
@@ -17,7 +17,6 @@ name = "base"
|
||||
type = "nccl"
|
||||
port = 29502
|
||||
timeout = 12000
|
||||
quantize_in_weight_transfer = true
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
@@ -69,7 +68,9 @@ non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
|
||||
"queue-scorer" = 3.0
|
||||
|
||||
[inference.vllm]
|
||||
model = "zai-org/GLM-5.1-FP8"
|
||||
model = "zai-org/GLM-5.1"
|
||||
dtype = "bfloat16"
|
||||
quantization = "fp8_per_block"
|
||||
max_model_len = 131072
|
||||
tool_call_parser = "glm47"
|
||||
reasoning_parser = "glm45"
|
||||
@@ -122,7 +123,7 @@ initial_inflight = 256
|
||||
max_inflight = 512
|
||||
|
||||
[orchestrator.model]
|
||||
name = "zai-org/GLM-5.1-FP8"
|
||||
name = "zai-org/GLM-5.1"
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-5.1"
|
||||
|
||||
@@ -10,7 +10,6 @@ project = "glm5-pd-disag"
|
||||
type = "nccl"
|
||||
port = 29502
|
||||
timeout = 12000
|
||||
quantize_in_weight_transfer = true
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
@@ -24,7 +23,9 @@ prefill_nodes_per_replica = 4
|
||||
decode_nodes_per_replica = 4
|
||||
|
||||
[inference.vllm]
|
||||
model = "zai-org/GLM-5-FP8"
|
||||
model = "zai-org/GLM-5"
|
||||
dtype = "bfloat16"
|
||||
quantization = "fp8_per_block"
|
||||
tool_call_parser = "glm47"
|
||||
gpu_memory_utilization = 0.80
|
||||
enable_expert_parallel = true
|
||||
@@ -71,7 +72,7 @@ initial_inflight = 4096
|
||||
max_inflight = 8192
|
||||
|
||||
[orchestrator.model]
|
||||
name = "zai-org/GLM-5-FP8"
|
||||
name = "zai-org/GLM-5"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
@@ -459,9 +459,6 @@ class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
port: int = 29501
|
||||
"""Port for the NCCL broadcast rendezvous."""
|
||||
|
||||
quantize_in_weight_transfer: bool = False
|
||||
"""Use kernel-format FP8 quantized NCCL transfer for weight updates."""
|
||||
|
||||
|
||||
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nixl"] = "nixl"
|
||||
|
||||
@@ -145,9 +145,6 @@ class SharedNCCLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
|
||||
port: int = 29501
|
||||
"""Port for NCCL weight broadcast."""
|
||||
|
||||
quantize_in_weight_transfer: bool = False
|
||||
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
|
||||
|
||||
|
||||
class SharedNIXLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
|
||||
type: Literal["nixl"] = "nixl"
|
||||
@@ -368,22 +365,6 @@ class RLConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_quantize_in_weight_transfer(self):
|
||||
if not isinstance(self.weight_broadcast, SharedNCCLWeightBroadcastConfig):
|
||||
return self
|
||||
|
||||
if not self.weight_broadcast.quantize_in_weight_transfer:
|
||||
return self
|
||||
|
||||
if self.inference is None:
|
||||
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires an inference config.")
|
||||
|
||||
if self.trainer.model.impl != "custom":
|
||||
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires trainer.model.impl = 'custom'.")
|
||||
|
||||
return self
|
||||
|
||||
### Auto-setup shared configs (before sub-config construction)
|
||||
|
||||
@model_validator(mode="before")
|
||||
@@ -487,9 +468,7 @@ class RLConfig(BaseConfig):
|
||||
inference_world_size=inference_world_size,
|
||||
)
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
transport_config = dict(
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
transport_config = {}
|
||||
trainer_config_type = TrainerNCCLWeightBroadcastConfig
|
||||
orchestrator_config_type = OrchestratorNCCLWeightBroadcastConfig
|
||||
else:
|
||||
@@ -538,18 +517,9 @@ class RLConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_eplb_requires_quantized_weight_transfer(self):
|
||||
if self.inference is None or not self.inference.vllm.enable_eplb:
|
||||
return self
|
||||
|
||||
# TODO(matej): check if weight reloading works itself before supporting EPLB without quantized transfer.
|
||||
trainer_weight_broadcast = self.trainer.weight_broadcast
|
||||
if trainer_weight_broadcast.type != "nccl" or not trainer_weight_broadcast.quantize_in_weight_transfer:
|
||||
raise ValueError(
|
||||
"inference.vllm.enable_eplb requires weight_broadcast.type = 'nccl' and "
|
||||
"weight_broadcast.quantize_in_weight_transfer = true."
|
||||
)
|
||||
|
||||
def validate_eplb(self):
|
||||
if self.inference is not None and self.inference.vllm.enable_eplb:
|
||||
raise ValueError("inference.vllm.enable_eplb is not supported with RL weight updates.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -645,9 +645,6 @@ class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
port: int = 29501
|
||||
"""Port for the NCCL broadcast rendezvous."""
|
||||
|
||||
quantize_in_weight_transfer: bool = False
|
||||
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
|
||||
|
||||
|
||||
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nixl"] = "nixl"
|
||||
|
||||
@@ -391,7 +391,6 @@ class DynamoAdminPlane(AdminPlane):
|
||||
port: int,
|
||||
timeout: int,
|
||||
inference_world_size: int,
|
||||
quantize_in_weight_transfer: bool = False,
|
||||
) -> None:
|
||||
async with self._mutation_lock:
|
||||
self._require_uninitialized_nccl()
|
||||
@@ -411,7 +410,6 @@ class DynamoAdminPlane(AdminPlane):
|
||||
0,
|
||||
1,
|
||||
timeout,
|
||||
quantize_in_weight_transfer,
|
||||
"default",
|
||||
],
|
||||
)
|
||||
|
||||
@@ -138,11 +138,10 @@ async def init_broadcaster(request: Request):
|
||||
timeout = data.get("timeout")
|
||||
rank_offset = data.get("rank_offset")
|
||||
inference_world_size = data.get("inference_world_size")
|
||||
quantize_in_weight_transfer = data.get("quantize_in_weight_transfer", False)
|
||||
session_id = data.get("session_id", "default")
|
||||
await engine_client(request).collective_rpc(
|
||||
"init_broadcaster",
|
||||
args=(host, port, rank_offset, inference_world_size, timeout, quantize_in_weight_transfer, session_id),
|
||||
args=(host, port, rank_offset, inference_world_size, timeout, session_id),
|
||||
)
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@@ -7,11 +7,7 @@ from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
|
||||
from vllm.distributed.utils import StatelessProcessGroup
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from prime_rl.inference.vllm.worker.weight_transfer import (
|
||||
load_weights_checkpoint_layerwise,
|
||||
load_weights_kernel,
|
||||
update_mla_absorbed_weights,
|
||||
)
|
||||
from prime_rl.inference.vllm.worker.weight_transfer import load_weights_checkpoint_layerwise
|
||||
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable
|
||||
|
||||
# This is to get type hints for the Worker class but not actually extend it at runtime as this is required by vLLM worker extension
|
||||
@@ -99,7 +95,6 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
rank_offset: int,
|
||||
inference_world_size: int,
|
||||
timeout: int,
|
||||
quantize_in_weight_transfer: bool = False,
|
||||
session_id: str = "default",
|
||||
) -> None:
|
||||
"""Initialize the NCCL broadcast receiver.
|
||||
@@ -109,7 +104,6 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
inference_world_size: Total number of inference GPUs across all servers.
|
||||
"""
|
||||
del session_id
|
||||
self.quantize_in_weight_transfer = quantize_in_weight_transfer
|
||||
# Use the worker's device index directly as the local rank.
|
||||
# The previous dp_group-based computation broke in vLLM v1 multiprocess
|
||||
# DP mode where each worker is a separate process with a singleton
|
||||
@@ -145,11 +139,6 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
assert isinstance(model, Module)
|
||||
|
||||
state_iter = self.nccl_broadcast_receiver.receive_state_dict()
|
||||
if self.quantize_in_weight_transfer:
|
||||
load_weights_kernel(model, state_iter)
|
||||
update_mla_absorbed_weights(model)
|
||||
return
|
||||
|
||||
load_weights_checkpoint_layerwise(
|
||||
model,
|
||||
state_iter,
|
||||
|
||||
@@ -98,10 +98,9 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
rank_offset: int,
|
||||
inference_world_size: int,
|
||||
timeout: int,
|
||||
quantize_in_weight_transfer: bool = False,
|
||||
session_id: str = "default",
|
||||
) -> None:
|
||||
del inference_world_size, quantize_in_weight_transfer
|
||||
del inference_world_size
|
||||
global_rank = rank_offset + self.device.index
|
||||
server_url = f"{host}:{port}"
|
||||
set_ucx_env_defaults(self.device.index)
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
from typing import Generator, Iterable
|
||||
from typing import Iterable
|
||||
|
||||
import torch
|
||||
from torch.nn import Module
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader.reload import finalize_layerwise_reload, initialize_layerwise_reload
|
||||
from vllm.model_executor.model_loader.weight_utils import remap_moe_expert_weights
|
||||
|
||||
logger = init_logger("vllm.inference.vllm.worker_weight_transfer")
|
||||
|
||||
@@ -24,116 +23,6 @@ def load_weights_checkpoint_layerwise(
|
||||
finalize_layerwise_reload(model, model_config)
|
||||
|
||||
|
||||
def _invert_logical_to_physical_map(logical_to_physical_map: torch.Tensor, num_physical_experts: int) -> torch.Tensor:
|
||||
"""Build a physical expert -> logical expert map from vLLM EPLB state."""
|
||||
physical_to_logical = torch.full(
|
||||
(num_physical_experts,),
|
||||
-1,
|
||||
dtype=torch.long,
|
||||
device=logical_to_physical_map.device,
|
||||
)
|
||||
logical_indices = torch.arange(
|
||||
logical_to_physical_map.shape[0],
|
||||
dtype=torch.long,
|
||||
device=logical_to_physical_map.device,
|
||||
)[:, None].expand_as(logical_to_physical_map)
|
||||
physical_indices = logical_to_physical_map.to(torch.long)
|
||||
invalid = (physical_indices < -1) | (physical_indices >= num_physical_experts)
|
||||
if invalid.any():
|
||||
invalid_indices = physical_indices[invalid].unique().tolist()
|
||||
raise ValueError(f"EPLB maps to invalid physical experts: {invalid_indices}")
|
||||
|
||||
valid = physical_indices >= 0
|
||||
physical_to_logical[physical_indices[valid]] = logical_indices[valid]
|
||||
return physical_to_logical
|
||||
|
||||
|
||||
def _build_expert_source_indices(routed_experts, router) -> torch.Tensor | None:
|
||||
if routed_experts._expert_map is None:
|
||||
return None
|
||||
|
||||
physical_indices = torch.where(routed_experts._expert_map >= 0)[0]
|
||||
local_indices = routed_experts._expert_map[physical_indices]
|
||||
physical_indices = physical_indices[local_indices.argsort()]
|
||||
|
||||
eplb_layer_state = getattr(router, "eplb_state", None)
|
||||
logical_to_physical_map = getattr(eplb_layer_state, "logical_to_physical_map", None)
|
||||
if logical_to_physical_map is None:
|
||||
return physical_indices
|
||||
|
||||
physical_to_logical = _invert_logical_to_physical_map(logical_to_physical_map, routed_experts.global_num_experts)
|
||||
logical_indices = physical_to_logical[physical_indices.to(physical_to_logical.device)]
|
||||
if (logical_indices < 0).any():
|
||||
missing = physical_indices[(logical_indices < 0).to(physical_indices.device)].tolist()
|
||||
raise ValueError(f"EPLB has no logical mapping for local physical experts: {missing}")
|
||||
|
||||
return logical_indices.to(physical_indices.device)
|
||||
|
||||
|
||||
def build_expert_map(model: Module) -> dict[str, torch.Tensor]:
|
||||
"""Map MoE module names to source expert indices local to this worker.
|
||||
|
||||
vLLM 0.24 turned ``FusedMoE`` into a factory returning a ``MoERunner`` and
|
||||
split the state that used to live on the ``FusedMoE`` module: the expert map
|
||||
(``_expert_map`` / ``global_num_experts``) now lives on
|
||||
``MoERunner.routed_experts`` (a ``RoutedExperts``), and the EPLB state on
|
||||
``MoERunner.router``. Keying by the ``MoERunner`` name prefix-matches the
|
||||
nested ``routed_experts.*`` weight params after ``load_weights_kernel``
|
||||
remaps incoming flat names via ``remap_moe_expert_weights``.
|
||||
"""
|
||||
from vllm.model_executor.layers.fused_moe import MoERunner
|
||||
|
||||
source_indices_by_module: dict[str, torch.Tensor] = {}
|
||||
for module_name, module in model.named_modules():
|
||||
if not isinstance(module, MoERunner):
|
||||
continue
|
||||
source_indices = _build_expert_source_indices(module.routed_experts, module.router)
|
||||
if source_indices is None:
|
||||
continue
|
||||
source_indices_by_module[module_name] = source_indices
|
||||
return source_indices_by_module
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def load_weights_kernel(model: Module, state_iter: Generator[tuple[str, torch.Tensor], None, None]) -> None:
|
||||
"""Load vLLM kernel-format tensors using in-place copy_ updates."""
|
||||
params = dict(model.named_parameters())
|
||||
expert_source_indices = build_expert_map(model)
|
||||
|
||||
loaded = 0
|
||||
skipped: list[str] = []
|
||||
shape_mismatches: list[str] = []
|
||||
|
||||
# The trainer emits pre-0.24 flat kernel names (``...experts.w13_weight``); since
|
||||
# vLLM 0.24 the expert params are nested (``...experts.routed_experts.w13_weight``).
|
||||
# ``remap_moe_expert_weights`` is upstream's compat shim for exactly this transition.
|
||||
for name, tensor in remap_moe_expert_weights(state_iter, params):
|
||||
if name not in params:
|
||||
skipped.append(name)
|
||||
continue
|
||||
|
||||
param = params[name]
|
||||
if param.shape != tensor.shape:
|
||||
for module_name, source_indices in expert_source_indices.items():
|
||||
if not name.startswith(f"{module_name}."):
|
||||
continue
|
||||
tensor = tensor[source_indices.to(tensor.device)]
|
||||
break
|
||||
|
||||
if param.shape != tensor.shape:
|
||||
shape_mismatches.append(f"{name}: param={list(param.shape)} != received={list(tensor.shape)}")
|
||||
continue
|
||||
|
||||
param.copy_(tensor)
|
||||
loaded += 1
|
||||
|
||||
if shape_mismatches:
|
||||
raise ValueError(f"Kernel weight transfer had {len(shape_mismatches)} shape mismatches: {shape_mismatches}")
|
||||
if skipped:
|
||||
raise ValueError(f"Kernel weight transfer skipped {len(skipped)} weights not found in model: {skipped}")
|
||||
logger.debug(f"Kernel weight transfer copied {loaded} weights in-place")
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def update_mla_absorbed_weights(model: Module) -> None:
|
||||
"""Recompute MLA absorbed KV weights after in-place kv_b_proj updates."""
|
||||
|
||||
@@ -169,7 +169,6 @@ class AdminPlane:
|
||||
port: int,
|
||||
timeout: int,
|
||||
inference_world_size: int,
|
||||
quantize_in_weight_transfer: bool = False,
|
||||
) -> None:
|
||||
gpus_per_server = inference_world_size // len(self.clients)
|
||||
get_logger().info(
|
||||
@@ -187,7 +186,6 @@ class AdminPlane:
|
||||
"rank_offset": rank_offset,
|
||||
"inference_world_size": inference_world_size,
|
||||
"timeout": timeout,
|
||||
"quantize_in_weight_transfer": quantize_in_weight_transfer,
|
||||
},
|
||||
)
|
||||
response.raise_for_status()
|
||||
@@ -513,7 +511,6 @@ async def init_nixl_broadcast(
|
||||
"rank_offset": rank_offset,
|
||||
"inference_world_size": inference_world_size,
|
||||
"timeout": timeout,
|
||||
"quantize_in_weight_transfer": False,
|
||||
"session_id": session_id,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -143,23 +143,6 @@ class PreTrainedModelPrimeRL(PreTrainedModel):
|
||||
"""
|
||||
return state_dict
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_vllm_kernel(
|
||||
cls,
|
||||
state_dict: dict[str, Tensor],
|
||||
layer_idx: int,
|
||||
quantize_fp8: bool = False,
|
||||
) -> dict[str, Tensor]:
|
||||
"""
|
||||
Convert a single layer's state dict from PrimeRL format to vLLM kernel format.
|
||||
|
||||
Args:
|
||||
state_dict: Layer weights in PrimeRL format.
|
||||
layer_idx: Layer index to convert.
|
||||
quantize_fp8: Whether to emit FP8 (e4m3) kernel weights with per-block scales.
|
||||
"""
|
||||
raise NotImplementedError(f"convert_layer_to_vllm_kernel is not implemented for {cls.__name__}")
|
||||
|
||||
def init_buffers_post_meta(self) -> None:
|
||||
"""
|
||||
Initialize buffers that are not in the state dict after loading with meta device.
|
||||
|
||||
@@ -37,28 +37,3 @@ def quantize_to_fp8_blockwise(weight: Tensor, block_size: int = 128) -> tuple[Te
|
||||
|
||||
quantized = blocks_fp8.permute(0, 2, 1, 3).reshape(padded_rows, padded_cols)[:rows, :cols].contiguous()
|
||||
return quantized, scales.float().contiguous()
|
||||
|
||||
|
||||
def quantize_to_vllm_kernel_format(weight: Tensor, block_size: int = 128) -> tuple[Tensor, Tensor]:
|
||||
"""Quantize a weight into the FP8 layout used by vLLM kernels.
|
||||
|
||||
Hopper kernels consume the regular blockwise scale grid. On SM100, vLLM's
|
||||
DeepGEMM kernels instead use UE8M0 scales in an architecture-specific packed
|
||||
layout. Reuse vLLM's own post-processing so tensors sent over the kernel
|
||||
weight-transfer path have the same representation as the loaded parameters.
|
||||
"""
|
||||
quantized, scales = quantize_to_fp8_blockwise(weight, block_size)
|
||||
|
||||
if not weight.is_cuda or torch.cuda.get_device_capability(weight.device) != (10, 0):
|
||||
return quantized, scales
|
||||
|
||||
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
|
||||
deepgemm_post_process_fp8_weight_block,
|
||||
)
|
||||
|
||||
return deepgemm_post_process_fp8_weight_block(
|
||||
wq=quantized,
|
||||
ws=scales,
|
||||
quant_block_shape=(block_size, block_size),
|
||||
use_e8m0=True,
|
||||
)
|
||||
|
||||
@@ -6,11 +6,7 @@ parameters retain their names in both formats.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
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
|
||||
|
||||
|
||||
@@ -19,123 +15,3 @@ def conversion_chain(config) -> list[ConvOp]:
|
||||
for layer_idx in range(config.num_hidden_layers):
|
||||
ops.extend(glm_moe_layer_ops(layer_idx))
|
||||
return ops
|
||||
|
||||
|
||||
def convert_tt_layer_to_vllm_kernel(
|
||||
state_dict: dict[str, Tensor],
|
||||
layer_idx: int,
|
||||
quantize_fp8: bool = False,
|
||||
) -> dict[str, Tensor]:
|
||||
"""Convert a single GLM layer from PrimeRL format to vLLM kernel format."""
|
||||
out: dict[str, Tensor] = {}
|
||||
prefix = f"model.layers.{layer_idx}"
|
||||
|
||||
def add(name: str, tensor: Tensor) -> None:
|
||||
out[name] = tensor
|
||||
|
||||
def add_maybe_fp8(name: str, tensor: Tensor) -> None:
|
||||
if quantize_fp8 and tensor.ndim == 2:
|
||||
fp8_weight, scale = quantize_to_vllm_kernel_format(tensor)
|
||||
out[name] = fp8_weight
|
||||
scale_name = name.removesuffix(".weight") + ".weight_scale_inv"
|
||||
out[scale_name] = scale
|
||||
return
|
||||
out[name] = tensor
|
||||
|
||||
for name in [f"{prefix}.input_layernorm.weight", f"{prefix}.post_attention_layernorm.weight"]:
|
||||
if name in state_dict:
|
||||
add(name, state_dict[name])
|
||||
|
||||
q_a_key = f"{prefix}.self_attn.q_a_proj.weight"
|
||||
kv_a_key = f"{prefix}.self_attn.kv_a_proj_with_mqa.weight"
|
||||
if q_a_key in state_dict and kv_a_key in state_dict:
|
||||
add_maybe_fp8(
|
||||
f"{prefix}.self_attn.fused_qkv_a_proj.weight", torch.cat([state_dict[q_a_key], state_dict[kv_a_key]], dim=0)
|
||||
)
|
||||
|
||||
for suffix in ["q_a_layernorm.weight", "kv_a_layernorm.weight"]:
|
||||
key = f"{prefix}.self_attn.{suffix}"
|
||||
if key in state_dict:
|
||||
add(key, state_dict[key])
|
||||
|
||||
for suffix in ["q_b_proj.weight", "kv_b_proj.weight", "o_proj.weight"]:
|
||||
key = f"{prefix}.self_attn.{suffix}"
|
||||
if key in state_dict:
|
||||
add_maybe_fp8(key, state_dict[key])
|
||||
|
||||
indexer_wq_b_key = f"{prefix}.self_attn.indexer.wq_b.weight"
|
||||
if indexer_wq_b_key in state_dict:
|
||||
add_maybe_fp8(indexer_wq_b_key, state_dict[indexer_wq_b_key])
|
||||
|
||||
indexer_wk_key = f"{prefix}.self_attn.indexer.wk.weight"
|
||||
indexer_weights_proj_key = f"{prefix}.self_attn.indexer.weights_proj.weight"
|
||||
if indexer_wk_key in state_dict and indexer_weights_proj_key in state_dict:
|
||||
add(
|
||||
f"{prefix}.self_attn.indexer.wk_weights_proj.weight",
|
||||
torch.cat([state_dict[indexer_wk_key], state_dict[indexer_weights_proj_key]], dim=0),
|
||||
)
|
||||
for suffix in ["indexer.k_norm.weight", "indexer.k_norm.bias"]:
|
||||
key = f"{prefix}.self_attn.{suffix}"
|
||||
if key in state_dict:
|
||||
add(key, state_dict[key])
|
||||
|
||||
gate_key = f"{prefix}.mlp.gate_proj.weight"
|
||||
up_key = f"{prefix}.mlp.up_proj.weight"
|
||||
down_key = f"{prefix}.mlp.down_proj.weight"
|
||||
if gate_key in state_dict and up_key in state_dict:
|
||||
add_maybe_fp8(f"{prefix}.mlp.gate_up_proj.weight", torch.cat([state_dict[gate_key], state_dict[up_key]], dim=0))
|
||||
if down_key in state_dict:
|
||||
add_maybe_fp8(f"{prefix}.mlp.down_proj.weight", state_dict[down_key])
|
||||
|
||||
router_key = f"{prefix}.mlp.router.gate.weight"
|
||||
if router_key in state_dict:
|
||||
add(f"{prefix}.mlp.gate.weight", state_dict[router_key])
|
||||
selection_bias_key = f"{prefix}.mlp.router.selection_bias"
|
||||
if selection_bias_key in state_dict:
|
||||
add(f"{prefix}.mlp.gate.e_score_correction_bias", state_dict[selection_bias_key])
|
||||
|
||||
w1_key = f"{prefix}.mlp.experts.gate_proj"
|
||||
w2_key = f"{prefix}.mlp.experts.down_proj"
|
||||
w3_key = f"{prefix}.mlp.experts.up_proj"
|
||||
if w1_key in state_dict and w2_key in state_dict and w3_key in state_dict:
|
||||
w1 = state_dict[w1_key]
|
||||
w2 = state_dict[w2_key]
|
||||
w3 = state_dict[w3_key]
|
||||
w13 = torch.cat([w1, w3], dim=1)
|
||||
|
||||
if quantize_fp8:
|
||||
w13_fp8: list[Tensor] = []
|
||||
w13_scales: list[Tensor] = []
|
||||
w2_fp8: list[Tensor] = []
|
||||
w2_scales: list[Tensor] = []
|
||||
for expert_idx in range(w1.shape[0]):
|
||||
expert_w13_fp8, expert_w13_scales = quantize_to_vllm_kernel_format(w13[expert_idx])
|
||||
expert_w2_fp8, expert_w2_scales = quantize_to_vllm_kernel_format(w2[expert_idx])
|
||||
w13_fp8.append(expert_w13_fp8)
|
||||
w13_scales.append(expert_w13_scales)
|
||||
w2_fp8.append(expert_w2_fp8)
|
||||
w2_scales.append(expert_w2_scales)
|
||||
|
||||
out[f"{prefix}.mlp.experts.w13_weight"] = torch.stack(w13_fp8)
|
||||
out[f"{prefix}.mlp.experts.w13_weight_scale_inv"] = torch.stack(w13_scales)
|
||||
out[f"{prefix}.mlp.experts.w2_weight"] = torch.stack(w2_fp8)
|
||||
out[f"{prefix}.mlp.experts.w2_weight_scale_inv"] = torch.stack(w2_scales)
|
||||
else:
|
||||
out[f"{prefix}.mlp.experts.w13_weight"] = w13
|
||||
out[f"{prefix}.mlp.experts.w2_weight"] = w2
|
||||
|
||||
sw1_key = f"{prefix}.mlp.shared_expert.gate_proj.weight"
|
||||
sw2_key = f"{prefix}.mlp.shared_expert.down_proj.weight"
|
||||
sw3_key = f"{prefix}.mlp.shared_expert.up_proj.weight"
|
||||
if sw1_key in state_dict and sw2_key in state_dict and sw3_key in state_dict:
|
||||
sw1 = state_dict[sw1_key]
|
||||
sw2 = state_dict[sw2_key]
|
||||
sw3 = state_dict[sw3_key]
|
||||
if sw1.ndim == 3:
|
||||
sw1 = sw1.squeeze(0)
|
||||
sw2 = sw2.squeeze(0)
|
||||
sw3 = sw3.squeeze(0)
|
||||
add_maybe_fp8(f"{prefix}.mlp.shared_experts.gate_up_proj.weight", torch.cat([sw1, sw3], dim=0))
|
||||
add_maybe_fp8(f"{prefix}.mlp.shared_experts.down_proj.weight", sw2)
|
||||
|
||||
return out
|
||||
|
||||
@@ -14,10 +14,7 @@ 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 (
|
||||
conversion_chain,
|
||||
convert_tt_layer_to_vllm_kernel,
|
||||
)
|
||||
from prime_rl.trainer.models.glm_moe_dsa.converting_glm_moe_dsa import conversion_chain
|
||||
from prime_rl.trainer.models.glm_moe_dsa.sparse_mla_attention import GlmMoeDsaAttention, SparseMlaAttentionArgs
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import FeedForward
|
||||
@@ -153,12 +150,6 @@ class GlmMoeDsaPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
def conversion_chain(cls, config):
|
||||
return conversion_chain(config)
|
||||
|
||||
@classmethod
|
||||
def convert_layer_to_vllm_kernel(
|
||||
cls, state_dict: dict[str, Tensor], layer_idx: int, quantize_fp8: bool = False
|
||||
) -> dict[str, Tensor]:
|
||||
return convert_tt_layer_to_vllm_kernel(state_dict, layer_idx, quantize_fp8=quantize_fp8)
|
||||
|
||||
|
||||
@auto_docstring
|
||||
class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
|
||||
|
||||
@@ -114,16 +114,6 @@ def preprocess_layer_checkpoint(
|
||||
return revert_weight_conversion(model, layer_state_dict)
|
||||
|
||||
|
||||
def preprocess_layer_quantized(
|
||||
model: nn.Module,
|
||||
layer_state_dict: dict[str, Tensor],
|
||||
layer_idx: int,
|
||||
) -> dict[str, Tensor]:
|
||||
if layer_idx < 0:
|
||||
return layer_state_dict
|
||||
return model.convert_layer_to_vllm_kernel(layer_state_dict, layer_idx, quantize_fp8=True)
|
||||
|
||||
|
||||
class NCCLBroadcaster:
|
||||
def __init__(
|
||||
self,
|
||||
@@ -133,12 +123,10 @@ class NCCLBroadcaster:
|
||||
world_size: int,
|
||||
device: int | str | torch.device,
|
||||
timeout: int,
|
||||
quantize_in_weight_transfer: bool = False,
|
||||
):
|
||||
self.logger = get_logger()
|
||||
self.world = get_world()
|
||||
self.dtype = torch.bfloat16
|
||||
self.quantize_in_weight_transfer = quantize_in_weight_transfer
|
||||
|
||||
if self.world.is_master:
|
||||
disable_nccl_p2p_if_unavailable()
|
||||
@@ -163,16 +151,10 @@ class NCCLBroadcaster:
|
||||
broadcast_integer(num_state_dict_to_send, self.communicator)
|
||||
|
||||
self.logger.debug(f"Broadcasting {num_state_dict_to_send} layer state dicts")
|
||||
preprocess_fn: Callable[[nn.Module, dict[str, Tensor], int], dict[str, Tensor]]
|
||||
if self.quantize_in_weight_transfer:
|
||||
preprocess_fn = preprocess_layer_quantized
|
||||
else:
|
||||
preprocess_fn = preprocess_layer_checkpoint
|
||||
|
||||
keep_in_fp32 = getattr(model, "keep_in_fp32_for_weight_transfer", None)
|
||||
for layer_id, layer_state_dict in filter_state_dict_by_layers(state_dict, num_layers, layer_prefix):
|
||||
layer_state_dict = resolve_dtensors(layer_state_dict, keep_in_fp32, self.dtype)
|
||||
layer_state_dict = preprocess_fn(model, layer_state_dict, layer_id)
|
||||
layer_state_dict = preprocess_layer_checkpoint(model, layer_state_dict, layer_id)
|
||||
if self.world.is_master:
|
||||
broadcast_state_dict(layer_state_dict, self.communicator)
|
||||
|
||||
@@ -194,14 +176,13 @@ class NCCLWeightSender(WeightSender):
|
||||
config.inference_world_size + 1,
|
||||
device,
|
||||
config.timeout,
|
||||
quantize_in_weight_transfer=config.quantize_in_weight_transfer,
|
||||
)
|
||||
|
||||
@torch.no_grad()
|
||||
def _broadcast(self, model: nn.Module, step: int, step_dir: Path) -> None:
|
||||
# The master enters only after the receiver acknowledged the handshake,
|
||||
# but all ranks must be held back until then: the broadcast preparation
|
||||
# (DTensor resolution, quantization) enqueues collectives on non-master
|
||||
# (DTensor resolution, checkpoint conversion) enqueues collectives on non-master
|
||||
# ranks, and if those start before the receiver has paused inference,
|
||||
# the collectives sit unmatched until NCCL's watchdog kills the process.
|
||||
if self.world.world_size > 1:
|
||||
@@ -221,7 +202,6 @@ class NCCLWeightReceiver(WeightReceiver):
|
||||
port=self.config.port,
|
||||
timeout=self.config.timeout,
|
||||
inference_world_size=self.config.inference_world_size,
|
||||
quantize_in_weight_transfer=self.config.quantize_in_weight_transfer,
|
||||
)
|
||||
|
||||
async def receive(self, step: int) -> None:
|
||||
|
||||
@@ -213,7 +213,7 @@ def test_dynamo_nccl_lifecycle_initializes_and_updates_weights(tmp_path):
|
||||
asyncio.run(admin.initialize_nccl(host="trainer", port=29501, timeout=10, inference_world_size=1))
|
||||
asyncio.run(admin.update_weights(tmp_path / "step_1", transport="nccl", step=1))
|
||||
|
||||
assert collective_rpc.await_args_list[0].kwargs["args"] == ["trainer", 29501, 0, 1, 10, False, "default"]
|
||||
assert collective_rpc.await_args_list[0].kwargs["args"] == ["trainer", 29501, 0, 1, 10, "default"]
|
||||
assert collective_rpc.await_args_list[1].kwargs["args"] == [(tmp_path / "step_1").as_posix()]
|
||||
assert [call.args[1] for call in post.await_args_list] == ["/pause", "/resume"]
|
||||
assert admin._nccl_initialization_state == "ready"
|
||||
|
||||
@@ -81,7 +81,6 @@ def test_admin_plane_initializes_nccl():
|
||||
"rank_offset": 0,
|
||||
"inference_world_size": 1,
|
||||
"timeout": 1200,
|
||||
"quantize_in_weight_transfer": False,
|
||||
},
|
||||
)
|
||||
asyncio.run(admin_plane.aclose())
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.models.glm_moe_dsa.converting_glm_moe_dsa import convert_tt_layer_to_vllm_kernel
|
||||
|
||||
|
||||
def _build_prime_layer_state(layer_idx: int = 0) -> dict[str, torch.Tensor]:
|
||||
prefix = f"model.layers.{layer_idx}"
|
||||
return {
|
||||
f"{prefix}.self_attn.q_a_proj.weight": torch.randn(4, 6),
|
||||
f"{prefix}.self_attn.kv_a_proj_with_mqa.weight": torch.randn(3, 6),
|
||||
f"{prefix}.self_attn.q_b_proj.weight": torch.randn(5, 6),
|
||||
f"{prefix}.self_attn.kv_b_proj.weight": torch.randn(7, 6),
|
||||
f"{prefix}.self_attn.o_proj.weight": torch.randn(6, 5),
|
||||
f"{prefix}.self_attn.indexer.wq_b.weight": torch.randn(4, 6),
|
||||
f"{prefix}.self_attn.indexer.wk.weight": torch.randn(4, 6),
|
||||
f"{prefix}.self_attn.indexer.k_norm.weight": torch.randn(6),
|
||||
f"{prefix}.self_attn.indexer.k_norm.bias": torch.randn(6),
|
||||
f"{prefix}.self_attn.indexer.weights_proj.weight": torch.randn(2, 6),
|
||||
f"{prefix}.mlp.gate_proj.weight": torch.randn(8, 6),
|
||||
f"{prefix}.mlp.up_proj.weight": torch.randn(8, 6),
|
||||
f"{prefix}.mlp.down_proj.weight": torch.randn(6, 8),
|
||||
f"{prefix}.mlp.router.gate.weight": torch.randn(4, 6),
|
||||
f"{prefix}.mlp.router.selection_bias": torch.randn(4),
|
||||
f"{prefix}.mlp.experts.gate_proj": torch.randn(2, 3, 6),
|
||||
f"{prefix}.mlp.experts.up_proj": torch.randn(2, 3, 6),
|
||||
f"{prefix}.mlp.experts.down_proj": torch.randn(2, 6, 3),
|
||||
f"{prefix}.mlp.shared_expert.gate_proj.weight": torch.randn(3, 6),
|
||||
f"{prefix}.mlp.shared_expert.up_proj.weight": torch.randn(3, 6),
|
||||
f"{prefix}.mlp.shared_expert.down_proj.weight": torch.randn(6, 3),
|
||||
}
|
||||
|
||||
|
||||
def test_convert_tt_layer_to_vllm_kernel_no_fp8():
|
||||
state = _build_prime_layer_state()
|
||||
out = convert_tt_layer_to_vllm_kernel(state, layer_idx=0, quantize_fp8=False)
|
||||
|
||||
assert "model.layers.0.self_attn.fused_qkv_a_proj.weight" in out
|
||||
assert out["model.layers.0.self_attn.fused_qkv_a_proj.weight"].shape == (7, 6)
|
||||
assert "model.layers.0.self_attn.indexer.wk_weights_proj.weight" in out
|
||||
assert out["model.layers.0.self_attn.indexer.wk_weights_proj.weight"].shape == (6, 6)
|
||||
assert "model.layers.0.self_attn.indexer.wk.weight" not in out
|
||||
assert "model.layers.0.self_attn.indexer.weights_proj.weight" not in out
|
||||
|
||||
assert "model.layers.0.mlp.gate_up_proj.weight" in out
|
||||
assert out["model.layers.0.mlp.gate_up_proj.weight"].shape == (16, 6)
|
||||
|
||||
assert "model.layers.0.mlp.experts.w13_weight" in out
|
||||
assert out["model.layers.0.mlp.experts.w13_weight"].shape == (2, 6, 6)
|
||||
assert "model.layers.0.mlp.experts.w2_weight" in out
|
||||
assert out["model.layers.0.mlp.experts.w2_weight"].shape == (2, 6, 3)
|
||||
|
||||
assert "model.layers.0.mlp.gate.weight" in out
|
||||
assert "model.layers.0.mlp.gate.e_score_correction_bias" in out
|
||||
|
||||
|
||||
def test_convert_tt_layer_to_vllm_kernel_with_fp8():
|
||||
state = _build_prime_layer_state()
|
||||
out = convert_tt_layer_to_vllm_kernel(state, layer_idx=0, quantize_fp8=True)
|
||||
|
||||
assert out["model.layers.0.self_attn.fused_qkv_a_proj.weight"].dtype == torch.float8_e4m3fn
|
||||
assert out["model.layers.0.self_attn.fused_qkv_a_proj.weight_scale_inv"].dtype == torch.float32
|
||||
assert out["model.layers.0.self_attn.indexer.wk_weights_proj.weight"].dtype == torch.float32
|
||||
assert "model.layers.0.self_attn.indexer.wk.weight_scale_inv" not in out
|
||||
|
||||
assert out["model.layers.0.mlp.experts.w13_weight"].dtype == torch.float8_e4m3fn
|
||||
assert out["model.layers.0.mlp.experts.w13_weight_scale_inv"].dtype == torch.float32
|
||||
assert out["model.layers.0.mlp.experts.w2_weight"].dtype == torch.float8_e4m3fn
|
||||
assert out["model.layers.0.mlp.experts.w2_weight_scale_inv"].dtype == torch.float32
|
||||
Reference in New Issue
Block a user