File size: 20,896 Bytes
688186a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 | 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
|