* Feat: deep-gemm-fp8 * Feat: cleanup * nit * Style * Feat: works now * Feat: fp8 grouped gemm works * Fix: skip unaligned + qwen3.5 * chore(deep_gemm): rebuild d30fc36 wheel against torch 2.11 / cu128 The wheel was built against torch 2.10 + cu128; the merge from main bumped torch to 2.11.0+cu128 / vllm to 0.20.1, breaking ABI compat with the old build. Rebuilt via scripts/install_deep_gemm.sh --wheel-dir tools/wheels. Also updates install_deep_gemm.sh: - default ref pinned to d30fc36 (was 477618c) - script header documents the wheel-dir flow used to refresh tools/wheels/ Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore(deep_gemm): pin to v0.5.0 release URL (uploaded d30fc36 wheel) The d30fc36 wheel is now hosted on the v0.5.0 GitHub release alongside the existing 477618c build, so we can drop the local path-based pin. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(fp8): make deep_gemm import optional for CPU-only envs deep_gemm only ships CUDA wheels; importing prime_rl on a CPU box currently fails with ImportError before any FP8 path is even touched. Wrap both call sites in try/except so the import is graceful — actual deep_gemm calls live inside autograd Function bodies that only run on GPU anyway. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(fp8): wire FP8 grouped GEMM into NemotronH; assert disabled for GPT-OSS Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com> Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.7
parent
1e9a3e9196
commit
229391fa27
@@ -330,6 +330,14 @@ class ModelConfig(BaseModelConfig):
|
||||
),
|
||||
] = True
|
||||
|
||||
fp8: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to use FP8 training via DeepGEMM. Replaces nn.Linear layers with FP8 blockwise linear "
|
||||
"and uses FP8 grouped GEMM for MoE experts. Requires SM90 (Hopper) GPUs and model.impl='custom'.",
|
||||
),
|
||||
] = False
|
||||
|
||||
freeze_moe_router: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
@@ -417,6 +425,12 @@ class ModelConfig(BaseModelConfig):
|
||||
raise ValueError("Flash attention 4 is only supported with the custom implementation")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def fp8_only_with_custom_impl(self):
|
||||
if self.fp8 and self.impl not in ("custom", "auto"):
|
||||
raise ValueError("FP8 training is only supported with model.impl='custom' or 'auto'.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_ep_comm_backend(self):
|
||||
if self.ep_comm_backend == "torch":
|
||||
|
||||
+3
-1
@@ -186,7 +186,9 @@ aime2025 = { index = "primeintellect" }
|
||||
deepdive = { index = "primeintellect" }
|
||||
mini_swe_agent_plus = { index = "primeintellect" }
|
||||
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+73b6ea4-cp312-cp312-linux_x86_64.whl" }
|
||||
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.3.0+477618c-cp312-cp312-linux_x86_64.whl" }
|
||||
# DeepGEMM bumped from 477618c to d30fc36 (newer kernel APIs needed by the
|
||||
# FP8 grouped-GEMM training path). Rebuild via scripts/install_deep_gemm.sh.
|
||||
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.3.0+d30fc36-cp312-cp312-linux_x86_64.whl" }
|
||||
nixl-cu12 = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
|
||||
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
|
||||
flash_attn_3 = { index = "pytorch-cu128-test" }
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build and install DeepGEMM from source for FP8 MoE inference.
|
||||
# Build and install DeepGEMM from source for FP8 MoE inference + FP8 training.
|
||||
#
|
||||
# Pinned to d30fc36 — the commit our FP8 grouped-GEMM training path requires
|
||||
# (newer than the 477618c that vLLM 0.17/0.19 used). The matching prebuilt
|
||||
# wheel lives at tools/wheels/deep_gemm-2.3.0+d30fc36-cp312-cp312-linux_x86_64.whl
|
||||
# and is what `pyproject.toml` consumes by default; this script is for
|
||||
# rebuilding when torch / CUDA / vllm bumps invalidate that wheel.
|
||||
#
|
||||
# Uses the commit recommended by vLLM for compatibility with vLLM 0.17+.
|
||||
# Requires CUDA 12.8+ and a Hopper/Blackwell GPU.
|
||||
#
|
||||
# Usage:
|
||||
# bash scripts/install_deep_gemm.sh
|
||||
# bash scripts/install_deep_gemm.sh # build + install in-place
|
||||
# bash scripts/install_deep_gemm.sh --wheel-dir tools/wheels # build wheel only
|
||||
#
|
||||
# Options:
|
||||
# --ref REF DeepGEMM commit hash (default: 477618c)
|
||||
# --ref REF DeepGEMM commit hash (default: d30fc36)
|
||||
# --wheel-dir DIR Output wheel to DIR instead of installing
|
||||
|
||||
set -euo pipefail
|
||||
@@ -17,7 +23,7 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
|
||||
|
||||
DEEPGEMM_GIT_REPO="https://github.com/deepseek-ai/DeepGEMM.git"
|
||||
DEEPGEMM_GIT_REF="477618cd51baffca09c4b0b87e97c03fe827ef03"
|
||||
DEEPGEMM_GIT_REF="d30fc36c8f229f4f873b90a492f6e19e6e610923"
|
||||
WHEEL_DIR=""
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
|
||||
@@ -43,6 +43,7 @@ from prime_rl.trainer.models.layers.checkpointing import (
|
||||
set_selective_activation_checkpointing,
|
||||
supports_selective_activation_checkpointing,
|
||||
)
|
||||
from prime_rl.trainer.models.layers.fp8_linear import replace_linear_with_fp8_blockwise_linear
|
||||
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
|
||||
from prime_rl.trainer.models.layers.moe import LatentMoE, MoE
|
||||
from prime_rl.trainer.parallel_dims import ParallelDims
|
||||
@@ -470,6 +471,7 @@ def get_model(
|
||||
if subconfig is not None and hasattr(subconfig, "use_cache"):
|
||||
subconfig.use_cache = False
|
||||
model_config.use_grouped_mm = config.moe_use_grouped_mm
|
||||
model_config.fp8 = config.fp8
|
||||
|
||||
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it).
|
||||
# In transformers v5, token IDs moved from PretrainedConfig to GenerationConfig.
|
||||
@@ -1040,6 +1042,9 @@ def setup_model(
|
||||
|
||||
inject_prime_lm_head(model, chunk_size=lm_head_chunk_size, fused_cross_entropy=fused_cross_entropy)
|
||||
|
||||
if config.fp8:
|
||||
replace_linear_with_fp8_blockwise_linear(model)
|
||||
|
||||
# Apply LoRA before FSDP setup
|
||||
if config.lora is not None:
|
||||
apply_lora_to_model(model, config.lora)
|
||||
|
||||
@@ -353,6 +353,7 @@ class AfmoeDecoderLayer(GradientCheckpointingLayer):
|
||||
top_k=config.num_experts_per_tok,
|
||||
use_grouped_mm=getattr(config, "use_grouped_mm", True),
|
||||
load_balance_coeff=getattr(config, "load_balance_coeff", None),
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
if self.moe_enabled:
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
|
||||
|
||||
@@ -68,6 +68,7 @@ class Glm4MoeDecoderLayer(GradientCheckpointingLayer):
|
||||
top_k=config.num_experts_per_tok,
|
||||
load_balance_coeff=1e-3,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
|
||||
@@ -65,6 +65,7 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
|
||||
top_k=config.num_experts_per_tok,
|
||||
load_balance_coeff=1e-3,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
|
||||
@@ -83,6 +83,9 @@ class GptOssMoE(nn.Module):
|
||||
|
||||
def __init__(self, config: GptOssConfig):
|
||||
super().__init__()
|
||||
# GptOssGroupedExperts has fused gate_up_proj + per-expert biases; the
|
||||
# current FP8 grouped-GEMM path doesn't model that yet.
|
||||
assert not getattr(config, "fp8", False), "FP8 training is not supported for GPT-OSS"
|
||||
self.num_experts = config.num_local_experts
|
||||
self.top_k = config.num_experts_per_tok
|
||||
self.router = GptOssTopKRouter(config)
|
||||
|
||||
@@ -0,0 +1,546 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Tuple
|
||||
|
||||
import torch
|
||||
import triton
|
||||
import triton.language as tl
|
||||
|
||||
FP8_MAX = 448.0
|
||||
MIN_SCALE = 1e-4
|
||||
GROUP_ALIGNMENT = 128
|
||||
|
||||
|
||||
def ceil_div(x: int, y: int) -> int:
|
||||
return (x + y - 1) // y
|
||||
|
||||
|
||||
def align(x: int, y: int) -> int:
|
||||
return ceil_div(x, y) * y
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Layout building
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def build_grouped_layout(offs: torch.Tensor, *, total_m: int | None = None):
|
||||
assert offs.dim() == 1
|
||||
assert offs.dtype == torch.int32
|
||||
device = offs.device
|
||||
total_m = (total_m if total_m is not None else int(offs[-1].item())) if offs.numel() else 0
|
||||
starts_tensor = torch.empty_like(offs)
|
||||
if offs.numel() > 0:
|
||||
starts_tensor[0] = 0
|
||||
if offs.numel() > 1:
|
||||
starts_tensor[1:] = offs[:-1]
|
||||
actual_ms_tensor = offs - starts_tensor
|
||||
aligned_ms_tensor = ((actual_ms_tensor + GROUP_ALIGNMENT - 1) // GROUP_ALIGNMENT) * GROUP_ALIGNMENT
|
||||
padded_ends = aligned_ms_tensor.cumsum(0)
|
||||
block_starts_tensor = (padded_ends - aligned_ms_tensor) // GROUP_ALIGNMENT
|
||||
ks_tensor = aligned_ms_tensor.contiguous()
|
||||
padded_total_m = int(padded_ends[-1].item()) if offs.numel() else 0
|
||||
total_blocks = padded_total_m // GROUP_ALIGNMENT
|
||||
grouped_layout = torch.empty((padded_total_m,), dtype=torch.int32, device=device)
|
||||
block_to_group = torch.empty((total_blocks,), dtype=torch.int32, device=device)
|
||||
if offs.numel():
|
||||
_build_grouped_layout_triton(
|
||||
grouped_layout,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
aligned_ms_tensor,
|
||||
block_starts_tensor,
|
||||
)
|
||||
return (
|
||||
total_m,
|
||||
padded_total_m,
|
||||
grouped_layout,
|
||||
block_to_group,
|
||||
ks_tensor,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
)
|
||||
|
||||
|
||||
def _build_grouped_layout_triton(
|
||||
grouped_layout: torch.Tensor,
|
||||
block_to_group: torch.Tensor,
|
||||
starts_tensor: torch.Tensor,
|
||||
actual_ms_tensor: torch.Tensor,
|
||||
aligned_ms_tensor: torch.Tensor,
|
||||
block_starts_tensor: torch.Tensor,
|
||||
) -> None:
|
||||
_build_grouped_layout_kernel[(actual_ms_tensor.numel(),)](
|
||||
grouped_layout,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
aligned_ms_tensor,
|
||||
block_starts_tensor,
|
||||
BLOCK_M=128,
|
||||
num_warps=4,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Triton kernels
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _build_grouped_layout_kernel(
|
||||
grouped_layout_ptr,
|
||||
block_to_group_ptr,
|
||||
starts_ptr,
|
||||
actual_ms_ptr,
|
||||
aligned_ms_ptr,
|
||||
block_starts_ptr,
|
||||
BLOCK_M: tl.constexpr,
|
||||
):
|
||||
pid_g = tl.program_id(axis=0)
|
||||
actual_m = tl.load(actual_ms_ptr + pid_g)
|
||||
aligned_m = tl.load(aligned_ms_ptr + pid_g)
|
||||
block_start = tl.load(block_starts_ptr + pid_g)
|
||||
dst_start = block_start * BLOCK_M
|
||||
block_idx = 0
|
||||
while block_idx < (aligned_m // BLOCK_M):
|
||||
row_offsets = block_idx * BLOCK_M + tl.arange(0, BLOCK_M)
|
||||
values = tl.where(row_offsets < actual_m, pid_g, -1)
|
||||
tl.store(grouped_layout_ptr + dst_start + row_offsets, values)
|
||||
tl.store(block_to_group_ptr + block_start + block_idx, pid_g)
|
||||
block_idx += 1
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _unpack_grouped_rows_kernel(
|
||||
x_ptr,
|
||||
block_to_group_ptr,
|
||||
starts_ptr,
|
||||
actual_ms_ptr,
|
||||
block_starts_ptr,
|
||||
out_ptr,
|
||||
cols,
|
||||
stride_xm,
|
||||
stride_xn,
|
||||
stride_ym,
|
||||
stride_yn,
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_N: tl.constexpr,
|
||||
GROUP_BLOCK_M: tl.constexpr,
|
||||
):
|
||||
pid_blk = tl.program_id(axis=0)
|
||||
pid_sub = tl.program_id(axis=1)
|
||||
pid_n = tl.program_id(axis=2)
|
||||
pid_g = tl.load(block_to_group_ptr + pid_blk)
|
||||
block_start = tl.load(block_starts_ptr + pid_g)
|
||||
dst_start = tl.load(starts_ptr + pid_g)
|
||||
actual_m = tl.load(actual_ms_ptr + pid_g)
|
||||
row_offsets = (pid_blk - block_start) * GROUP_BLOCK_M + pid_sub * BLOCK_M + tl.arange(0, BLOCK_M)
|
||||
col_offsets = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
|
||||
valid_rows = row_offsets < actual_m
|
||||
valid_cols = col_offsets < cols
|
||||
x = tl.load(
|
||||
x_ptr
|
||||
+ (pid_blk * GROUP_BLOCK_M + pid_sub * BLOCK_M + tl.arange(0, BLOCK_M))[:, None] * stride_xm
|
||||
+ col_offsets[None, :] * stride_xn,
|
||||
mask=valid_rows[:, None] & valid_cols[None, :],
|
||||
other=0.0,
|
||||
)
|
||||
tl.store(
|
||||
out_ptr + (dst_start + row_offsets)[:, None] * stride_ym + col_offsets[None, :] * stride_yn,
|
||||
x,
|
||||
mask=valid_rows[:, None] & valid_cols[None, :],
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _per_token_fp8_kernel(
|
||||
x_ptr,
|
||||
out_ptr,
|
||||
sf_ptr,
|
||||
rows,
|
||||
cols,
|
||||
stride_xm,
|
||||
stride_xn,
|
||||
stride_ym,
|
||||
stride_yn,
|
||||
stride_sm,
|
||||
stride_sk,
|
||||
USE_UE8M0: tl.constexpr,
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_K: tl.constexpr,
|
||||
):
|
||||
pid_m = tl.program_id(axis=0)
|
||||
pid_k = tl.program_id(axis=1)
|
||||
row_offsets = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
||||
col_offsets = pid_k * BLOCK_K + tl.arange(0, BLOCK_K)
|
||||
mask = (row_offsets[:, None] < rows) & (col_offsets[None, :] < cols)
|
||||
x = tl.load(
|
||||
x_ptr + row_offsets[:, None] * stride_xm + col_offsets[None, :] * stride_xn,
|
||||
mask=mask,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
amax = tl.max(tl.abs(x), axis=1)
|
||||
scale = tl.maximum(amax / 448.0, 1e-4)
|
||||
if USE_UE8M0:
|
||||
scale = tl.exp2(tl.ceil(tl.log2(scale)))
|
||||
y = x / scale[:, None]
|
||||
tl.store(
|
||||
out_ptr + row_offsets[:, None] * stride_ym + col_offsets[None, :] * stride_yn,
|
||||
y.to(tl.float8e4nv),
|
||||
mask=mask,
|
||||
)
|
||||
tl.store(sf_ptr + row_offsets * stride_sm + pid_k * stride_sk, scale, mask=row_offsets < rows)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _grouped_per_token_fp8_kernel(
|
||||
x_ptr,
|
||||
block_to_group_ptr,
|
||||
starts_ptr,
|
||||
actual_ms_ptr,
|
||||
block_starts_ptr,
|
||||
out_ptr,
|
||||
sf_ptr,
|
||||
cols,
|
||||
stride_xm,
|
||||
stride_xn,
|
||||
stride_ym,
|
||||
stride_yn,
|
||||
stride_sm,
|
||||
stride_sk,
|
||||
USE_UE8M0: tl.constexpr,
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_K: tl.constexpr,
|
||||
GROUP_BLOCK_M: tl.constexpr,
|
||||
):
|
||||
pid_blk = tl.program_id(axis=0)
|
||||
pid_sub = tl.program_id(axis=1)
|
||||
pid_k = tl.program_id(axis=2)
|
||||
pid_g = tl.load(block_to_group_ptr + pid_blk)
|
||||
src_start = tl.load(starts_ptr + pid_g)
|
||||
actual_m = tl.load(actual_ms_ptr + pid_g)
|
||||
block_start = tl.load(block_starts_ptr + pid_g)
|
||||
local_block = pid_blk - block_start
|
||||
row_offsets = local_block * GROUP_BLOCK_M + pid_sub * BLOCK_M + tl.arange(0, BLOCK_M)
|
||||
col_offsets = pid_k * BLOCK_K + tl.arange(0, BLOCK_K)
|
||||
valid_rows = row_offsets < actual_m
|
||||
valid_cols = col_offsets < cols
|
||||
src_rows = src_start + row_offsets
|
||||
dst_rows = pid_blk * GROUP_BLOCK_M + pid_sub * BLOCK_M + tl.arange(0, BLOCK_M)
|
||||
x = tl.load(
|
||||
x_ptr + src_rows[:, None] * stride_xm + col_offsets[None, :] * stride_xn,
|
||||
mask=valid_rows[:, None] & valid_cols[None, :],
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
amax = tl.max(tl.abs(x), axis=1)
|
||||
scale = tl.maximum(amax / 448.0, 1e-4)
|
||||
if USE_UE8M0:
|
||||
scale = tl.exp2(tl.ceil(tl.log2(scale)))
|
||||
y = x / scale[:, None]
|
||||
tl.store(
|
||||
out_ptr + dst_rows[:, None] * stride_ym + col_offsets[None, :] * stride_yn,
|
||||
y.to(tl.float8e4nv),
|
||||
mask=valid_rows[:, None] & valid_cols[None, :],
|
||||
)
|
||||
tl.store(sf_ptr + dst_rows * stride_sm + pid_k * stride_sk, scale, mask=valid_rows)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _grouped_per_channel_fp8_sm90_kmajor_kernel(
|
||||
x_ptr,
|
||||
block_to_group_ptr,
|
||||
starts_ptr,
|
||||
actual_ms_ptr,
|
||||
aligned_ms_ptr,
|
||||
block_starts_ptr,
|
||||
out_ptr,
|
||||
sf_ptr,
|
||||
cols,
|
||||
stride_xm,
|
||||
stride_xn,
|
||||
stride_sf0,
|
||||
stride_sf1,
|
||||
USE_UE8M0: tl.constexpr,
|
||||
BLOCK_K: tl.constexpr,
|
||||
BLOCK_N: tl.constexpr,
|
||||
):
|
||||
pid_blk = tl.program_id(axis=0)
|
||||
pid_n = tl.program_id(axis=1)
|
||||
pid_g = tl.load(block_to_group_ptr + pid_blk)
|
||||
src_start = tl.load(starts_ptr + pid_g)
|
||||
actual_m = tl.load(actual_ms_ptr + pid_g)
|
||||
aligned_m = tl.load(aligned_ms_ptr + pid_g)
|
||||
block_start = tl.load(block_starts_ptr + pid_g)
|
||||
local_block = pid_blk - block_start
|
||||
row_offsets = local_block * BLOCK_K + tl.arange(0, BLOCK_K)
|
||||
col_offsets = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
|
||||
valid_rows = row_offsets < actual_m
|
||||
valid_cols = col_offsets < cols
|
||||
src_rows = src_start + row_offsets
|
||||
x = tl.load(
|
||||
x_ptr + src_rows[:, None] * stride_xm + col_offsets[None, :] * stride_xn,
|
||||
mask=valid_rows[:, None] & valid_cols[None, :],
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
amax = tl.max(tl.abs(x), axis=0)
|
||||
scale = tl.maximum(amax / 448.0, 1e-4)
|
||||
if USE_UE8M0:
|
||||
scale = tl.exp2(tl.ceil(tl.log2(scale)))
|
||||
y = x / scale[None, :]
|
||||
flat_base = block_start * BLOCK_K * cols
|
||||
out_ptrs = out_ptr + flat_base + col_offsets[:, None] * aligned_m + row_offsets[None, :]
|
||||
tl.store(out_ptrs, tl.trans(y).to(tl.float8e4nv), mask=valid_cols[:, None] & (row_offsets[None, :] < aligned_m))
|
||||
tl.store(
|
||||
sf_ptr + pid_blk * stride_sf0 + col_offsets * stride_sf1,
|
||||
scale,
|
||||
mask=valid_cols,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _grouped_per_block_fp8_kernel(
|
||||
x_ptr,
|
||||
out_ptr,
|
||||
sf_ptr,
|
||||
groups,
|
||||
rows,
|
||||
cols,
|
||||
stride_xg,
|
||||
stride_xm,
|
||||
stride_xn,
|
||||
stride_yg,
|
||||
stride_ym,
|
||||
stride_yn,
|
||||
stride_sg,
|
||||
stride_sm,
|
||||
stride_sn,
|
||||
USE_UE8M0: tl.constexpr,
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_N: tl.constexpr,
|
||||
):
|
||||
pid_g = tl.program_id(axis=0)
|
||||
pid_m = tl.program_id(axis=1)
|
||||
pid_n = tl.program_id(axis=2)
|
||||
row_offsets = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
||||
col_offsets = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
|
||||
mask = (pid_g < groups) & (row_offsets[:, None] < rows) & (col_offsets[None, :] < cols)
|
||||
x = tl.load(
|
||||
x_ptr + pid_g * stride_xg + row_offsets[:, None] * stride_xm + col_offsets[None, :] * stride_xn,
|
||||
mask=mask,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
amax = tl.max(tl.abs(x))
|
||||
scale = tl.maximum(amax / 448.0, 1e-4)
|
||||
if USE_UE8M0:
|
||||
scale = tl.exp2(tl.ceil(tl.log2(scale)))
|
||||
y = x / scale
|
||||
tl.store(
|
||||
out_ptr + pid_g * stride_yg + row_offsets[:, None] * stride_ym + col_offsets[None, :] * stride_yn,
|
||||
y.to(tl.float8e4nv),
|
||||
mask=mask,
|
||||
)
|
||||
tl.store(sf_ptr + pid_g * stride_sg + pid_m * stride_sm + pid_n * stride_sn, scale, mask=pid_g < groups)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public quantization functions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def unpack_rows_triton(
|
||||
x: torch.Tensor,
|
||||
total_m: int,
|
||||
block_to_group: torch.Tensor,
|
||||
starts_tensor: torch.Tensor,
|
||||
actual_ms_tensor: torch.Tensor,
|
||||
block_starts_tensor: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
out = torch.empty((total_m, x.size(1)), device=x.device, dtype=x.dtype)
|
||||
if total_m == 0:
|
||||
return out
|
||||
grid = (block_to_group.numel(), GROUP_ALIGNMENT // 32, ceil_div(x.size(1), 128))
|
||||
_unpack_grouped_rows_kernel[grid](
|
||||
x,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
out,
|
||||
x.size(1),
|
||||
x.stride(0),
|
||||
x.stride(1),
|
||||
out.stride(0),
|
||||
out.stride(1),
|
||||
BLOCK_M=32,
|
||||
BLOCK_N=128,
|
||||
GROUP_BLOCK_M=GROUP_ALIGNMENT,
|
||||
num_warps=4,
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def per_token_cast_to_fp8_triton(
|
||||
x: torch.Tensor, use_ue8m0: bool, gran_k: int = GROUP_ALIGNMENT
|
||||
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
assert x.dim() == 2
|
||||
assert gran_k == GROUP_ALIGNMENT
|
||||
rows, cols = x.shape
|
||||
out = torch.empty_like(x, dtype=torch.float8_e4m3fn)
|
||||
sf = torch.empty((rows, ceil_div(cols, gran_k)), device=x.device, dtype=torch.float32)
|
||||
grid = lambda meta: (ceil_div(rows, meta["BLOCK_M"]), ceil_div(cols, meta["BLOCK_K"]))
|
||||
_per_token_fp8_kernel[grid](
|
||||
x,
|
||||
out,
|
||||
sf,
|
||||
rows,
|
||||
cols,
|
||||
x.stride(0),
|
||||
x.stride(1),
|
||||
out.stride(0),
|
||||
out.stride(1),
|
||||
sf.stride(0),
|
||||
sf.stride(1),
|
||||
USE_UE8M0=use_ue8m0,
|
||||
BLOCK_M=8,
|
||||
BLOCK_K=gran_k,
|
||||
num_warps=4,
|
||||
)
|
||||
return out, sf
|
||||
|
||||
|
||||
def grouped_per_token_cast_to_fp8_triton(
|
||||
x: torch.Tensor,
|
||||
padded_total_m: int,
|
||||
block_to_group: torch.Tensor,
|
||||
starts_tensor: torch.Tensor,
|
||||
actual_ms_tensor: torch.Tensor,
|
||||
block_starts_tensor: torch.Tensor,
|
||||
use_ue8m0: bool,
|
||||
gran_k: int = GROUP_ALIGNMENT,
|
||||
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
assert x.dim() == 2
|
||||
assert gran_k == GROUP_ALIGNMENT
|
||||
out = torch.empty((padded_total_m, x.size(1)), device=x.device, dtype=torch.float8_e4m3fn)
|
||||
sf = torch.empty(
|
||||
(padded_total_m, ceil_div(x.size(1), gran_k)),
|
||||
device=x.device,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
if block_to_group.numel() == 0:
|
||||
return out, sf
|
||||
grid = (block_to_group.numel(), GROUP_ALIGNMENT // 8, ceil_div(x.size(1), gran_k))
|
||||
_grouped_per_token_fp8_kernel[grid](
|
||||
x,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
out,
|
||||
sf,
|
||||
x.size(1),
|
||||
x.stride(0),
|
||||
x.stride(1),
|
||||
out.stride(0),
|
||||
out.stride(1),
|
||||
sf.stride(0),
|
||||
sf.stride(1),
|
||||
USE_UE8M0=use_ue8m0,
|
||||
BLOCK_M=8,
|
||||
BLOCK_K=gran_k,
|
||||
GROUP_BLOCK_M=GROUP_ALIGNMENT,
|
||||
num_warps=4,
|
||||
)
|
||||
return out, sf
|
||||
|
||||
|
||||
def grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
|
||||
x: torch.Tensor,
|
||||
padded_total_m: int,
|
||||
block_to_group: torch.Tensor,
|
||||
starts_tensor: torch.Tensor,
|
||||
actual_ms_tensor: torch.Tensor,
|
||||
ks_tensor: torch.Tensor,
|
||||
block_starts_tensor: torch.Tensor,
|
||||
use_ue8m0: bool,
|
||||
gran_k: int = GROUP_ALIGNMENT,
|
||||
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
assert x.dim() == 2
|
||||
assert gran_k == GROUP_ALIGNMENT
|
||||
out = torch.empty((padded_total_m * x.size(1),), device=x.device, dtype=torch.float8_e4m3fn)
|
||||
total_blocks = padded_total_m // gran_k
|
||||
sf = torch.empty((total_blocks, x.size(1)), device=x.device, dtype=torch.float32)
|
||||
if block_to_group.numel() == 0:
|
||||
return out, sf.T
|
||||
grid = (block_to_group.numel(), ceil_div(x.size(1), 128))
|
||||
_grouped_per_channel_fp8_sm90_kmajor_kernel[grid](
|
||||
x,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
ks_tensor,
|
||||
block_starts_tensor,
|
||||
out,
|
||||
sf,
|
||||
x.size(1),
|
||||
x.stride(0),
|
||||
x.stride(1),
|
||||
sf.stride(0),
|
||||
sf.stride(1),
|
||||
USE_UE8M0=use_ue8m0,
|
||||
BLOCK_K=gran_k,
|
||||
BLOCK_N=128,
|
||||
num_warps=4,
|
||||
)
|
||||
return out, sf.T
|
||||
|
||||
|
||||
def grouped_per_block_cast_to_fp8_triton(
|
||||
x: torch.Tensor, use_ue8m0: bool, gran_k: int = GROUP_ALIGNMENT
|
||||
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
assert x.dim() == 3
|
||||
assert gran_k == GROUP_ALIGNMENT
|
||||
groups, rows, cols = x.shape
|
||||
out = torch.empty((groups, rows, cols), device=x.device, dtype=torch.float8_e4m3fn)
|
||||
sf = torch.empty(
|
||||
(groups, ceil_div(rows, gran_k), ceil_div(cols, gran_k)),
|
||||
device=x.device,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
grid = (groups, ceil_div(rows, gran_k), ceil_div(cols, gran_k))
|
||||
_grouped_per_block_fp8_kernel[grid](
|
||||
x,
|
||||
out,
|
||||
sf,
|
||||
groups,
|
||||
rows,
|
||||
cols,
|
||||
x.stride(0),
|
||||
x.stride(1),
|
||||
x.stride(2),
|
||||
out.stride(0),
|
||||
out.stride(1),
|
||||
out.stride(2),
|
||||
sf.stride(0),
|
||||
sf.stride(1),
|
||||
sf.stride(2),
|
||||
USE_UE8M0=use_ue8m0,
|
||||
BLOCK_M=gran_k,
|
||||
BLOCK_N=gran_k,
|
||||
num_warps=8,
|
||||
)
|
||||
return out, sf
|
||||
|
||||
|
||||
def per_block_cast_to_fp8_triton(
|
||||
x: torch.Tensor, use_ue8m0: bool, gran_k: int = GROUP_ALIGNMENT
|
||||
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
assert x.dim() == 2
|
||||
out, sf = grouped_per_block_cast_to_fp8_triton(
|
||||
x.unsqueeze(0),
|
||||
use_ue8m0,
|
||||
gran_k,
|
||||
)
|
||||
return out[0], sf[0]
|
||||
@@ -1,5 +1,18 @@
|
||||
# Vendored from tile-ai/tilelang (Apache 2.0), modified for dynamic shapes.
|
||||
|
||||
# TileLang ships a libcudart stub that proxies to the real CUDA runtime via
|
||||
# dlsym(RTLD_DEFAULT, ...). If the stub's own symbols are the first ones found
|
||||
# (because nothing loaded the real libcudart globally yet), the self-check fails
|
||||
# and the stub calls abort(). Pre-loading the real library with RTLD_GLOBAL
|
||||
# ensures dlsym finds it before the stub's own exports.
|
||||
import ctypes as _ctypes
|
||||
|
||||
try:
|
||||
_ctypes.CDLL("libcudart.so", mode=_ctypes.RTLD_GLOBAL)
|
||||
except Exception:
|
||||
# This is expected on CPU-only machines
|
||||
pass
|
||||
|
||||
import tilelang
|
||||
import torch
|
||||
from tilelang import language as T
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
# Vendored from tile-ai/tilelang (Apache 2.0), modified for dynamic shapes.
|
||||
|
||||
# TileLang ships a libcudart stub that proxies to the real CUDA runtime via
|
||||
# dlsym(RTLD_DEFAULT, ...). If the stub's own symbols are the first ones found
|
||||
# (because nothing loaded the real libcudart globally yet), the self-check fails
|
||||
# and the stub calls abort(). Pre-loading the real library with RTLD_GLOBAL
|
||||
# ensures dlsym finds it before the stub's own exports.
|
||||
import ctypes as _ctypes
|
||||
|
||||
try:
|
||||
_ctypes.CDLL("libcudart.so", mode=_ctypes.RTLD_GLOBAL)
|
||||
except Exception:
|
||||
# This is expected on CPU-only machines
|
||||
pass
|
||||
|
||||
import tilelang
|
||||
from tilelang import language as T
|
||||
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
from __future__ import annotations
|
||||
|
||||
try:
|
||||
import deep_gemm
|
||||
except ImportError:
|
||||
deep_gemm = None # CPU-only environments don't ship deep_gemm; FP8 paths
|
||||
# are GPU-only at runtime, so leaving the symbol None is safe — only the
|
||||
# autograd Function bodies below actually call into it.
|
||||
import torch
|
||||
|
||||
from prime_rl.trainer.models.kernels.fp8_utils import (
|
||||
GROUP_ALIGNMENT,
|
||||
build_grouped_layout,
|
||||
grouped_per_block_cast_to_fp8_triton,
|
||||
grouped_per_channel_cast_to_fp8_sm90_kmajor_triton,
|
||||
grouped_per_token_cast_to_fp8_triton,
|
||||
unpack_rows_triton,
|
||||
)
|
||||
|
||||
|
||||
def _compute_grad_weight(
|
||||
x: torch.Tensor,
|
||||
grad_output: torch.Tensor,
|
||||
weight_shape: torch.Size,
|
||||
padded_total_m: int,
|
||||
block_to_group: torch.Tensor,
|
||||
ks_tensor: torch.Tensor,
|
||||
starts_tensor: torch.Tensor,
|
||||
actual_ms_tensor: torch.Tensor,
|
||||
block_starts_tensor: torch.Tensor,
|
||||
aligned_ms: list[int],
|
||||
) -> torch.Tensor:
|
||||
x_k_major = grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
|
||||
x,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
ks_tensor,
|
||||
block_starts_tensor,
|
||||
False,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
dy_k_major = grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
|
||||
grad_output,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
ks_tensor,
|
||||
block_starts_tensor,
|
||||
False,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
grad_weight = torch.zeros(weight_shape, device=x.device, dtype=torch.float32)
|
||||
deep_gemm.k_grouped_fp8_gemm_nt_contiguous(
|
||||
x_k_major,
|
||||
dy_k_major,
|
||||
grad_weight,
|
||||
aligned_ms,
|
||||
ks_tensor,
|
||||
grad_weight,
|
||||
)
|
||||
return grad_weight.to(torch.bfloat16)
|
||||
|
||||
|
||||
class _GroupedFP8Gemm(torch.autograd.Function):
|
||||
@staticmethod
|
||||
def forward(
|
||||
ctx,
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
offs: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
(
|
||||
total_m,
|
||||
padded_total_m,
|
||||
grouped_layout,
|
||||
block_to_group,
|
||||
ks_tensor,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
) = build_grouped_layout(offs, total_m=x.size(0))
|
||||
|
||||
x_fp8 = grouped_per_token_cast_to_fp8_triton(
|
||||
x,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
False,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
weight_fp8 = grouped_per_block_cast_to_fp8_triton(
|
||||
weight.transpose(1, 2),
|
||||
False,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
|
||||
out_padded = torch.empty(
|
||||
(padded_total_m, weight.size(2)),
|
||||
device=x.device,
|
||||
dtype=x.dtype,
|
||||
)
|
||||
deep_gemm.m_grouped_fp8_gemm_nt_contiguous(
|
||||
x_fp8,
|
||||
weight_fp8,
|
||||
out_padded,
|
||||
grouped_layout,
|
||||
use_psum_layout=False,
|
||||
)
|
||||
out = unpack_rows_triton(
|
||||
out_padded,
|
||||
total_m,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
)
|
||||
|
||||
ctx.padded_total_m = padded_total_m
|
||||
ctx.aligned_ms = ks_tensor.tolist()
|
||||
ctx.save_for_backward(
|
||||
x,
|
||||
weight,
|
||||
grouped_layout,
|
||||
block_to_group,
|
||||
ks_tensor,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
)
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad_output: torch.Tensor):
|
||||
(
|
||||
x,
|
||||
weight,
|
||||
grouped_layout,
|
||||
block_to_group,
|
||||
ks_tensor,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
) = ctx.saved_tensors
|
||||
padded_total_m = ctx.padded_total_m
|
||||
aligned_ms = ctx.aligned_ms
|
||||
grad_output = grad_output.contiguous()
|
||||
|
||||
grad_x = grad_weight = None
|
||||
|
||||
if ctx.needs_input_grad[1]:
|
||||
grad_weight = _compute_grad_weight(
|
||||
x,
|
||||
grad_output,
|
||||
weight.shape,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
ks_tensor,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
aligned_ms,
|
||||
)
|
||||
|
||||
if ctx.needs_input_grad[0]:
|
||||
dy_fp8 = grouped_per_token_cast_to_fp8_triton(
|
||||
grad_output,
|
||||
padded_total_m,
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
False,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
weight_dx_fp8 = grouped_per_block_cast_to_fp8_triton(
|
||||
weight,
|
||||
False,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
grad_x_padded = torch.empty(
|
||||
(padded_total_m, weight.size(1)),
|
||||
device=grad_output.device,
|
||||
dtype=grad_output.dtype,
|
||||
)
|
||||
deep_gemm.m_grouped_fp8_gemm_nt_contiguous(
|
||||
dy_fp8,
|
||||
weight_dx_fp8,
|
||||
grad_x_padded,
|
||||
grouped_layout,
|
||||
use_psum_layout=False,
|
||||
)
|
||||
grad_x = unpack_rows_triton(
|
||||
grad_x_padded,
|
||||
x.size(0),
|
||||
block_to_group,
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
)
|
||||
|
||||
return grad_x, grad_weight, None
|
||||
|
||||
|
||||
def grouped_fp8_gemm(
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
offs: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""FP8 grouped GEMM, drop-in replacement for torch._grouped_mm.
|
||||
|
||||
Args:
|
||||
x: (M, K) concatenated token activations in bfloat16.
|
||||
weight: (G, K, N) expert weights in bfloat16.
|
||||
offs: (G,) int32 cumulative token counts per expert.
|
||||
|
||||
Returns:
|
||||
(M, N) output tensor in bfloat16.
|
||||
"""
|
||||
return _GroupedFP8Gemm.apply(x, weight, offs)
|
||||
@@ -0,0 +1,174 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
try:
|
||||
import deep_gemm
|
||||
except ImportError:
|
||||
deep_gemm = None # CPU-only environments don't ship deep_gemm; FP8 paths
|
||||
# are GPU-only at runtime, so leaving the symbol None is safe — only the
|
||||
# autograd Function bodies below actually call into it.
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from prime_rl.trainer.models.kernels.fp8_utils import (
|
||||
per_block_cast_to_fp8_triton,
|
||||
per_token_cast_to_fp8_triton,
|
||||
)
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
class _FP8BlockwiseMM(torch.autograd.Function):
|
||||
@staticmethod
|
||||
def forward(ctx, x, weight, block_size, out_dtype=torch.bfloat16):
|
||||
x_shape = x.shape
|
||||
x_2d = x.reshape(-1, x_shape[-1]).contiguous()
|
||||
x_fp8 = per_token_cast_to_fp8_triton(x_2d, False, block_size)
|
||||
weight_fp8 = per_block_cast_to_fp8_triton(weight, False, block_size)
|
||||
|
||||
out = torch.empty((x_2d.size(0), weight.size(0)), device=x.device, dtype=out_dtype)
|
||||
deep_gemm.fp8_gemm_nt(x_fp8, weight_fp8, out)
|
||||
|
||||
ctx.save_for_backward(x_2d, weight)
|
||||
ctx.x_shape = x_shape
|
||||
ctx.block_size = block_size
|
||||
return out.reshape(*x_shape[:-1], out.size(-1))
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad_output):
|
||||
x_2d, weight = ctx.saved_tensors
|
||||
block_size = ctx.block_size
|
||||
grad_output_2d = grad_output.reshape(-1, grad_output.shape[-1]).contiguous()
|
||||
|
||||
grad_x = grad_weight = None
|
||||
if ctx.needs_input_grad[0]:
|
||||
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, False, block_size)
|
||||
weight_t = weight.transpose(0, 1).contiguous()
|
||||
weight_dx_fp8 = per_block_cast_to_fp8_triton(weight_t, False, block_size)
|
||||
grad_x_2d = torch.empty_like(x_2d)
|
||||
deep_gemm.fp8_gemm_nt(grad_output_fp8, weight_dx_fp8, grad_x_2d)
|
||||
grad_x = grad_x_2d.reshape(ctx.x_shape)
|
||||
|
||||
if ctx.needs_input_grad[1]:
|
||||
# deep_gemm.fp8_gemm_nt with recipe=(1, 1, 128) requires the K (token)
|
||||
# dim to be a multiple of 128. Zero-pad along the token axis so non-
|
||||
# aligned per-rank batches (from sequence packing) don't trip the kernel.
|
||||
M_tok = grad_output_2d.size(0)
|
||||
M_pad = (M_tok + block_size - 1) // block_size * block_size
|
||||
if M_pad != M_tok:
|
||||
pad_rows = M_pad - M_tok
|
||||
grad_output_2d_padded = torch.nn.functional.pad(grad_output_2d, (0, 0, 0, pad_rows))
|
||||
x_2d_padded = torch.nn.functional.pad(x_2d, (0, 0, 0, pad_rows))
|
||||
else:
|
||||
grad_output_2d_padded = grad_output_2d
|
||||
x_2d_padded = x_2d
|
||||
grad_output_t = grad_output_2d_padded.transpose(0, 1).contiguous()
|
||||
x_t = x_2d_padded.transpose(0, 1).contiguous()
|
||||
grad_output_t_fp8 = per_token_cast_to_fp8_triton(grad_output_t, False, block_size)
|
||||
x_t_fp8 = per_token_cast_to_fp8_triton(x_t, False, block_size)
|
||||
grad_weight_fp32 = torch.zeros_like(weight, dtype=torch.float32)
|
||||
deep_gemm.fp8_gemm_nt(
|
||||
grad_output_t_fp8,
|
||||
x_t_fp8,
|
||||
grad_weight_fp32,
|
||||
c=grad_weight_fp32,
|
||||
recipe=(1, 1, 128),
|
||||
)
|
||||
grad_weight = grad_weight_fp32.to(weight.dtype)
|
||||
|
||||
return grad_x, grad_weight, None, None
|
||||
|
||||
|
||||
class Float8BlockwiseLinear(nn.Linear):
|
||||
"""nn.Linear replacement that uses FP8 blockwise matmul via DeepGEMM.
|
||||
|
||||
Requires:
|
||||
- SM90 (Hopper) GPU
|
||||
- bfloat16 inputs/weights
|
||||
- No bias
|
||||
- in_features and out_features divisible by 128
|
||||
"""
|
||||
|
||||
def __init__(self, *args, block_size: int = 128, dtype=torch.bfloat16, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.block_size = block_size
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return _FP8BlockwiseMM.apply(x, self.weight, self.block_size, torch.bfloat16)
|
||||
|
||||
@classmethod
|
||||
def from_linear(cls, mod: nn.Linear) -> "Float8BlockwiseLinear":
|
||||
"""Convert an existing nn.Linear to Float8BlockwiseLinear."""
|
||||
with torch.device("meta"):
|
||||
new_mod = cls(
|
||||
mod.in_features,
|
||||
mod.out_features,
|
||||
bias=mod.bias is not None,
|
||||
)
|
||||
new_mod.weight = mod.weight
|
||||
new_mod.bias = mod.bias
|
||||
return new_mod
|
||||
|
||||
|
||||
DEFAULT_FP8_IGNORE_PATTERNS: list[str] = [
|
||||
"lm_head",
|
||||
"router",
|
||||
"mlp.gate.",
|
||||
"shared_expert_gate", # Qwen3.5 MoE: nn.Linear(hidden, 1, bias=False)
|
||||
"eh_proj",
|
||||
"weights_proj",
|
||||
"in_proj_a",
|
||||
"in_proj_b",
|
||||
]
|
||||
|
||||
|
||||
def replace_linear_with_fp8_blockwise_linear(model: nn.Module, ignore_modules: list[str] | None = None) -> None:
|
||||
"""Replace nn.Linear in `model` with Float8BlockwiseLinear, skipping any
|
||||
module whose qualified name matches an ignore pattern (substring or regex).
|
||||
|
||||
The default ignore list covers layers that should never be quantized:
|
||||
- lm_head
|
||||
- MoE routers and gates (router, mlp.gate., shared_expert_gate)
|
||||
- sparse-MLA scalar projection (weights_proj)
|
||||
- GLM-5.1 MTP head (eh_proj)
|
||||
- hybrid-Mamba projections (in_proj_a, in_proj_b)
|
||||
|
||||
Independently of the name-based ignore list, we also skip any nn.Linear
|
||||
whose in_features or out_features is not a multiple of 128. Float8BlockwiseLinear
|
||||
documents that requirement and DeepGEMM's fp8_gemm_nt crashes at runtime
|
||||
on unaligned dims — better to keep them in BF16 with a clear log line than
|
||||
silently break in the kernel.
|
||||
|
||||
Conv1d, layer norms, and embedding tables are not nn.Linear and are
|
||||
skipped automatically by the type check; we don't need to list them.
|
||||
"""
|
||||
if ignore_modules is None:
|
||||
ignore_modules = list(DEFAULT_FP8_IGNORE_PATTERNS)
|
||||
logger = get_logger()
|
||||
logger.info(f"Replacing linear layers with FP8 blockwise linear layers (ignore={ignore_modules})")
|
||||
replaced_modules = []
|
||||
skipped_modules = []
|
||||
skipped_unaligned: list[str] = []
|
||||
named_modules = dict(model.named_modules())
|
||||
for name, module in named_modules.items():
|
||||
if not isinstance(module, nn.Linear):
|
||||
continue
|
||||
if any(re.search(pattern, name) for pattern in ignore_modules):
|
||||
skipped_modules.append(name)
|
||||
continue
|
||||
if module.in_features % 128 != 0 or module.out_features % 128 != 0:
|
||||
skipped_unaligned.append(f"{name}({module.in_features}->{module.out_features})")
|
||||
continue
|
||||
parent_name, attr_name = name.rsplit(".", 1) if "." in name else ("", name)
|
||||
parent = model.get_submodule(parent_name) if parent_name else model
|
||||
setattr(parent, attr_name, Float8BlockwiseLinear.from_linear(module))
|
||||
replaced_modules.append(name)
|
||||
|
||||
logger.info(
|
||||
f"Replaced {len(replaced_modules)} linear layers with FP8 blockwise linear "
|
||||
f"(skipped {len(skipped_modules)} by name, "
|
||||
f"{len(skipped_unaligned)} by 128-divisibility); "
|
||||
f"first replaced={replaced_modules[:3]}, "
|
||||
f"first skipped(name)={skipped_modules[:3]}, "
|
||||
f"first skipped(unaligned)={skipped_unaligned[:3]}"
|
||||
)
|
||||
@@ -30,6 +30,7 @@ class MoEArgs:
|
||||
top_k: int = 1
|
||||
use_grouped_mm: bool = True # grouped mm or for-loop for the experts computation
|
||||
load_balance_coeff: float | None = 1e-3
|
||||
fp8: bool = False # use FP8 grouped GEMM via DeepGEMM (requires SM90)
|
||||
|
||||
|
||||
# can be used as dense FFN layer or shared experts in MoE layers
|
||||
@@ -144,20 +145,39 @@ def _run_experts_grouped_mm(
|
||||
return _run_experts_grouped_mm_impl(w1, w2, w3, x, num_tokens_per_expert)
|
||||
|
||||
|
||||
def _run_experts_grouped_mm_impl(
|
||||
@expert_parallel
|
||||
def _run_experts_fp8_grouped_mm(
|
||||
w1: torch.Tensor,
|
||||
w2: torch.Tensor,
|
||||
w3: torch.Tensor,
|
||||
x: torch.Tensor,
|
||||
num_tokens_per_expert: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return _run_experts_grouped_mm_impl(w1, w2, w3, x, num_tokens_per_expert, fp8=True)
|
||||
|
||||
|
||||
def _run_experts_grouped_mm_impl(
|
||||
w1: torch.Tensor,
|
||||
w2: torch.Tensor,
|
||||
w3: torch.Tensor,
|
||||
x: torch.Tensor,
|
||||
num_tokens_per_expert: torch.Tensor,
|
||||
fp8: bool = False,
|
||||
) -> torch.Tensor:
|
||||
offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32)
|
||||
# grouped mm between a 2D tensor and a 3D tensor
|
||||
assert x.dim() == 2
|
||||
|
||||
h = F.silu(torch._grouped_mm(x.bfloat16(), w1.bfloat16().transpose(-2, -1), offs=offsets))
|
||||
h = h * torch._grouped_mm(x.bfloat16(), w3.bfloat16().transpose(-2, -1), offs=offsets)
|
||||
out = torch._grouped_mm(h, w2.bfloat16().transpose(-2, -1), offs=offsets).type_as(x)
|
||||
if fp8:
|
||||
from prime_rl.trainer.models.layers.fp8_grouped_gemm import grouped_fp8_gemm
|
||||
|
||||
h = F.silu(grouped_fp8_gemm(x.bfloat16(), w1.bfloat16().transpose(-2, -1), offsets))
|
||||
h = h * grouped_fp8_gemm(x.bfloat16(), w3.bfloat16().transpose(-2, -1), offsets)
|
||||
out = grouped_fp8_gemm(h, w2.bfloat16().transpose(-2, -1), offsets).type_as(x)
|
||||
else:
|
||||
h = F.silu(torch._grouped_mm(x.bfloat16(), w1.bfloat16().transpose(-2, -1), offs=offsets))
|
||||
h = h * torch._grouped_mm(x.bfloat16(), w3.bfloat16().transpose(-2, -1), offs=offsets)
|
||||
out = torch._grouped_mm(h, w2.bfloat16().transpose(-2, -1), offs=offsets).type_as(x)
|
||||
|
||||
return out
|
||||
|
||||
@@ -169,6 +189,7 @@ class GroupedExperts(nn.Module):
|
||||
hidden_dim: int,
|
||||
num_experts: int,
|
||||
use_grouped_mm: bool,
|
||||
fp8: bool = False,
|
||||
):
|
||||
super().__init__()
|
||||
self.num_experts = num_experts
|
||||
@@ -176,6 +197,7 @@ class GroupedExperts(nn.Module):
|
||||
self.w2 = nn.Parameter(torch.empty(num_experts, dim, hidden_dim))
|
||||
self.w3 = nn.Parameter(torch.empty(num_experts, hidden_dim, dim))
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
self.fp8 = fp8
|
||||
self.ep_comm_backend: EPCommBackend = "torch"
|
||||
|
||||
def set_ep_comm_backend(self, backend: EPCommBackend) -> None:
|
||||
@@ -186,7 +208,7 @@ class GroupedExperts(nn.Module):
|
||||
w2 = self.w2.to_local()
|
||||
w3 = self.w3.to_local()
|
||||
if self.use_grouped_mm:
|
||||
return _run_experts_grouped_mm_impl(w1, w2, w3, x, num_tokens_per_expert)
|
||||
return _run_experts_grouped_mm_impl(w1, w2, w3, x, num_tokens_per_expert, fp8=self.fp8)
|
||||
return _run_experts_for_loop_impl(w1, w2, w3, x, num_tokens_per_expert)
|
||||
|
||||
def forward(
|
||||
@@ -198,6 +220,8 @@ class GroupedExperts(nn.Module):
|
||||
return self._forward_deepep(x, num_tokens_per_expert)
|
||||
|
||||
if self.use_grouped_mm:
|
||||
if self.fp8:
|
||||
return _run_experts_fp8_grouped_mm(self.w1, self.w2, self.w3, x, num_tokens_per_expert)
|
||||
return _run_experts_grouped_mm(self.w1, self.w2, self.w3, x, num_tokens_per_expert)
|
||||
else:
|
||||
return _run_experts_for_loop(self.w1, self.w2, self.w3, x, num_tokens_per_expert)
|
||||
@@ -534,6 +558,7 @@ class MoE(nn.Module):
|
||||
hidden_dim=hidden_dim,
|
||||
num_experts=num_experts,
|
||||
use_grouped_mm=moe_args.use_grouped_mm,
|
||||
fp8=moe_args.fp8,
|
||||
)
|
||||
self.ep_comm_backend: EPCommBackend = "torch"
|
||||
self.experts.set_ep_comm_backend(self.ep_comm_backend)
|
||||
@@ -799,12 +824,19 @@ def _run_nongated_experts_grouped_mm_impl(
|
||||
_w3: torch.Tensor,
|
||||
x: torch.Tensor,
|
||||
num_tokens_per_expert: torch.Tensor,
|
||||
fp8: bool = False,
|
||||
) -> torch.Tensor:
|
||||
offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32)
|
||||
assert x.dim() == 2
|
||||
|
||||
h = relu2(torch._grouped_mm(x.bfloat16(), w1.bfloat16().transpose(-2, -1), offs=offsets))
|
||||
out = torch._grouped_mm(h, w2.bfloat16().transpose(-2, -1), offs=offsets).type_as(x)
|
||||
if fp8:
|
||||
from prime_rl.trainer.models.layers.fp8_grouped_gemm import grouped_fp8_gemm
|
||||
|
||||
h = relu2(grouped_fp8_gemm(x.bfloat16(), w1.bfloat16().transpose(-2, -1), offsets))
|
||||
out = grouped_fp8_gemm(h, w2.bfloat16().transpose(-2, -1), offsets).type_as(x)
|
||||
else:
|
||||
h = relu2(torch._grouped_mm(x.bfloat16(), w1.bfloat16().transpose(-2, -1), offs=offsets))
|
||||
out = torch._grouped_mm(h, w2.bfloat16().transpose(-2, -1), offs=offsets).type_as(x)
|
||||
return out
|
||||
|
||||
|
||||
@@ -819,6 +851,17 @@ def _run_nongated_experts_grouped_mm(
|
||||
return _run_nongated_experts_grouped_mm_impl(w1, w2, _w3, x, num_tokens_per_expert)
|
||||
|
||||
|
||||
@expert_parallel
|
||||
def _run_nongated_experts_fp8_grouped_mm(
|
||||
w1: torch.Tensor,
|
||||
w2: torch.Tensor,
|
||||
_w3: torch.Tensor,
|
||||
x: torch.Tensor,
|
||||
num_tokens_per_expert: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return _run_nongated_experts_grouped_mm_impl(w1, w2, _w3, x, num_tokens_per_expert, fp8=True)
|
||||
|
||||
|
||||
class NonGatedGroupedExperts(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
@@ -826,6 +869,7 @@ class NonGatedGroupedExperts(nn.Module):
|
||||
intermediate_dim: int,
|
||||
num_experts: int,
|
||||
use_grouped_mm: bool,
|
||||
fp8: bool = False,
|
||||
):
|
||||
super().__init__()
|
||||
self.num_experts = num_experts
|
||||
@@ -834,6 +878,7 @@ class NonGatedGroupedExperts(nn.Module):
|
||||
# Dummy w3 for @expert_parallel decorator compatibility (expects w1, w2, w3 signature)
|
||||
self.w3 = nn.Parameter(torch.empty(0))
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
self.fp8 = fp8
|
||||
self.ep_comm_backend: EPCommBackend = "torch"
|
||||
|
||||
def set_ep_comm_backend(self, backend: EPCommBackend) -> None:
|
||||
@@ -844,7 +889,7 @@ class NonGatedGroupedExperts(nn.Module):
|
||||
w2 = self.w2.to_local()
|
||||
w3 = self.w3.to_local()
|
||||
if self.use_grouped_mm:
|
||||
return _run_nongated_experts_grouped_mm_impl(w1, w2, w3, x, num_tokens_per_expert)
|
||||
return _run_nongated_experts_grouped_mm_impl(w1, w2, w3, x, num_tokens_per_expert, fp8=self.fp8)
|
||||
return _run_nongated_experts_for_loop_impl(w1, w2, w3, x, num_tokens_per_expert)
|
||||
|
||||
def forward(
|
||||
@@ -855,6 +900,8 @@ class NonGatedGroupedExperts(nn.Module):
|
||||
if self.ep_comm_backend == "deepep":
|
||||
return self._forward_deepep(x, num_tokens_per_expert)
|
||||
if self.use_grouped_mm:
|
||||
if self.fp8:
|
||||
return _run_nongated_experts_fp8_grouped_mm(self.w1, self.w2, self.w3, x, num_tokens_per_expert)
|
||||
return _run_nongated_experts_grouped_mm(self.w1, self.w2, self.w3, x, num_tokens_per_expert)
|
||||
else:
|
||||
return _run_nongated_experts_for_loop(self.w1, self.w2, self.w3, x, num_tokens_per_expert)
|
||||
@@ -971,6 +1018,7 @@ class LatentMoE(nn.Module):
|
||||
routed_scaling_factor: float,
|
||||
use_grouped_mm: bool,
|
||||
load_balance_coeff: float | None,
|
||||
fp8: bool = False,
|
||||
):
|
||||
super().__init__()
|
||||
effective_latent_dim = latent_dim if latent_dim is not None else dim
|
||||
@@ -988,6 +1036,7 @@ class LatentMoE(nn.Module):
|
||||
intermediate_dim=moe_intermediate_size,
|
||||
num_experts=num_experts,
|
||||
use_grouped_mm=use_grouped_mm,
|
||||
fp8=fp8,
|
||||
)
|
||||
self.ep_comm_backend: EPCommBackend = "torch"
|
||||
self.experts.set_ep_comm_backend(self.ep_comm_backend)
|
||||
|
||||
@@ -55,6 +55,7 @@ class MiniMaxM2DecoderLayer(GradientCheckpointingLayer):
|
||||
top_k=config.num_experts_per_tok,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
load_balance_coeff=1e-3 if config.use_routing_bias else None,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.intermediate_size)
|
||||
|
||||
|
||||
@@ -257,6 +257,7 @@ class NemotronHMoELayer(GradientCheckpointingLayer):
|
||||
routed_scaling_factor=config.routed_scaling_factor,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
load_balance_coeff=config.load_balance_coeff,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
|
||||
def forward(
|
||||
|
||||
@@ -613,6 +613,7 @@ class Qwen3_5MoeDecoderLayer(GradientCheckpointingLayer):
|
||||
top_k=config.num_experts_per_tok,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
load_balance_coeff=config.load_balance_coeff,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
|
||||
|
||||
|
||||
@@ -73,6 +73,7 @@ class Qwen3MoeDecoderLayer(GradientCheckpointingLayer):
|
||||
top_k=config.num_experts_per_tok,
|
||||
use_grouped_mm=config.use_grouped_mm,
|
||||
load_balance_coeff=config.load_balance_coeff,
|
||||
fp8=getattr(config, "fp8", False),
|
||||
)
|
||||
mlp_config = MLPConfig(
|
||||
hidden_size=config.hidden_size,
|
||||
|
||||
@@ -11,7 +11,7 @@ supported-markers = [
|
||||
]
|
||||
|
||||
[options]
|
||||
exclude-newer = "2026-04-27T23:51:18.884329218Z"
|
||||
exclude-newer = "2026-04-29T22:09:49.355713533Z"
|
||||
exclude-newer-span = "P7D"
|
||||
|
||||
[options.exclude-newer-package]
|
||||
@@ -704,10 +704,10 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "deep-gemm"
|
||||
version = "2.3.0+477618c"
|
||||
source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.3.0+477618c-cp312-cp312-linux_x86_64.whl" }
|
||||
version = "2.3.0+d30fc36"
|
||||
source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.3.0+d30fc36-cp312-cp312-linux_x86_64.whl" }
|
||||
wheels = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.3.0+477618c-cp312-cp312-linux_x86_64.whl", hash = "sha256:a40cea03705cfa50eefe5651d91e3e7ebf87a53acf06cde8bbb877fb95f0f921" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.3.0+d30fc36-cp312-cp312-linux_x86_64.whl", hash = "sha256:dfa8dbeff3d820193f4f94b75f12734c7d73650495e9e8bbdb276953316db6f9" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2856,7 +2856,7 @@ requires-dist = [
|
||||
{ name = "color-codeword", marker = "extra == 'envs'", index = "https://hub.primeintellect.ai/primeintellect/simple/" },
|
||||
{ name = "datasets", specifier = ">=4.0.0" },
|
||||
{ name = "deep-ep", marker = "platform_machine == 'x86_64' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+73b6ea4-cp312-cp312-linux_x86_64.whl" },
|
||||
{ name = "deep-gemm", marker = "platform_machine == 'x86_64' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.3.0+477618c-cp312-cp312-linux_x86_64.whl" },
|
||||
{ name = "deep-gemm", marker = "platform_machine == 'x86_64' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.3.0+d30fc36-cp312-cp312-linux_x86_64.whl" },
|
||||
{ name = "deepdive", marker = "extra == 'envs'", index = "https://hub.primeintellect.ai/primeintellect/simple/" },
|
||||
{ name = "dion", git = "https://github.com/samsja/dion.git?rev=d891eeb" },
|
||||
{ name = "flash-attn", marker = "platform_machine == 'x86_64' and extra == 'flash-attn'", url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.4/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_x86_64.whl" },
|
||||
|
||||
Reference in New Issue
Block a user