Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

56.3 KB
Raw Blame
from __future__ import annotations
from functools import cached_property
from typing_extensions import override
import torch
import numpy as np
from ..model.config import Config
from . import Module
from .quant import LinearFP16, LinearEXL3
from .quant.exl3_lib import quantize_exl3, quantize_exl3_batch
from ..ext import exllamav3_ext as ext
from ..model.model_tp_alloc import TPAllocation
import os
import time as _time

# EXL3_QUANT_PROFILE=1: host-wall accumulator for capture_H, printed per module by
# convert_model (stage=capture_split). Wall time includes any device-sync stall that
# happens inside the call; the counters themselves add no syncs or allocations.
_CAP_PROFILE = os.environ.get("EXL3_QUANT_PROFILE") == "1"
CAP_STAT = {"wall": 0.0, "calls": 0}
FLUSH_STAT = {"wall": 0.0, "calls": 0}
# EXL3_CAPTURE_LEGACY=1 restores the pre-batch path (per-call host sync on the finiteness
# check, per-call fp32 copy, immediate addmm_). Default is the deferred batched flush.
_CAP_LEGACY = os.environ.get("EXL3_CAPTURE_LEGACY") == "1"

# MXFP4 (e2m1 + e8m0 block scale) as stored by gpt-oss: each 16-byte block packs 32 fp4 values
# (low nibble first), one power-of-two scale byte per block
_MXFP4_LUT = [
    +0.0, +0.5, +1.0, +1.5, +2.0, +3.0, +4.0, +6.0,
    -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0,
]

def _mxfp4_dequant(blocks: torch.Tensor, scales: torch.Tensor) -> torch.Tensor:
    """(N, G, 16) uint8 blocks + (N, G) uint8 scales -> (N, G * 32) fp16"""
    lut = torch.tensor(_MXFP4_LUT, dtype = torch.float, device = blocks.device)
    b = blocks.int()
    w = torch.stack((lut[b & 0x0F], lut[b >> 4]), dim = -1).view(blocks.shape[0], blocks.shape[1], 32)
    # exp2 multiply rather than torch.ldexp: exact for these integer exponents, and the CUDA
    # ldexp kernel in some torch builds reads out of bounds on broadcast integer exponents
    # (silent on a warm allocator, illegal-memory-access on a freshly initialized device)
    w = w * torch.exp2(scales.float() - 127.0).unsqueeze(-1)
    return w.view(blocks.shape[0], -1).half()


def _mxfp4_to_gguf(blocks: torch.Tensor, scales: torch.Tensor) -> torch.Tensor:
    """OpenAI MXFP4 (N, G, 16) blocks (byte j = elements 2j | 2j+1 << 4) + (N, G) E8M0 scales -> GGUF MXFP4 rows (N, G * 17):
    per 32-block the E8M0 byte then 16 bytes with element j in the low nibble and element j + 16 in the high one (ggml block_mxfp4)."""
    b = blocks.to(torch.uint8)
    e = torch.stack((b & 0x0F, b >> 4), dim = -1).view(b.shape[0], b.shape[1], 32)     # elements in order
    q = e[..., :16] | (e[..., 16:] << 4)
    return torch.cat((scales.to(torch.uint8).unsqueeze(-1), q), dim = -1).reshape(b.shape[0], -1).contiguous()


def _scale_block(n: int, s: int, block: int | None) -> int:
    """Block length along an axis of n elements covered by s scales (config block first, else exact division)."""
    if block and -(-n // block) == s:
        return block
    assert n % s == 0, f"scale grid {s} does not cover {n} elements (block {block})"
    return n // s


def apply_scale_grid(w: torch.Tensor, scale: torch.Tensor, block: tuple | None = None) -> torch.Tensor:
    """float32 w [rows, cols] x scale (scalar, [rows], [rows, 1] or a [sr, sc] grid with ceil-div blocks) -> float32.
    Torch twin of foreign_quant.vendor_input.apply_scales (tests assert bit equality). `block` = (rows, cols)."""
    w = w.float()
    scale = scale.float()
    if scale.numel() == 1:
        return w * scale.reshape(())
    rows, cols = w.shape
    if scale.dim() == 1:
        assert scale.shape[0] in (rows, cols), f"1D scale {tuple(scale.shape)} fits neither {rows} nor {cols}"
        return w * (scale[:, None] if scale.shape[0] == rows else scale[None, :])
    sr, sc = scale.shape
    bo = _scale_block(rows, sr, block[0] if block else None)
    bi = _scale_block(cols, sc, block[1] if block else None)
    if rows % bo == 0 and cols % bi == 0:
        return (w.view(sr, bo, sc, bi) * scale.view(sr, 1, sc, 1)).view(rows, cols)
    full = scale.repeat_interleave(bo, 0).repeat_interleave(bi, 1)[:rows, :cols]
    return w * full




class _ForeignInner:
    """Linear inner over a ForeignLinear payload (NVFP4 served as stored): the ForeignLinear kernels, Linear's interface."""

    def __init__(self, fl, bias):
        self.fl, self.bias = fl, bias
        self.in_features, self.out_features = fl.in_features, fl.out_features
        self.bc = None
        self._pinned_store = None
        self.swap_device = None

    def unload(self):
        pass

    def get_tensors(self, key):
        return self.fl.get_tensors()

    def get_weight_tensor(self):
        return self.fl._dequant_rows(0, self.out_features).T

    def get_bias_tensor(self):
        return self.bias

    def forward(self, x, params, out_dtype = None):
        if self.bias is None:
            return self.fl.forward(x, params, out_dtype)
        self.fl._bias_fused = False
        y = self.fl.forward(x, params, out_dtype, bias = self.bias)    # EXL3_FQ_MMVQ_EPI: the mmvq epilogue may add it (then _bias_fused)
        return y if self.fl._bias_fused else y + self.bias


class Linear(Module):

    def __init__(
        self,
        config: Config | None,
        key: str,
        in_features: int,
        out_features: int,
        qmap: str | None = None,
        alt_key: str | list | None = None,
        qbits_key: str = "bits",
        fkey : str | None = None,
        frange: tuple[int, int] | None = None,
        frange_dim: int = 0,
        fidx: int | None = None,
        finterleaved: bool = False,
        fdequant = None,
        caps: dict = None,
        softcap: float = 0.0,
        pad_to: int = 128,
        trim_padded_out: bool = False,
        full_in_features: int | None = None,
        full_out_features: int | None = None,
        first_in_feature: int | None = None,
        first_out_feature: int | None = None,
        out_dtype: torch.dtype | None = None,
        allow_input_padding: bool = False,
        pre_scale: float = 1.0,
        post_scale: float = 1.0,
        weight_scale: float = 1.0,
        transposed_load: bool = True,
        transpose_fused_weights: bool = True,
        ftranspose_after_load: bool = True,
        select_hq_bits: int = 0,
        qgroup: str = None,
        no_defer_load: bool = False
    ):
        super().__init__(config, key, qmap)
        # Routed-weighted Hessians (EXL3_RWH): expert Linears also accumulate a per-expert H over their routed
        # tokens only, rows scaled by the routing weight; qmap_q is where the quantizer looks the final H up
        self.cap_rkey = None
        self.qmap_q = None

        self.alt_key = alt_key
        self.in_features_unpadded = in_features
        self.in_features = (in_features + pad_to - 1) // pad_to * pad_to
        self.out_features_unpadded = out_features
        self.out_features = (out_features + pad_to - 1) // pad_to * pad_to
        self.trim_padded_out = trim_padded_out
        self.full_in_features = full_in_features if full_in_features is not None else self.in_features
        self.full_out_features = full_out_features if full_out_features is not None else self.out_features
        self.first_in_feature = first_in_feature if first_in_feature is not None else 0
        self.first_out_feature = first_out_feature if first_out_feature is not None else 0
        self.inner = None
        self.qbits_key = qbits_key
        self.fkey = fkey
        self.frange = frange
        self.frange_dim = frange_dim
        self.fidx = fidx
        self.finterleaved = finterleaved
        # Optional architecture-supplied reader for the fused checkpoint tensor named by fkey.
        # Signature: (stc, fkey, device) -> fp16 (out_features, in_features) tensor
        self.fdequant = fdequant
        self.quant_type = None
        self.softcap = softcap
        self.is_sliced = self.in_features < self.full_in_features or self.out_features < self.full_out_features
        self.out_dtype = out_dtype
        self.pre_scale = pre_scale
        self.post_scale = post_scale
        self.weight_scale = weight_scale
        self.transposed_load = transposed_load
        self.transpose_fused_weights = transpose_fused_weights
        self.ftranspose_after_load = ftranspose_after_load
        self.no_defer_load = no_defer_load
        self.select_hq_bits = select_hq_bits
        self.qgroup = qgroup or key
        self.lora_a_tensors = {}
        self.lora_b_tensors = {}

        # in_features_unpadded < in_features is handled at runtime: inputs narrower than the
        # (padded) weight are zero-extended in forward(). allow_input_padding marks layers whose
        # inputs already arrive padded (e.g. MoE down projections fed from padded gate/up)
        self.allow_input_padding = allow_input_padding

        if caps is not None:
            self.caps.update(caps)


    @override
    def optimizer_targets(self):
        return [self.key]


    def pad_out(self, w: torch.Tensor | None) -> torch.Tensor | None:
        """Zero-pad a weight in (in_features, out_features) orientation (or a bias) to the padded
        dims. Padding either or both dims with zeros is inert: pad output columns produce zero
        (trimmed or consumed by a matching pad on the consumer's input dim), pad input rows only
        ever see zero activations."""
        if w is None or self.out_features == self.out_features_unpadded and self.in_features == self.in_features_unpadded:
            return w
        if w.dim() == 2:
            padded = torch.zeros((self.in_features, self.out_features), dtype = w.dtype, device = w.device)
            padded[:w.shape[0], :w.shape[1]] = w
        else:
            assert w.dim() == 1
            padded = torch.zeros((self.out_features,), dtype = w.dtype, device = w.device)
            padded[:w.shape[0]] = w
        return padded.contiguous()


    def quant_block_(self):
        """weight_block_size of the checkpoint's quantization_config as (rows, cols) of the CHECKPOINT orientation,
        swapped when the weight is loaded transposed. None = infer the block from the scale grid."""
        qc = getattr(self.config, "config_dict", {}).get("quantization_config") or {}
        b = qc.get("weight_block_size")
        if not b or len(b) != 2:
            return None
        return (b[1], b[0]) if self.transposed_load else (b[0], b[1])


    # FP8 scales: per-tensor, per-channel or a block grid (ceil-div), always MULTIPLIED, whether the tensor is
    # called weight_scale or weight_scale_inv (DeepSeek / Qwen3-FP8 / GLM / MiniMax name the multiplier "inv")
    def apply_fp8_scales_(self, weight: torch.Tensor, scale: torch.Tensor):
        if scale.dim() == 1 and scale.numel() > 1:
            scale = scale.reshape(1, -1) if self.transposed_load else scale.reshape(-1, 1)    # per output channel, also when square
        return apply_scale_grid(weight, scale, self.quant_block_()).half()


    def apply_fp8_scales_inv_(self, weight: torch.Tensor, scale_inv: torch.Tensor):
        return self.apply_fp8_scales_(weight, scale_inv)


    def load_nvfp4_stored_(self, key: str, dev) -> bool:
        """NVFP4 linear (ModelOpt weight / weight_scale / weight_scale_2, or compressed-tensors weight_packed / weight_scale /
        weight_global_scale divisor) kept as stored: the ForeignLinear nvfp4 kernels (fq_gemv_nvfp4 <= 16 rows) instead of the
        fp16 dequant. quant_type "nvfp4". EXL3_NVFP4_STORED=0 restores the fp16 dequant."""
        if os.environ.get("EXL3_NVFP4_STORED", "1") == "0" or self.is_sliced or self.weight_scale != 1.0 or self.alt_key and key == self.alt_key:
            return False
        stc = self.config.stc
        if not isinstance(key, str) or not stc.has_tensor(key + ".weight_scale"):
            return False
        ws = stc.get_tensor(key + ".weight_scale", dev, optional = True, no_defer = True)
        if ws is None or ws.dtype != torch.float8_e4m3fn or ws.dim() != 2:
            return False
        g = stc.get_tensor(key + ".weight_scale_2", dev, optional = True, no_defer = True)
        inv = g is None
        if inv:
            g = stc.get_tensor(key + ".weight_global_scale", dev, optional = True, no_defer = True)
        if g is None:
            return False
        wname = ".weight_packed" if stc.has_tensor(key + ".weight_packed") else ".weight"
        packed = stc.get_tensor(key + wname, dev, no_defer = True).contiguous().view(torch.uint8)
        N, K = self.out_features, self.in_features
        if tuple(packed.shape) != (N, K // 2) or tuple(ws.shape) != (N, K // 16) or K % 512:
            return False
        from .foreign_linear import ForeignLinear
        fl = ForeignLinear(self.config, self.key, K, N, "nvfp4", out_dtype = self.out_dtype)
        fl.packed, fl.scales = packed, ws.contiguous().view(torch.uint8)
        gv = float(g.float().reshape(-1)[0].item())
        fl.global_scale = 1.0 / gv if inv else gv
        bias = stc.get_tensor(key + ".bias", dev, float2half = True, optional = True, no_defer = True)
        self.used_alt_key = key == self.alt_key
        self.inner = _ForeignInner(fl, bias)
        self.quant_type = "nvfp4"
        return True

    def load_fp8_stored_(self, key: str, dev, has_scale: bool, has_scale_inv: bool) -> bool:
        """FP8 E4M3 linear kept as stored (quant_type "fp8", modules/quant/fp8.py): one byte per weight instead of the fp16 dequant.
        Per-row / per-tensor weight_scale or the weight_scale_inv block grid. EXL3_FP8_STORED=0 restores the fp16 dequant."""
        if os.environ.get("EXL3_FP8_STORED", "1") == "0" or self.is_sliced or self.weight_scale != 1.0 or not (has_scale or has_scale_inv):
            return False
        stc = self.config.stc
        w = stc.get_tensor(key + ".weight", dev, no_defer = True)
        if w.dtype != torch.float8_e4m3fn or tuple(w.shape) != (self.out_features, self.in_features):
            return False
        s = stc.get_tensor(key + (".weight_scale" if has_scale else ".weight_scale_inv"), dev, no_defer = True)
        s = (s.float() - 127.0).exp2() if s.dtype == torch.uint8 else s.float()
        N, K = w.shape
        from .quant.fp8 import LinearFP8, ok as fp8_ok
        if s.numel() == 1:
            s, grid, block = s.reshape(1).expand(N).contiguous(), False, (1, 1)
        elif s.dim() == 1 or (s.dim() == 2 and s.shape == (N, 1)):
            s, grid, block = s.reshape(N).contiguous(), False, (1, 1)
        elif s.dim() == 2:
            qb = self.quant_block_()
            block = (_scale_block(N, s.shape[0], qb[0] if qb else None), _scale_block(K, s.shape[1], qb[1] if qb else None))
            grid = True
            if not fp8_ok(N, K, grid, block):
                return False
        else:
            return False
        bias = stc.get_tensor(key + ".bias", dev, float2half = True, optional = True, no_defer = True)
        self.used_alt_key = key == self.alt_key
        self.inner = LinearFP8(K, N, w.view(torch.uint8), s, grid, block, bias, self.out_dtype, key = self.key)
        self.quant_type = "fp8"
        return True


    # NVFP4: packed e2m1 (U8 [out, in/2], low nibble first) x E4M3 scale per 16 inputs x one fp32 global scale.
    # ModelOpt: weight / weight_scale / weight_scale_2 (multiplier); compressed-tensors: weight_packed /
    # weight_scale / weight_global_scale (divisor). Returns (out, in) fp16 in checkpoint orientation, or None.
    def dequant_nvfp4_(self, key: str, dev) -> torch.Tensor | None:
        stc = self.config.stc
        wname = ".weight_packed" if stc.has_tensor(key + ".weight_packed") else ".weight"
        ws = stc.get_tensor(key + ".weight_scale", dev, optional = True, no_defer = True)
        if ws is None or ws.dtype != torch.float8_e4m3fn or ws.dim() != 2:
            return None
        inv = False
        g = stc.get_tensor(key + ".weight_scale_2", dev, optional = True, no_defer = True)
        if g is None:
            g = stc.get_tensor(key + ".weight_global_scale", dev, optional = True, no_defer = True)
            inv = g is not None
        assert g is not None, f"{key}: NVFP4 weight without weight_scale_2 / weight_global_scale"
        u8 = stc.get_tensor(key + wname, dev, no_defer = True).contiguous().view(torch.uint8)
        lut = torch.tensor(_MXFP4_LUT, dtype = torch.float, device = u8.device)
        w = torch.stack((lut[(u8 & 0x0F).long()], lut[(u8 >> 4).long()]), dim = -1).view(u8.shape[0], -1)
        w = apply_scale_grid(w, ws.float(), None)
        g = g.float().reshape(-1)[0]
        return ((w / g) if inv else (w * g)).half()


    # DeepSeek-V4-style quantized checkpoint tensors, dequantized to FP16 at load (they get
    # requantized to EXL3 anyway; no runtime paths for exotic dtypes). One generic routine:
    # the block shape is derived from the scale grid, covering FP8 E4M3 with a [128, 128]
    # grid and packed FP4 (two e2m1 nibbles per int8 byte, low nibble first) with a [1, 32]
    # grid. E8M0 scales arrive as uint8 exponent bytes, value 2^(byte - 127). Mirrors the
    # transformers finegrained_fp8 reference dequant.
    def dequant_e8m0_blocks_(self, weight: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
        # MiMo-V2 stores the same packed-FP4 expert weights as U8 rather than I8; the bytes are
        # identical (SGLang's loader only bitcasts to match its int8 parameter, then masks as
        # unsigned again), so both dtypes take the unpack path
        if weight.dtype in (torch.int8, torch.uint8):
            u8 = weight.contiguous().view(torch.uint8)
            lut = torch.tensor(_MXFP4_LUT, dtype = torch.float, device = weight.device)
            w = torch.stack((lut[(u8 & 0x0F).long()], lut[(u8 >> 4).long()]), dim = -1)
            w = w.view(weight.shape[0], -1)
        else:
            w = weight.float()
        rows, cols = w.shape
        sr, sc = scale.shape
        assert rows % sr == 0 and cols % sc == 0, \
            f"{self.key}: weight {rows}x{cols} not divisible by scale grid {sr}x{sc}"
        s = (scale.float() - 127.0).exp2() if scale.dtype == torch.uint8 else scale.float()
        w = (w.view(sr, rows // sr, sc, cols // sc) * s.view(sr, 1, sc, 1)).view(rows, cols)
        return w.half()


    def load_fp16(self, key: str | list[str]) -> bool:

        if self.config.stc.has_tensor_group(key, ["weight"]) or \
                (isinstance(key, str) and self.config.stc.has_tensor(key + ".weight_packed")):

            self.used_alt_key = key == self.alt_key
            if self.used_alt_key and isinstance(key, list):
                dev = self.device
                weight = [self.config.stc.get_tensor(k + ".weight", dev, float2half = True, transpose = self.transposed_load, no_defer = True) for k in key]
                bias = [self.config.stc.get_tensor(k + ".bias", dev, float2half = True, optional = True, no_defer = True) for k in key]
                weight = torch.cat(weight, dim = -1)
                bias = torch.cat(bias, dim = -1) if bias[0] is not None else None
            else:
                dev = "cpu" if self.is_sliced else self.device
                pad1 = (self.out_features,) if not self.is_sliced else None
                pad2 = (self.in_features, self.out_features) if not self.is_sliced else None
                if self.load_nvfp4_stored_(key, dev):
                    return True
                scale_q = self.config.stc.get_tensor(key + ".scale", dev, optional = True, no_defer = True)
                nv = self.dequant_nvfp4_(key, dev) if scale_q is None and self.config.stc.has_tensor(key + ".weight_scale") else None
                if nv is None and scale_q is None and self.config.stc.has_tensor(key + ".weight_scale"):
                    # MiMo-V2 routed experts: same E8M0 block grid, named "weight_scale" and
                    # stored as U8 exponent bytes. Only 2D uint8 scales route here; float
                    # "weight_scale" tensors keep the per-row/per-tensor fp8 path below. Fetched
                    # untransposed because the dequant runs in checkpoint (out, in) orientation
                    ws_q = self.config.stc.get_tensor(key + ".weight_scale", dev, optional = True, no_defer = True)
                    if ws_q is not None and ws_q.dim() == 2 and ws_q.dtype == torch.uint8:
                        scale_q = ws_q
                if nv is not None:
                    # NVFP4 (ModelOpt / compressed-tensors): dequantized in checkpoint orientation above
                    weight = nv.T if self.transposed_load else nv
                    weight = weight.contiguous() if self.is_sliced else self.pad_out(weight.contiguous())
                    bias = self.config.stc.get_tensor(key + ".bias", dev, float2half = True, optional = True, pad_to = pad1, no_defer = True)
                    scale = scale_inv = None
                elif scale_q is not None and scale_q.dim() == 2:
                    # DeepSeek-V4 style: fp8/fp4 blocks + E8M0 scale grid, checkpoint
                    # orientation (out, in); dequant first, then orient/pad like a plain load
                    wname = ".weight_packed" if self.config.stc.has_tensor(key + ".weight_packed") else ".weight"    # compressed-tensors / AutoRound MXFP4
                    w_raw = self.config.stc.get_tensor(key + wname, dev, no_defer = True)
                    weight = self.dequant_e8m0_blocks_(w_raw, scale_q)
                    if self.transposed_load:
                        weight = weight.T
                    weight = weight.contiguous() if self.is_sliced else self.pad_out(weight.contiguous())
                    bias = None
                    scale = scale_inv = None
                else:
                    scale = self.config.stc.get_tensor(key + ".weight_scale", dev, transpose = self.transposed_load, optional = True, no_defer = True)
                    scale_inv = self.config.stc.get_tensor(key + ".weight_scale_inv", dev, transpose = self.transposed_load, optional = True, no_defer = True)
                    assert scale is None or scale_inv is None
                    # MXFP8 (MiniMax-M3): FP8 weights with a U8 weight_scale_inv of E8M0 exponent bytes, one per 32 inputs
                    if scale_inv is not None and scale_inv.dtype == torch.uint8:
                        scale_inv = (scale_inv.float() - 127.0).exp2()
                    if scale is not None and scale.dtype == torch.uint8:
                        scale = (scale.float() - 127.0).exp2()
                    if self.load_fp8_stored_(key, dev, scale is not None, scale_inv is not None):
                        return True
                    no_defer = self.no_defer_load or scale is not None or scale_inv is not None or self.weight_scale != 1.0
                    weight = self.config.stc.get_tensor(key + ".weight", dev, float2half = True, transpose = self.transposed_load, pad_to = pad2, no_defer = no_defer)
                    bias = self.config.stc.get_tensor(key + ".bias", dev, float2half = True, optional = True, pad_to = pad1, no_defer = no_defer)
                if scale is not None:
                    weight = self.apply_fp8_scales_(weight, scale)
                elif scale_inv is not None:
                    weight = self.apply_fp8_scales_inv_(weight, scale_inv)
                if self.weight_scale != 1.0:
                    weight = (weight.float() * self.weight_scale).to(weight.dtype)
                    if bias is not None:
                        bias = (bias.float() * self.weight_scale).to(bias.dtype)

            self.inner = LinearFP16(
                self.in_features,
                self.out_features,
                weight,
                bias,
                self.full_in_features,
                self.full_out_features,
                self.first_in_feature,
                self.first_out_feature,
                self.out_dtype,
                key = self.key
            )
            if self.is_sliced:
                self.inner.swap_device = self.device
                self.inner.unswap_cpu()
            self.quant_type = "fp16"
            return True

        # Special dumb loading mode for Qwen3VLMoE
        elif self.fkey and self.config.stc.has_tensor(self.fkey) and self.fidx is not None:

            # Load and split fused weight along first dim
            weight = self.config.stc.get_tensor(
                self.fkey,
                self.device,
                transpose = self.transpose_fused_weights,
                no_defer = True,
                fidx = self.fidx
            )
            if weight.dtype in (torch.float8_e4m3fn, torch.float8_e5m2):
                # fp8 batch tensor (Mistral-Small-4): per-expert scalar scale stored as
                # {fkey}_scale_inv with the expert on the first dim
                scale_inv = self.config.stc.get_tensor(
                    self.fkey + "_scale_inv", self.device, optional = True, no_defer = True, fidx = self.fidx
                )
                weight = weight.float()
                if scale_inv is not None:
                    weight = weight * scale_inv.float().reshape(-1)[0]
                weight = weight.half()
            if self.frange is not None:
                if self.frange_dim == 0:
                    weight = weight[self.frange[0] : self.frange[1]].contiguous()
                elif self.frange_dim == 1:
                    weight = weight[:, self.frange[0] : self.frange[1]].contiguous()
                else:
                    raise ValueError(f"Unsupported frange_dim={self.frange_dim} for {self.key}")
            if self.ftranspose_after_load:
                weight = weight.T.contiguous()
            # pad_out expects (in_features, out_features) orientation
            weight = self.pad_out(weight)
            if self.weight_scale != 1.0:
                weight = (weight.float() * self.weight_scale).to(weight.dtype)
            self.inner = LinearFP16(
                self.in_features,
                self.out_features,
                weight,
                None,
                self.full_in_features,
                self.full_out_features,
                self.first_in_feature,
                self.first_out_feature,
                out_dtype = self.out_dtype,
                key = self.key
            )
            self.quant_type = "fp16"
            return True

        # MXFP4 batch tensor (gpt-oss): experts packed as {fkey}_blocks/_scales/_bias, one 3D/4D
        # tensor per projection with the expert on the first dim. Dequantized to fp16 per expert
        # slice here; the interleaved flag handles fused tensors that alternate gate/up rows
        elif self.fkey and self.fidx is not None and self.config.stc.has_tensor(self.fkey + "_blocks"):

            assert self.ftranspose_after_load, \
                f"MXFP4 batch tensor for {self.key} requires ftranspose_after_load"
            blocks = self.config.stc.get_tensor(
                self.fkey + "_blocks", self.device, no_defer = True, fidx = self.fidx
            )
            scales = self.config.stc.get_tensor(
                self.fkey + "_scales", self.device, no_defer = True, fidx = self.fidx
            )
            bias = self.config.stc.get_tensor(
                self.fkey + "_bias", self.device, optional = True, no_defer = True, fidx = self.fidx
            )
            # Slice out rows (output features) before dequantizing
            if self.frange is not None:
                n = self.frange[1] - self.frange[0]
                if self.finterleaved:
                    step = blocks.shape[0] // n
                    off = self.frange[0] // n
                    sl = slice(off, None, step)
                else:
                    sl = slice(self.frange[0], self.frange[1])
                blocks = blocks[sl].contiguous()
                scales = scales[sl].contiguous()
                if bias is not None:
                    bias = bias[sl].contiguous()
            if os.environ.get("EXL3_MXFP4_STORED", "1") != "0" and self.weight_scale == 1.0 and not self.is_sliced \
                    and blocks.shape[0] <= self.out_features and blocks.shape[1] * 32 <= self.in_features and self.in_features % 32 == 0:
                # kept as stored: the ForeignLinear mxfp4 kernels (GGUF block layout, same E8M0 bytes) instead of the fp16 dequant.
                # The engine pads both dims to 128 (gpt-oss 2880 -> 2944): zero blocks / zero rows (weight 0, bias 0) fill the pad.
                from .foreign_linear import ForeignLinear
                pk = _mxfp4_to_gguf(blocks, scales)
                Kb, Kp = blocks.shape[1], self.in_features // 32
                if Kp > Kb:
                    pk = torch.cat((pk, torch.zeros((pk.shape[0], (Kp - Kb) * 17), dtype = torch.uint8, device = pk.device)), dim = 1)
                if self.out_features > pk.shape[0]:
                    pk = torch.cat((pk, torch.zeros((self.out_features - pk.shape[0], pk.shape[1]), dtype = torch.uint8, device = pk.device)), dim = 0)
                fl = ForeignLinear(self.config, self.key, self.in_features, self.out_features, "mxfp4", out_dtype = self.out_dtype)
                fl.packed = pk.contiguous()
                self.inner = _ForeignInner(fl, self.pad_out(bias).half() if bias is not None else None)
                self.quant_type = "mxfp4"
                return True
            weight = _mxfp4_dequant(blocks, scales)
            weight = weight.T.contiguous()
            weight = self.pad_out(weight)
            bias = self.pad_out(bias)
            if self.weight_scale != 1.0:
                weight = (weight.float() * self.weight_scale).to(weight.dtype)
                if bias is not None:
                    bias = (bias.float() * self.weight_scale).to(bias.dtype)
            self.inner = LinearFP16(
                self.in_features,
                self.out_features,
                weight,
                bias,
                self.full_in_features,
                self.full_out_features,
                self.first_in_feature,
                self.first_out_feature,
                out_dtype = self.out_dtype,
                key = self.key
            )
            self.quant_type = "fp16"
            return True

        elif self.fkey and self.config.stc.has_tensor_group(self.fkey, ["weight"]) and self.frange is not None:

            if self.fdequant is not None:
                # Architecture-supplied reader for a fused tensor whose checkpoint layout the
                # generic paths cannot describe (MiMo-V2: TP-shard-interleaved fused QKV with a
                # per-shard, ceiling-padded FP8 scale grid). Returns the canonical, contiguous
                # (out_features, in_features) fp16 matrix that frange indexes into
                weight = self.fdequant(self.config.stc, self.fkey, self.device)
                bias = None
            else:
                weight = self.config.stc.get_tensor(
                    self.fkey + ".weight",
                    self.device,
                    no_defer = True
                )
                # Fused checkpoint tensor in FP8/FP4-block form (DeepSeek-V4 wo_a): dequantize the
                # whole tensor before slicing out this group's rows
                scale_q = self.config.stc.get_tensor(self.fkey + ".scale", self.device, optional = True, no_defer = True)
                if scale_q is not None and scale_q.dim() == 2:
                    weight = self.dequant_e8m0_blocks_(weight, scale_q)
            weight = weight[self.frange[0] : self.frange[1]].contiguous()
            weight = self.pad_out(weight)
            if self.fdequant is None:
                bias = self.config.stc.get_tensor(
                    self.fkey + ".bias",
                    self.device,
                    optional = True,
                    no_defer = True
                )
            if bias is not None:
                bias = bias[self.frange[0] : self.frange[1]].contiguous()
                bias = self.pad_out(bias)
            if self.ftranspose_after_load:
                weight = weight.T.contiguous()
            self.inner = LinearFP16(
                self.in_features,
                self.out_features,
                weight,
                bias,
                self.full_in_features,
                self.full_out_features,
                self.first_in_feature,
                self.first_out_feature,
                out_dtype = self.out_dtype,
                key = self.key
            )
            self.quant_type = "fp16"
            return True

        return False


    def is_exl3_storage(self, key: str):
        return self.config.stc.has_tensor_group(
            key,
            [["sv", "svh"], ["su", "suh"], "trellis"]
        )

    def load_exl3(self, key: str) -> bool:
        if not self.is_exl3_storage(key):
            return False
        self.used_alt_key = key == self.alt_key
        # Probe the header before fetching: most formats ship only a subset of these tensors,
        # and the misses otherwise add up to a significant share of bulk-load Python overhead
        stc = self.config.stc
        def opt(subkey, device, **kwargs):
            k = key + subkey
            return stc.get_tensor(k, device, optional = True, **kwargs) if stc.has_tensor(k) else None
        scale = None  # opt(".scale", self.device)
        su = opt(".su", self.device, no_defer = True)
        suh = opt(".suh", self.device)
        sv = opt(".sv", self.device, no_defer = True)
        svh = opt(".svh", self.device)
        trellis = stc.get_tensor(key + ".trellis", self.device)
        mcg = opt(".mcg", "cpu")
        mul1 = opt(".mul1", "cpu")
        bias = opt(".bias", self.device)
        cls = LinearEXL3
        if torch.device(self.device).type == "cpu":      # no CUDA kernels: dense reconstruction (quant/exl3_cpu.py)
            from .quant.exl3_cpu import CpuLinearEXL3
            cls = CpuLinearEXL3
        self.inner = cls(
            self.config,
            self.in_features,
            self.out_features,
            scale,
            su,
            sv,
            suh,
            svh,
            trellis,
            mcg,
            mul1,
            bias,
            self.out_dtype,
            key = self.key
        )
        self.quant_type = "exl3"
        return True


    @override
    def can_defer_load(self):
        if self.is_sliced: return False
        return super().can_defer_load()


    @override
    def load(self, device: torch.device, **kwargs):
        self.device = device
        keys = [self.key]
        if self.alt_key:
            keys += [self.alt_key]
        if any(self.load_gguf_(k, device) for k in keys): return
        if any(self.load_exl3(k) for k in keys): return
        if any(self.load_fp16(k) for k in keys): return
        raise ValueError(f"No tensors found for {self.key} matching supported quantization format.")

    def load_gguf_(self, key, dev) -> bool:
        """GGUF backing store (config.gguf + config.gguf_formats): a weight stored in a ggml quant format loads as a ForeignLinear
        (kernels on the stored blocks, no dequant); fp / bf16 tensors go on to load_fp16 as before."""
        g, fm = getattr(self.config, "gguf", None), getattr(self.config, "gguf_formats", None)
        if g is None or not fm or not isinstance(key, str) or self.is_sliced or self.weight_scale != 1.0:
            return False
        if os.environ.get("EXL3_GGUF_GENERIC", "0") == "1" and g.new_tensors and (key + ".weight") in g.new_tensors:
            return False  # in-memory fp override (e.g. dequantized GDN b/a projs) wins over the stored quant blocks
        gname = g.name_map.get(key + ".weight")
        gname = gname[0] if isinstance(gname, tuple) else gname
        from ..loader.gguf_collection import gguf_fmt as _gguf_fmt
        fmt = _gguf_fmt(fm, gname)
        if fmt is None or fmt == "fp" or fmt.startswith("unk"):
            return False
        from .foreign_linear import ForeignLinear
        fl = ForeignLinear(self.config, key, self.in_features, self.out_features, fmt, out_dtype = self.out_dtype)
        fl.load(dev)
        bias = self.config.stc.get_tensor(key + ".bias", dev, float2half = True, optional = True, no_defer = True)
        self.used_alt_key = key == self.alt_key
        self.inner = _ForeignInner(fl, bias)
        self.quant_type = fmt
        return True


    @override
    def pin_linears(self):
        """Move this layer's bulk weight storage (fp16 weight or EXL3 trellis) to pinned host
        memory and swap in a zero-copy CUDA alias, freeing the VRAM. Compute paths read the
        weights over PCIe: fine for occasional, compute-bound vision-tower batches. Small
        tensors (bias, suh/svh) stay in VRAM. Runs post-load, so it covers every load flavor
        (fused/sliced/fp8-dequant) and deferred fills have already landed."""
        inner = self.inner
        if inner is None or self.device is None:
            return
        device = torch.device(self.device)
        if device.type != "cuda":
            return

        def pin_alias(t):
            if not t.is_contiguous():
                t = t.contiguous()
            p = torch.empty(t.shape, dtype = t.dtype, device = "cpu", pin_memory = True)
            p.copy_(t)
            return p, ext.pinned_cuda_view(p, device.index if device.index is not None else 0)

        if isinstance(inner, LinearFP16) and inner.swap_device is None:
            inner._pinned_store, inner.weight = pin_alias(inner.weight)
            inner.bc = ext.BC_LinearFP16(inner.weight, inner.bias)
        elif isinstance(inner, LinearEXL3):
            from ..util.tensor import g_tensor_cache
            inner._pinned_store, inner.trellis = pin_alias(inner.trellis)
            inner.bc = ext.BC_LinearEXL3(
                inner.trellis, inner.suh, inner.svh, inner.K, inner.bias,
                inner.mcg, inner.mul1, g_tensor_cache.get(*inner.bsz1_xh_args))

    @override
    def unload(self):
        if self.inner is not None:
            self.inner.unload()
        self.device = None
        self.inner = None
        self.lora_a_tensors.clear()
        self.lora_b_tensors.clear()


    @override
    def get_tensors(self):
        if self.device:
            return self.inner.get_tensors(self.key)
        else:
            return {}


    def convert_exl3(
        self,
        H_data: dict,
        quant_args: dict,
        progress_str: str | None = None,
        return_weight_q: bool = False,
        verbose: bool = False,
        save_reg: str = None,
        override_swap_device: torch.device | None = None
    ):
        assert isinstance(self.inner, LinearFP16), \
            "Inner layer is already quant type"

        # Destroy original layer here to save VRAM, we only need weights
        swap_to_device = self.inner.swap_device  # in case weights are swapped to CPU
        if swap_to_device is not None and override_swap_device is not None:
            swap_to_device = override_swap_device

        orig_weight = self.inner.get_weight_tensor().float()
        orig_bias = self.inner.get_bias_tensor()
        self.inner = None

        weight_q, proxy_err, out_tensors = quantize_exl3(
            orig_weight,
            H_data,
            quant_args,
            return_weight_q,
            progress_str,
            verbose,
            swap_to_device,
            save_reg = save_reg
        )

        self.inner = LinearEXL3(
            self.config,
            self.in_features,
            self.out_features,
            out_tensors.get("scale"),
            out_tensors.get("su"),
            out_tensors.get("sv"),
            out_tensors.get("suh"),
            out_tensors.get("svh"),
            out_tensors.get("trellis"),
            out_tensors.get("mcg"),
            out_tensors.get("mul1"),
            orig_bias,
            self.out_dtype,
            key = self.key
        )

        if return_weight_q:
            return proxy_err, weight_q
        else:
            return proxy_err


    def init_H_data(self, init_tensor: bool):
        return {
            "H": torch.zeros(self.in_features, self.in_features, dtype = torch.float32, device = self.device if init_tensor else "meta"),
            "first_key": self.key,
            "count": 0,
            "finalized": False,
            "num_total": 0,
            "inf_nan": torch.zeros(2, dtype = torch.long, device = self.device),
            "device": self.device,
        }


    def capture_H(self, x: torch.Tensor, params: dict):
        _cap_t0 = _time.perf_counter() if _CAP_PROFILE else None
        if self.qmap not in params["capture"]:
            params["capture"][self.qmap] = self.init_H_data(True)

        params["capture"][self.qmap]["num_total"] += x.numel()
        ext.count_inf_nan(x, params["capture"][self.qmap]["inf_nan"])

        if params["capture"][self.qmap]["first_key"] == self.key:
            if _CAP_LEGACY:
                rows = np.prod(x.shape[:-1])
                dim = x.shape[-1]
                x = x.view((rows, dim)).to(torch.float, copy = True)  # TODO: Why copy here?

                # fp16 activation overflow (+-inf) would poison entire rows/columns of H through the
                # accumulation, and no diagonal damping can repair non-finite entries afterwards.
                # Drop the affected rows; the inf_nan counter above still reports them
                finite = torch.isfinite(x).all(dim = 1)
                if not finite.all():
                    x = x[finite]
                    rows = x.shape[0]

                params["capture"][self.qmap]["H"].addmm_(x.T, x)
                params["capture"][self.qmap]["count"] += rows
            else:
                # Defer: queue the (viewed, uncast) activation and let flush_capture_H()
                # filter non-finite rows device-side (zero-fill, no host sync) and
                # accumulate this forward's entries through batched GEMMs. The finite-row
                # count becomes a device scalar resolved once at finalize time.
                rows = int(np.prod(x.shape[:-1]))
                dim = x.shape[-1]
                x = x.view((rows, dim))
                pend = params.get("_cap_pending")
                if pend is None:
                    pend = []
                    params["_cap_pending"] = pend
                pend.append((params["capture"][self.qmap], x))

        rw = params.get("_cap_rw")
        if rw is not None and self.cap_rkey is not None:
            idx, wv = rw
            hd = params["capture"].get(self.cap_rkey)
            if hd is None:
                hd = self.init_H_data(True)
                hd["sw2"] = torch.zeros((), dtype = torch.float32, device = self.device)
                hd["sw4"] = torch.zeros((), dtype = torch.float32, device = self.device)
                params["capture"][self.cap_rkey] = hd
            if hd["first_key"] == self.key:
                xr = x.view(-1, x.shape[-1])[idx] * wv.to(x.dtype).unsqueeze(1)
                hd["sw2"] += (wv.float() ** 2).sum()
                hd["sw4"] += (wv.float() ** 4).sum()
                hd["count"] += int(idx.numel())
                pend = params.get("_cap_pending")
                if pend is None:
                    pend = []
                    params["_cap_pending"] = pend
                pend.append((hd, xr))

        if _cap_t0 is not None:
            CAP_STAT["wall"] += _time.perf_counter() - _cap_t0
            CAP_STAT["calls"] += 1


    @override
    def weights_numel(self):
        return self.in_features * self.out_features


    @override
    def forward(
        self,
        x: torch.Tensor,
        params: dict,
        out_dtype: torch.dtype | None = None,
    ) -> torch.Tensor:

        if self.out_features == 0:
            dtype = out_dtype or self.out_dtype or torch.half
            return x.new_empty((*x.shape[:-1], 0), dtype = dtype)

        # When in_features is padded past the incoming activation width (dims not a multiple of
        # pad_to, e.g. gpt-oss hidden_size 2880), zero-extend the input. The padded weight rows
        # are zeros, so this is exact; H capture below sees the padded width, keeping the
        # quantizer's Hadamard blocks aligned
        if x.shape[-1] < self.in_features:
            x = torch.nn.functional.pad(x, (0, self.in_features - x.shape[-1]))

        if self.qmap and "capture" in params:
            self.capture_H(x, params)

        if self.lora_a_tensors:
            lora_input = x
        else:
            lora_input = None

        x = self.inner.forward(x, params, out_dtype)

        # Padded output columns carry only zeros (fp16) or quantization noise (EXL3); trim when
        # the consumer expects the exact width (e.g. projections back into the residual stream).
        # Contiguous copy: downstream kernels index flat memory
        if self.trim_padded_out and self.out_features != self.out_features_unpadded:
            x = x[..., :self.out_features_unpadded].contiguous()

        if lora_input is not None:
            self.apply_lora(lora_input, x)

        if self.pre_scale != 1.0:
            x *= self.pre_scale
        if self.softcap != 0.0:
            ext.softcap(x, x, self.softcap)
        if self.post_scale != 1.0:
            x *= self.post_scale
        return x


    def apply_lora(self, lora_input: torch.Tensor, x: torch.Tensor):
        orig_shape = lora_input.shape
        flat = lora_input.view(-1, orig_shape[-1])
        for lora, a in self.lora_a_tensors.items():
            b = self.lora_b_tensors.get(lora)
            if b is not None:
                lora_in = flat if flat.dtype == a.dtype else flat.to(a.dtype)
                delta = lora_in @ a @ b
                x += delta.view(*orig_shape[:-1], -1).to(x.dtype)


    def quant_format_id(self):
        # alt_key is only used when loading unquantized model
        if self.is_exl3_storage(self.key):
            return "exl3"
        else:
            return None


    @cached_property
    def _storage_size(self):
        # alt_key is only used when loading unquantized model
        if self.is_exl3_storage(self.key):
            return sum(self.config.stc.get_tensor_sizes(prefix = self.key))
        else:
            return 2 * self.in_features * self.out_features
    def storage_size(self):
        return self._storage_size


    def recons_size(self):
        return 2 * self.in_features * self.out_features


    def make_tp_allocation(self, options: dict) -> list[TPAllocation]:
        storage = 0
        storage += self.storage_size()
        overhead_d = self.out_features * (self.out_dtype or torch.half).itemsize
        overhead_s = self.out_features * (self.out_dtype or torch.half).itemsize
        recons = self.recons_size()
        tpa = TPAllocation(
            key = self.key,
            channel_width = 128,
            channel_unit = "channels",
            storage_per_device = 0,
            storage_to_split = storage,
            overhead_per_device = overhead_d,
            overhead_to_split = overhead_s,
            recons_temp = recons,
            channels_to_split = self.out_features // 128,
            limit_key = "linear"
        )
        return [tpa]


    def tp_export(self, plan, producer):
        assert self.device is not None and self.inner is not None, "Cannot export module for TP before loading."
        return {
            "cls": Linear,
            "kwargs": {
                "key": self.key,
                "in_features": self.in_features,
                "out_features": self.out_features,
                "out_dtype": self.out_dtype,
                "alt_key": self.alt_key,
                "fkey": self.fkey,
                "frange": self.frange,
                "frange_dim": self.frange_dim,
                "fidx": self.fidx,
                "finterleaved": self.finterleaved,
                "trim_padded_out": self.trim_padded_out,
                "ftranspose_after_load": self.ftranspose_after_load,
                "caps": self.caps,
                "softcap": self.softcap,
                "full_in_features": self.full_in_features,
                "full_out_features": self.full_out_features,
                "first_in_feature": self.first_in_feature,
                "first_out_feature": self.first_out_feature,
                "pre_scale": self.pre_scale,
                "post_scale": self.post_scale,
            },
            # Not constructor args: restored post-construction by _adopt_inner_dims for dims the
            # split leaves whole (padded models pad the hidden dims, which are never split)
            "unpadded": (self.in_features_unpadded, self.out_features_unpadded),
            "inner": self.inner.tp_export(plan, producer),
            "device": self.device
        }


    @staticmethod
    def tp_import_split(local_context, exported, plan, split):
        device = local_context["device"]
        module = Linear(
            config = None,
            **exported["kwargs"],
        )
        module.device = device
        module.inner = exported["inner"]["cls"].tp_import_split(local_context, exported["inner"], plan, split)
        module.quant_type = module.inner.quant_type
        if split is not None:
            split_out, first, _ = split
            module._adopt_inner_dims(exported, out_first = first if split_out else None,
                                     in_first = first if not split_out else None)
        else:
            module._adopt_inner_dims(exported)
        return module

    @staticmethod
    def tp_import_split_3(local_context, exported, plan, split_0, split_1, split_2):
        device = local_context["device"]
        module = Linear(
            config = None,
            **exported["kwargs"],
        )
        module.device = device
        module.inner = exported["inner"]["cls"].tp_import_split_3(local_context, exported["inner"], plan, split_0, split_1, split_2)
        module.quant_type = module.inner.quant_type
        module._adopt_inner_dims(exported)
        return module

    @staticmethod
    def tp_import_split_n(local_context, exported, plan, splits):
        # N-range output split (Mamba2 in_proj: [z | x | B | C | dt] sections split by state
        # group, with the dt section replicated). The ranges select only real (unpadded) columns,
        # so the local slice is exact by construction: no output trim, no padded-out bookkeeping
        device = local_context["device"]
        module = Linear(
            config = None,
            **exported["kwargs"],
        )
        module.device = device
        module.inner = exported["inner"]["cls"].tp_import_split_n(local_context, exported["inner"], plan, splits)
        module.quant_type = module.inner.quant_type
        module.in_features = module.inner.in_features
        module.out_features = module.inner.out_features
        exp_in = exported["kwargs"]["in_features"]
        unp_in, _ = exported.get("unpadded", (exp_in, None))
        module.in_features_unpadded = unp_in if module.in_features == exp_in else module.in_features
        module.out_features_unpadded = module.out_features
        module.trim_padded_out = False
        module.is_sliced = True
        return module

    def _adopt_inner_dims(self, exported: dict, in_first: int | None = None, out_first: int | None = None):
        # The exported kwargs carry the full unsplit (padded) dims; forward() sizes its input padding and
        # output trim against the wrapper dims, so they must track the local slice. A dim the split left
        # whole keeps its true unpadded value (padded models pad the hidden dims, which are never split).
        # Splitting a padded dim is fine when the slice offset is known: slices below the pad boundary
        # are exact, and the slice containing it has (unpadded - first) real columns (e.g. an lm_head
        # with a padded vocab split across ranks -- the pad columns ride in the tail slice like they do
        # on a single device)
        exp_in, exp_out = exported["kwargs"]["in_features"], exported["kwargs"]["out_features"]
        unp_in, unp_out = exported.get("unpadded", (exp_in, exp_out))
        self.in_features = self.inner.in_features
        self.out_features = self.inner.out_features
        if self.in_features == exp_in:
            self.in_features_unpadded = unp_in
        elif exp_in == unp_in:
            self.in_features_unpadded = self.in_features
        else:
            assert in_first is not None, f"{self.key}: cannot split the padded input dim without the slice offset"
            self.in_features_unpadded = max(0, min(unp_in - in_first, self.in_features))
        if self.out_features == exp_out:
            self.out_features_unpadded = unp_out
        elif exp_out == unp_out:
            self.out_features_unpadded = self.out_features
        else:
            assert out_first is not None, f"{self.key}: cannot split the padded output dim without the slice offset"
            self.out_features_unpadded = max(0, min(unp_out - out_first, self.out_features))
            # A load-bearing output trim (projections back into the residual stream) has no
            # defined per-slice gather semantics; no current model splits such a dim
            assert not self.trim_padded_out or self.out_features_unpadded == self.out_features, \
                f"{self.key}: cannot split a padded output dim that requires trimming"
        self.is_sliced = self.in_features < self.full_in_features or self.out_features < self.full_out_features


    @staticmethod
    def tp_import(local_context, exported, plan):
        key = exported["kwargs"]["key"]
        first, last, unit = plan[key] if key in plan else (None, None, "channels")
        assert unit == "channels"
        split = (True, first, last) if first is not None else None
        return Linear.tp_import_split(local_context, exported, plan, split)


def flush_capture_H(params: dict):
    """Consume the activations queued by capture_H() for one forward pass.

    Grouped by (rows, dim, dtype): every entry goes through one fp32 bmm per chunk, then a
    single add_ into its own H. Non-finite rows are zero-filled on the device instead of
    being dropped behind a host sync (their contribution to H is exactly zero, and the
    finite-row count is accumulated into each entry's count_dev scalar), so H matches the
    legacy per-call addmm_ path to fp32 rounding (batched vs. sequential accumulation
    order) while the forward loop runs sync-free.
    """
    _t0 = _time.perf_counter() if _CAP_PROFILE else None
    pending = params.pop("_cap_pending", None)
    if not pending:
        return
    shape_groups: dict = {}
    order = []
    for hd, x in pending:
        key = (x.shape, x.dtype, x.device)
        if key not in shape_groups:
            shape_groups[key] = []
            order.append(key)
        shape_groups[key].append((hd, x))
    for key in order:
        entries = shape_groups[key]
        # Chunk to bound the transient fp32 stack (b x rows x dim) + bmm output
        for s in range(0, len(entries), 64):
            chunk = entries[s:s + 64]
            xs = torch.stack([e[1] for e in chunk])
            xf = xs.to(torch.float)
            finite = torch.isfinite(xf).all(dim = 2)
            xf = xf.masked_fill_(~finite.unsqueeze(2), 0.0)
            P = torch.bmm(xf.transpose(1, 2), xf)
            fs = finite.sum(dim = 1)
            for j, (hd, _x) in enumerate(chunk):
                hd["H"].add_(P[j])
                cd = hd.get("count_dev")
                if cd is None:
                    cd = torch.zeros((), dtype = torch.long, device = hd["H"].device)
                    hd["count_dev"] = cd
                cd.add_(fs[j])
            xs = xf = P = fs = None
    if _t0 is not None:
        FLUSH_STAT["wall"] += _time.perf_counter() - _t0
        FLUSH_STAT["calls"] += 1


def convert_exl3_group(
    linears: list,
    H_datas: list[dict],
    quant_args_list: list[dict],
    progress_str: str | None = None,
):
    """
    Convert a group of Linear modules to EXL3 in one batched quantization pass (see quantize_exl3_batch for
    the grouping requirements: shared Hessian with equal in_features, or same-shape tensors with individual
    Hessians, all at the same bitrate).

    :return:
        list of proxy errors, one per module; each module's quant_args dict in quant_args_list is updated
        the same way Linear.convert_exl3 updates its quant_args
    """
    weights = []
    biases = []
    for linear in linears:
        assert isinstance(linear.inner, LinearFP16), \
            "Inner layer is already quant type"
        # Checkpoint precision, usually still swapped to CPU: quantize_exl3_batch stages the
        # upload through pinned memory and casts to fp32 on the device
        weights.append(linear.inner.get_weight_tensor())
        biases.append(linear.inner.get_bias_tensor())
        linear.inner = None

    results = quantize_exl3_batch(weights, H_datas, quant_args_list, progress_str)

    proxy_errs = []
    for linear, bias, (proxy_err, out_tensors) in zip(linears, biases, results):
        linear.inner = LinearEXL3(
            linear.config,
            linear.in_features,
            linear.out_features,
            out_tensors.get("scale"),
            out_tensors.get("su"),
            out_tensors.get("sv"),
            out_tensors.get("suh"),
            out_tensors.get("svh"),
            out_tensors.get("trellis"),
            out_tensors.get("mcg"),
            out_tensors.get("mul1"),
            bias,
            linear.out_dtype,
            key = linear.key
        )
        proxy_errs.append(proxy_err)
    return proxy_errs