Inkling-2-Mini-NVFP4-M2 / vllm /overlay.diff
sambit9238's picture
Inkling-2-Mini NVFP4 M2: W4A16 local attention + lm_head, NVFP4 L20-23 experts
688186a verified
Raw History Blame Contribute Delete
20.9 kB
diff -ruN -x __pycache__ vllm_inkling2_orig/nvidia/attention.py ../overlay/inkling2/nvidia/attention.py
--- vllm_inkling2_orig/nvidia/attention.py 2026-11-20 22:41:42.000000000 +0530
+++ ../overlay/inkling2/nvidia/attention.py 2026-11-22 19:03:43.070337796 +0530
@@ -62,6 +62,7 @@
from .ops.linear import linear
from .ops.sconv import attention_prologue, shift_rel_proj
from .sconv import K_STREAM, V_STREAM, Inkling2ShortConv, conv_metadata
+from .w4a16 import W4A16Linear
@dataclass
@@ -186,9 +187,13 @@
conv_state: InklingConvState,
prefix: str,
pass_conv_states: tuple[InklingConvState, ...] = (),
+ w4a16: bool = False,
) -> None:
+ """`w4a16` holds the q_side / k / v / o projections as NVFP4
+ weight-only Marlin linears (local layers, TP 1, no LoRA)."""
super().__init__()
self.prefix = prefix
+ self.w4a16 = w4a16
self.is_local = is_local
num_heads = (
config.swa_num_attention_heads if is_local else config.num_attention_heads
@@ -231,19 +236,38 @@
pad_size = -sum(self.split_sizes) % 8
if pad_size:
self.split_sizes.append(pad_size)
- self.qkvr = MergedColumnParallelLinear(
- config.hidden_size,
- [size * tp_size for size in self.split_sizes],
- bias=False,
- prefix=f"{prefix}.qkvr",
- )
- self.wo_ud = RowParallelLinear(
- q_size * tp_size,
- config.hidden_size,
- bias=False,
- reduce_results=False,
- prefix=f"{prefix}.wo_ud",
- )
+ if w4a16:
+ if not is_local or tp_size != 1:
+ raise ValueError(
+ f"{prefix}: NVFP4 W4A16 attention needs a local layer and TP 1"
+ )
+ if get_current_vllm_config().lora_config is not None:
+ raise ValueError(
+ f"{prefix}: LoRA is not supported on NVFP4 W4A16 attention "
+ "layers; serve without --enable-lora or use a checkpoint "
+ "without an nvfp4_w4a16 group"
+ )
+ # Checkpoint layout: q_side = rows of wq_du, wr_du, gate_attn,
+ # attn_sink_proj; wk_dv and wv_dv are separate.
+ hidden = config.hidden_size
+ self.q_side = W4A16Linear(q_side, hidden)
+ self.wk_dv = W4A16Linear(kv_size, hidden)
+ self.wv_dv = W4A16Linear(kv_size, hidden)
+ self.wo_ud = W4A16Linear(hidden, q_size)
+ else:
+ self.qkvr = MergedColumnParallelLinear(
+ config.hidden_size,
+ [size * tp_size for size in self.split_sizes],
+ bias=False,
+ prefix=f"{prefix}.qkvr",
+ )
+ self.wo_ud = RowParallelLinear(
+ q_size * tp_size,
+ config.hidden_size,
+ bias=False,
+ reduce_results=False,
+ prefix=f"{prefix}.wo_ud",
+ )
self.rel_logits_proj = nn.Parameter(
torch.empty(self.d_rel, self.rel_extent), requires_grad=False
)
@@ -307,6 +331,12 @@
_INKLING2_FA4_REL_ATTENTION_KERNEL.register_warmup()
def process_weights_after_loading(self) -> None:
+ if self.w4a16:
+ # vLLM's finalize_model_weights already ran each child's own hook
+ # (children first); prepare here only when called directly (tests).
+ for linear_ in (self.q_side, self.wk_dv, self.wv_dv, self.wo_ud):
+ if not linear_.w4a16_prepared:
+ linear_.process_weights_after_loading()
self.rel_proj_shifted = shift_rel_proj(self.rel_logits_proj, self.is_local)
def get_attn_backend(self) -> type[AttentionBackend]:
@@ -330,6 +360,10 @@
def _project(
self, x_q: torch.Tensor, x_k: torch.Tensor, x_v: torch.Tensor
) -> list[torch.Tensor]:
+ if self.w4a16:
+ # Always three GEMMs, whether or not the inputs are shared.
+ q_side = self.q_side(x_q).split(self.split_sizes[:4], dim=-1)
+ return [*q_side, self.wk_dv(x_k), self.wv_dv(x_v)]
# ``linear`` on the weight bypasses the layer (and a LoRA wrapper's
# forward), so the LoRA deltas are added here (no-op without LoRA).
weight = self.qkvr.weight
@@ -395,6 +429,11 @@
output,
pass_idx,
)
+ if self.w4a16:
+ projected = self.wo_ud(output)
+ if out is None:
+ return projected
+ return out.copy_(projected)
out = linear(output, self.wo_ud.weight, out)
add_linear_lora(self.wo_ud, out, output)
return out
diff -ruN -x __pycache__ vllm_inkling2_orig/nvidia/dspark.py ../overlay/inkling2/nvidia/dspark.py
--- vllm_inkling2_orig/nvidia/dspark.py 2026-11-20 22:41:42.000000000 +0530
+++ ../overlay/inkling2/nvidia/dspark.py 2026-11-22 07:50:23.647303937 +0530
@@ -48,6 +48,7 @@
silu_and_mul,
)
from .ops.linear import linear
+from .w4a16 import head_dequantized_t, head_logits, is_w4a16_head
class _RMSNorm(nn.Module):
@@ -487,7 +488,10 @@
"""Finish sharing the target's normalized embeddings and LM head (its
`embed_tokens` and `lm_head` are aliased by `load_dspark_model`)
and derive the weights that depend on them."""
- assert self.lm_head is not None and self.lm_head.weight.dtype == torch.bfloat16
+ assert self.lm_head is not None
+ assert is_w4a16_head(self.lm_head) or (
+ self.lm_head.weight.dtype == torch.bfloat16
+ )
self.model.embed_norm = target_model.model.embed_norm
head = self.model.markov_head
head.rnn_bias = torch.empty_like(head.rnn_proj.bias, dtype=torch.float32)
@@ -501,7 +505,16 @@
assert self.lm_head is not None
head = self.model.markov_head
assert head.rnn_bias is not None
- head.fold(self.lm_head.weight)
+ if is_w4a16_head(self.lm_head):
+ # The packed head is Marlin-repacked; fold from its dequantized
+ # rows (a transient of 2 * vocab * hidden bytes).
+ weight_t = head_dequantized_t(self.lm_head)
+ # fold's tensors take the dtype of what it is given; bf16 as with
+ # the unquantized head (the head itself may compute in fp16).
+ head.fold(weight_t.t().to(torch.bfloat16))
+ del weight_t
+ else:
+ head.fold(self.lm_head.weight)
head.rnn_bias.copy_(head.rnn_proj.bias)
self.model.fuse_alpha.copy_(
torch.softmax(self.model.fuse_weight.float(), dim=-1)
@@ -544,6 +557,8 @@
def compute_base_logits(self, hidden_states: torch.Tensor) -> torch.Tensor:
"""TP-local bf16 base logits (bf16 GEMM, as the reference)."""
assert self.lm_head is not None
+ if is_w4a16_head(self.lm_head):
+ return head_logits(self.lm_head, hidden_states).to(hidden_states.dtype)
return linear(hidden_states, self.lm_head.weight)
def markov_step(
diff -ruN -x __pycache__ vllm_inkling2_orig/nvidia/model.py ../overlay/inkling2/nvidia/model.py
--- vllm_inkling2_orig/nvidia/model.py 2026-11-20 22:41:42.000000000 +0530
+++ ../overlay/inkling2/nvidia/model.py 2026-11-22 07:43:43.762544373 +0530
@@ -76,12 +76,16 @@
from .ops.seq_parallel import SeqParallel
from .sconv import ATTN_STREAM, MLP_STREAM, Inkling2ShortConv, conv_metadata
from .vision import Inkling2VisionEncoder, VisionMetadata
+from .w4a16 import W4A16HeadMethod, is_w4a16_head
class Inkling2LogitsProcessor(LogitsProcessor):
"""Use the low-M projection while preserving vocab gathering and softcaps."""
def _apply_head(self, lm_head, hidden_states, embedding_bias):
+ if is_w4a16_head(lm_head):
+ assert embedding_bias is None
+ return lm_head.quant_method.apply(lm_head, hidden_states)
from vllm.model_executor.layers.linear import UnquantizedLinearMethod
from vllm.model_executor.layers.vocab_parallel_embedding import (
UnquantizedEmbeddingMethod,
@@ -197,6 +201,7 @@
self.conv_state,
prefix=f"{prefix}.attn",
pass_conv_states=self.conv_states[1:],
+ w4a16=quant_config is not None and quant_config.is_w4a16_attn(layer_id),
)
eps = config.rms_norm_eps
# Local layers: attn_norm; full layers: q/k/v_input_norm, stacked.
@@ -572,8 +577,13 @@
model_cls = Inkling2LoopModel
self.model = model_cls(text_config, quant_config, f"{prefix}model")
+ w4a16_head = quant_config is not None and quant_config.w4a16_lm_head
+ if w4a16_head and vllm_config.lora_config is not None:
+ raise ValueError("LoRA is not supported with an NVFP4 W4A16 lm_head")
self.lm_head = ParallelLMHead(
- text_config.padded_vocab_size, text_config.hidden_size
+ text_config.padded_vocab_size,
+ text_config.hidden_size,
+ quant_method=W4A16HeadMethod() if w4a16_head else None,
)
processor = (
Inkling2LogitsProcessor
@@ -772,7 +782,9 @@
for old, new in self._renames:
name = name.replace(old, new)
shard_id = None
- for old, (new, shard) in self._shards.items():
+ # NVFP4 W4A16 attention tensors (q_side, wk_dv, ...) are params of
+ # their own; only names without one are shards of a fused weight.
+ for old, (new, shard) in ([] if name in params else self._shards.items()):
if old in name:
name = name.replace(old, new)
shard_id = shard
diff -ruN -x __pycache__ vllm_inkling2_orig/nvidia/w4a16.py ../overlay/inkling2/nvidia/w4a16.py
--- vllm_inkling2_orig/nvidia/w4a16.py 1970-01-01 05:30:00.000000000 +0530
+++ ../overlay/inkling2/nvidia/w4a16.py 2026-11-22 07:50:29.993434768 +0530
@@ -0,0 +1,202 @@
+# SPDX-License-Identifier: Apache-2.0
+# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
+"""NVFP4 weight-only (W4A16) linears on FP4 Marlin, loaded in ModelOpt layout.
+
+Checkpoint tensors per linear (`<name>.weight` etc.):
+ weight uint8 [N, K/2] two e2m1 nibbles per byte (even k low)
+ weight_scale fp8e4m3 [N, K/16] per-16-group scale
+ weight_scale_2 fp32 [] per-tensor scale
+ W[n, k] = e2m1(nibble) * weight_scale[n, k // 16] * weight_scale_2
+
+vLLM's Marlin `weight_global_scale` multiplies in the same way (ModelOpt's
+`weight_scale_2` is passed through unchanged), so no inversion is needed.
+"""
+
+import os
+
+import torch
+from torch import nn
+
+from vllm.model_executor.layers.quantization.base_config import QuantizeMethodBase
+from vllm.model_executor.layers.quantization.utils.marlin_utils_fp4 import (
+ apply_fp4_marlin_linear,
+ prepare_fp4_layer_for_marlin,
+)
+from vllm.logger import init_logger
+
+logger = init_logger(__name__)
+
+GROUP_SIZE = 16
+LOGIT_WARN = 1e4
+
+
+def default_head_dtype() -> torch.dtype:
+ """fp16 (about 8x finer logits than bf16) unless
+ INKLING2_W4A16_HEAD_DTYPE=bfloat16."""
+ name = os.environ.get("INKLING2_W4A16_HEAD_DTYPE", "float16")
+ if name not in ("float16", "bfloat16"):
+ raise ValueError(f"INKLING2_W4A16_HEAD_DTYPE must be float16 or bfloat16: {name}")
+ return getattr(torch, name)
+
+
+def _load(param: nn.Parameter, loaded: torch.Tensor) -> None:
+ param.data.copy_(loaded)
+
+
+def _no_reload(param: nn.Parameter, loaded: torch.Tensor) -> None:
+ raise RuntimeError(
+ "NVFP4 W4A16 weights were already Marlin-repacked and cannot be "
+ "reloaded (weight reload / RL refit is not supported with an "
+ "nvfp4_w4a16 checkpoint)"
+ )
+
+
+class _W4A16Params:
+ """Allocation and Marlin repacking shared by `W4A16Linear` and the head."""
+
+ @staticmethod
+ def register(
+ layer: nn.Module, n: int, k: int, compute_dtype: torch.dtype
+ ) -> None:
+ assert k % GROUP_SIZE == 0
+ layer.output_size_per_partition = n
+ layer.input_size_per_partition = k
+ layer.params_dtype = compute_dtype
+ layer.w4a16_prepared = False
+ for name, shape, dtype in (
+ ("weight", (n, k // 2), torch.uint8),
+ ("weight_scale", (n, k // GROUP_SIZE), torch.float8_e4m3fn),
+ ("weight_scale_2", (), torch.float32),
+ ):
+ param = nn.Parameter(torch.empty(shape, dtype=dtype), requires_grad=False)
+ param.weight_loader = _load
+ layer.register_parameter(name, param)
+
+ @staticmethod
+ def prepare(layer: nn.Module) -> None:
+ if layer.w4a16_prepared:
+ raise RuntimeError("NVFP4 W4A16 layer was already prepared for Marlin")
+ # prepare_fp4_layer_for_marlin reads `weight_global_scale`.
+ layer.weight_global_scale = nn.Parameter(
+ layer.weight_scale_2.data.clone(), requires_grad=False
+ )
+ prepare_fp4_layer_for_marlin(layer)
+ # weight_scale_2 stays (a scalar) so a reload reaches `_no_reload`.
+ for name in ("weight", "weight_scale", "weight_scale_2"):
+ getattr(layer, name).weight_loader = _no_reload
+ layer.w4a16_prepared = True
+ layer.w4a16_checked = not getattr(layer, "w4a16_check", False)
+
+ @staticmethod
+ def apply(layer: nn.Module, x: torch.Tensor) -> torch.Tensor:
+ assert layer.w4a16_prepared, "process_weights_after_loading was not run"
+ # workspace=None: Marlin takes its (persistent, graph-safe) lock buffer
+ # from the worker's workspace manager instead of allocating per call.
+ out = apply_fp4_marlin_linear(
+ x.to(layer.params_dtype),
+ layer.weight,
+ layer.weight_scale,
+ layer.weight_global_scale,
+ None,
+ layer.output_size_per_partition,
+ layer.input_size_per_partition,
+ )
+ if not layer.w4a16_checked and not torch.cuda.is_current_stream_capturing():
+ # Once, at the first eager call: fp16 logits overflow at 65504.
+ layer.w4a16_checked = True
+ hid, raw = x.abs().max().item(), out.abs().max().item()
+ if hid > LOGIT_WARN or raw > LOGIT_WARN:
+ logger.warning(
+ "NVFP4 W4A16 head: max|hidden|=%.3g, max|logit|=%.3g exceed "
+ "%.0e; %s logits may overflow or lose precision",
+ hid, raw, LOGIT_WARN, layer.params_dtype,
+ )
+ return out
+
+ @staticmethod
+ def dequantize(layer: nn.Module) -> torch.Tensor:
+ """bf16 `W^T` [K, N] of a prepared layer (the Marlin GEMM on an
+ identity); a transient of 2*N*K bytes."""
+ k = layer.input_size_per_partition
+ eye = torch.eye(k, dtype=layer.params_dtype, device=layer.weight.device)
+ checked, layer.w4a16_checked = layer.w4a16_checked, True
+ try:
+ return _W4A16Params.apply(layer, eye)
+ finally:
+ layer.w4a16_checked = checked
+
+
+class W4A16Linear(nn.Module):
+ """`x @ W.T` over an NVFP4 weight (bias-free), at the checkpoint's layout."""
+
+ def __init__(
+ self, n: int, k: int, compute_dtype: torch.dtype = torch.bfloat16
+ ) -> None:
+ super().__init__()
+ _W4A16Params.register(self, n, k, compute_dtype)
+
+ def process_weights_after_loading(self) -> None:
+ _W4A16Params.prepare(self)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return _W4A16Params.apply(self, x)
+
+
+class W4A16HeadMethod(QuantizeMethodBase):
+ """Quant method of a `ParallelLMHead` whose weight is NVFP4: allocates the
+ packed tensors instead of the bf16 weight. `apply` returns fp32 logits of
+ this rank's vocab shard (as the fp32 head does)."""
+
+ def __init__(self, compute_dtype: torch.dtype | None = None) -> None:
+ super().__init__()
+ self.compute_dtype = compute_dtype or default_head_dtype()
+
+ def create_weights(
+ self,
+ layer: nn.Module,
+ input_size_per_partition: int,
+ output_partition_sizes: list[int],
+ input_size: int,
+ output_size: int,
+ params_dtype: torch.dtype,
+ **extra_weight_attrs,
+ ) -> None:
+ tp_size = getattr(layer, "tp_size", 1)
+ assert tp_size == 1, f"the NVFP4 W4A16 lm_head needs TP 1, got TP {tp_size}"
+ _W4A16Params.register(
+ layer,
+ sum(output_partition_sizes),
+ input_size_per_partition,
+ self.compute_dtype,
+ )
+ layer.w4a16 = True
+ layer.w4a16_check = True
+
+ def process_weights_after_loading(self, layer: nn.Module) -> None:
+ _W4A16Params.prepare(layer)
+
+ def apply(
+ self,
+ layer: nn.Module,
+ x: torch.Tensor,
+ bias: torch.Tensor | None = None,
+ ) -> torch.Tensor:
+ assert bias is None
+ return _W4A16Params.apply(layer, x).float()
+
+ def embedding(self, layer: nn.Module, input_: torch.Tensor) -> torch.Tensor:
+ raise NotImplementedError("the NVFP4 head is not an embedding table")
+
+
+def is_w4a16_head(lm_head: nn.Module) -> bool:
+ return getattr(lm_head, "w4a16", False)
+
+
+def head_logits(lm_head: nn.Module, x: torch.Tensor) -> torch.Tensor:
+ """Marlin logits of this rank's shard in the head's compute dtype."""
+ return _W4A16Params.apply(lm_head, x)
+
+
+def head_dequantized_t(lm_head: nn.Module) -> torch.Tensor:
+ """bf16-or-fp16 `W^T` [K, N] of the quantized head."""
+ return _W4A16Params.dequantize(lm_head)
diff -ruN -x __pycache__ vllm_inkling2_orig/quant_config.py ../overlay/inkling2/quant_config.py
--- vllm_inkling2_orig/quant_config.py 2026-11-20 22:41:42.000000000 +0530
+++ ../overlay/inkling2/quant_config.py 2026-11-22 07:43:23.376576705 +0530
@@ -3,11 +3,14 @@
"""Per-tensor precision metadata of Inkling2 checkpoints (hf_quant_config.json).
Only the routed experts are quantized (NVFP4 or MXFP8); they are handled by
-`Inkling2MoE`. Every other layer runs unquantized.
+`Inkling2MoE`. Every other layer runs unquantized, except those listed in an
+"nvfp4_w4a16" group (overlay): the attention linears of some local layers and
+the lm_head, as NVFP4 weight-only (see `nvidia/w4a16.py`).
"""
from __future__ import annotations
+import re
from typing import Any
import torch
@@ -19,19 +22,40 @@
)
from vllm.models.inkling2.configs import INKLING2_ARCHITECTURES
-_COMPUTE_DTYPES = ("float32", "bfloat16", "mxfp8", "nvfp4")
+_COMPUTE_DTYPES = ("float32", "bfloat16", "mxfp8", "nvfp4", "nvfp4_w4a16")
+_W4A16_ATTN = re.compile(r"^model\.llm\.layers\.(\d+)\.attn\.(q_side|wk_dv|wv_dv|wo_ud)\.weight$")
+_W4A16_HEAD = "model.llm.unembed.weight"
class Inkling2QuantConfig(QuantizationConfig):
def __init__(self, config: dict[str, Any]) -> None:
super().__init__()
self.mxfp8_weights: set[str] = set()
+ self.w4a16_weights: set[str] = set()
for group in config["model"]["parameter_groups"]:
compute = group["compute_dtype"]
if compute not in _COMPUTE_DTYPES:
raise ValueError(f"Unsupported Inkling2 compute dtype: {compute}")
if compute == "mxfp8":
self.mxfp8_weights.update(group["tensors"])
+ elif compute == "nvfp4_w4a16":
+ self.w4a16_weights.update(group["tensors"])
+ self.w4a16_attn_layers: set[int] = set()
+ parts: dict[int, set[str]] = {}
+ for name in self.w4a16_weights:
+ if name == _W4A16_HEAD:
+ continue
+ m = _W4A16_ATTN.match(name)
+ if m is None:
+ raise ValueError(f"Unsupported nvfp4_w4a16 tensor: {name}")
+ parts.setdefault(int(m.group(1)), set()).add(m.group(2))
+ for layer_id, names in parts.items():
+ if names != {"q_side", "wk_dv", "wv_dv", "wo_ud"}:
+ raise ValueError(
+ f"nvfp4_w4a16 layer {layer_id} must list q_side, wk_dv, "
+ f"wv_dv and wo_ud, got {sorted(names)}"
+ )
+ self.w4a16_attn_layers.add(layer_id)
@classmethod
def get_name(cls) -> QuantizationMethods:
@@ -76,3 +100,10 @@
def is_mxfp8_layer(self, layer_id: int) -> bool:
name = f"model.llm.layers.{layer_id}.mlp.experts.w13_weight"
return name in self.mxfp8_weights
+
+ def is_w4a16_attn(self, layer_id: int) -> bool:
+ return layer_id in self.w4a16_attn_layers
+
+ @property
+ def w4a16_lm_head(self) -> bool:
+ return _W4A16_HEAD in self.w4a16_weights