# Copyright (c) 2026 Philip Bartsch (@batteryphil). # Licensed under the Bartsch Personal-Free & 5% Commercial Profit-Share License v1.0 (see LICENSE). """ True In-VRAM Compressed PyTorch + Triton Runtime (`PrimeLiveModule`) ==================================================================== Keeps weights permanently compressed in GPU VRAM (`2.50 bpw` `Q2_G32` / `P2_G32` or `4.50 bpw` `P4_G32`) and dequantizes on-the-fly per layer forward pass with zero persistent `FP16`/`BF16` weight copy! Supports `linear`, `embedding`, `conv2d`, and `conv3d`, plus `<1.5s` `torch.device("meta")` SafeTensors v2 serialization and loading. """ from __future__ import annotations import os from typing import Any, Dict, List, Optional, Tuple import torch import torch.nn as nn import torch.nn.functional as F from safetensors import safe_open P2_LUT_LIST: List[float] = [-23.0, -7.0, 5.0, 17.0] P4_LUT_LIST: List[float] = [ -127.0, -101.0, -80.0, -62.0, -46.0, -33.0, -21.0, -10.0, 0.0, 10.0, 21.0, 33.0, 46.0, 62.0, 80.0, 101.0, ] _BYTE_LUT_CACHE: Dict[Tuple[torch.device, torch.dtype, str], torch.Tensor] = {} _TRITON_LUT_CACHE: Dict[Tuple[torch.device, str], torch.Tensor] = {} try: import triton as _triton import triton.language as _tl @_triton.jit def _unpack_p4_g32_triton( qp_ptr, df_ptr, lut_ptr, out_ptr, n_blocks, BLOCK_B: _tl.constexpr, ): pid = _tl.program_id(0) b = pid * BLOCK_B + _tl.arange(0, BLOCK_B) b_mask = b < n_blocks scale = _tl.load(df_ptr + b, mask=b_mask, other=0.0).to(_tl.float32) offs16 = _tl.arange(0, 16) byte_idx = b[:, None] * 16 + offs16[None, :] packed = _tl.load(qp_ptr + byte_idx, mask=b_mask[:, None], other=0).to(_tl.int32) v_lo = _tl.load(lut_ptr + (packed & 0x0F)) * scale[:, None] v_hi = _tl.load(lut_ptr + ((packed >> 4) & 0x0F)) * scale[:, None] v_full = _tl.interleave(v_lo, v_hi).to(out_ptr.dtype.element_ty) offs32 = _tl.arange(0, 32) out_idx = b[:, None] * 32 + offs32[None, :] _tl.store(out_ptr + out_idx, v_full, mask=b_mask[:, None]) @_triton.jit def _unpack_q2_g32_triton( qp_ptr, df_ptr, out_ptr, n_blocks, BLOCK_B: _tl.constexpr, ): pid = _tl.program_id(0) b = pid * BLOCK_B + _tl.arange(0, BLOCK_B) b_mask = b < n_blocks scale = _tl.load(df_ptr + b, mask=b_mask, other=0.0).to(_tl.float32) offs8 = _tl.arange(0, 8) byte_idx = b[:, None] * 8 + offs8[None, :] packed = _tl.load(qp_ptr + byte_idx, mask=b_mask[:, None], other=0).to(_tl.int32) c0 = ((packed & 0x03) - 2).to(_tl.float32) * scale[:, None] c1 = (((packed >> 2) & 0x03) - 2).to(_tl.float32) * scale[:, None] c2 = (((packed >> 4) & 0x03) - 2).to(_tl.float32) * scale[:, None] c3 = (((packed >> 6) & 0x03) - 2).to(_tl.float32) * scale[:, None] ce = _tl.interleave(c0, c2) co = _tl.interleave(c1, c3) v_full = _tl.interleave(ce, co).to(out_ptr.dtype.element_ty) offs32 = _tl.arange(0, 32) out_idx = b[:, None] * 32 + offs32[None, :] _tl.store(out_ptr + out_idx, v_full, mask=b_mask[:, None]) @_triton.jit def _unpack_p2_g32_triton( qp_ptr, df_ptr, lut_ptr, out_ptr, n_blocks, BLOCK_B: _tl.constexpr, ): pid = _tl.program_id(0) b = pid * BLOCK_B + _tl.arange(0, BLOCK_B) b_mask = b < n_blocks scale = _tl.load(df_ptr + b, mask=b_mask, other=0.0).to(_tl.float32) offs8 = _tl.arange(0, 8) byte_idx = b[:, None] * 8 + offs8[None, :] packed = _tl.load(qp_ptr + byte_idx, mask=b_mask[:, None], other=0).to(_tl.int32) c0 = _tl.load(lut_ptr + (packed & 0x03)) * scale[:, None] c1 = _tl.load(lut_ptr + ((packed >> 2) & 0x03)) * scale[:, None] c2 = _tl.load(lut_ptr + ((packed >> 4) & 0x03)) * scale[:, None] c3 = _tl.load(lut_ptr + ((packed >> 6) & 0x03)) * scale[:, None] ce = _tl.interleave(c0, c2) co = _tl.interleave(c1, c3) v_full = _tl.interleave(ce, co).to(out_ptr.dtype.element_ty) offs32 = _tl.arange(0, 32) out_idx = b[:, None] * 32 + offs32[None, :] _tl.store(out_ptr + out_idx, v_full, mask=b_mask[:, None]) @_triton.jit def _dequant_p4_i8_triton( q_ptr, d_ptr, lut_ptr, out_ptr, n_blocks, BLOCK_B: _tl.constexpr, ): pid = _tl.program_id(0) b = pid * BLOCK_B + _tl.arange(0, BLOCK_B) b_mask = b < n_blocks scale = _tl.load(d_ptr + b, mask=b_mask, other=0.0).to(_tl.float32) offs32 = _tl.arange(0, 32) idx = b[:, None] * 32 + offs32[None, :] qi = _tl.load(q_ptr + idx, mask=b_mask[:, None], other=8).to(_tl.int32) v_full = (_tl.load(lut_ptr + qi) * scale[:, None]).to(out_ptr.dtype.element_ty) _tl.store(out_ptr + idx, v_full, mask=b_mask[:, None]) @_triton.jit def _gemv_2bit_g32_triton( x_ptr, qp_ptr, df_ptr, lut_ptr, bias_ptr, e_ids_ptr, out_ptr, rows, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de, stride_xk, IS_MOE: _tl.constexpr, HAS_BIAS: _tl.constexpr, BLOCK_R: _tl.constexpr, GROUPS_K: _tl.constexpr, ): pid_r = _tl.program_id(0) r = pid_r * BLOCK_R + _tl.arange(0, BLOCK_R) r_mask = r < rows r_i64 = r.to(_tl.int64) if IS_MOE: pid_k = _tl.program_id(1) e_raw = _tl.load(e_ids_ptr + pid_k).to(_tl.int64) e_idx = _tl.minimum(_tl.maximum(e_raw, 0), num_experts - 1) qp_base = e_idx * stride_qe df_base = e_idx * stride_de x_base = pid_k.to(_tl.int64) * stride_xk out_base = pid_k.to(_tl.int64) * rows else: qp_base = _tl.cast(0, _tl.int64) df_base = _tl.cast(0, _tl.int64) x_base = _tl.cast(0, _tl.int64) out_base = _tl.cast(0, _tl.int64) acc = _tl.zeros((BLOCK_R,), dtype=_tl.float32) g_offs = _tl.arange(0, GROUPS_K) b_offs = _tl.arange(0, GROUPS_K * 8) x_offs = _tl.arange(0, GROUPS_K * 32) for g0 in range(0, n_groups, GROUPS_K): g = g0 + g_offs g_mask = g < n_groups df_off = df_base + r_i64[:, None] * n_groups + g[None, :] scale = _tl.load(df_ptr + df_off, mask=r_mask[:, None] & g_mask[None, :], other=0.0).to(_tl.float32) xc = g0 * 32 + x_offs xv = _tl.load(x_ptr + x_base + xc, mask=xc < cols_real, other=0.0).to(_tl.float32) xe, xo = _tl.split(xv.reshape(GROUPS_K * 16, 2)) x0, x2 = _tl.split(xe.reshape(GROUPS_K * 8, 2)) x1, x3 = _tl.split(xo.reshape(GROUPS_K * 8, 2)) k_byte = g0 * 8 + b_offs kb_mask = k_byte < pack_cols qp_off = qp_base + r_i64[:, None] * pack_cols + k_byte[None, :] packed = _tl.load(qp_ptr + qp_off, mask=r_mask[:, None] & kb_mask[None, :], other=0).to(_tl.int32) # L0-cached 16-byte 4-float LUT decode (matches P4 throughput, beats 32-op VALU arithmetic by 1.45x on RDNA4) v0 = _tl.load(lut_ptr + (packed & 0x03)) v1 = _tl.load(lut_ptr + ((packed >> 2) & 0x03)) v2 = _tl.load(lut_ptr + ((packed >> 4) & 0x03)) v3 = _tl.load(lut_ptr + ((packed >> 6) & 0x03)) dot = (v0 * x0[None, :] + v1 * x1[None, :] + v2 * x2[None, :] + v3 * x3[None, :]).reshape( BLOCK_R, GROUPS_K, 8 ) acc += _tl.sum(_tl.sum(dot, axis=2) * scale, axis=1) if HAS_BIAS: acc += _tl.load(bias_ptr + r, mask=r_mask, other=0.0).to(_tl.float32) _tl.store(out_ptr + out_base + r_i64, acc.to(out_ptr.dtype.element_ty), mask=r_mask) @_triton.jit def _gemv_p4_g32_triton( x_ptr, qp_ptr, df_ptr, lut_ptr, bias_ptr, e_ids_ptr, out_ptr, rows, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de, stride_xk, IS_MOE: _tl.constexpr, HAS_BIAS: _tl.constexpr, BLOCK_R: _tl.constexpr, GROUPS_K: _tl.constexpr, ): pid_r = _tl.program_id(0) r = pid_r * BLOCK_R + _tl.arange(0, BLOCK_R) r_mask = r < rows r_i64 = r.to(_tl.int64) if IS_MOE: pid_k = _tl.program_id(1) e_raw = _tl.load(e_ids_ptr + pid_k).to(_tl.int64) e_idx = _tl.minimum(_tl.maximum(e_raw, 0), num_experts - 1) qp_base = e_idx * stride_qe df_base = e_idx * stride_de x_base = pid_k.to(_tl.int64) * stride_xk out_base = pid_k.to(_tl.int64) * rows else: qp_base = _tl.cast(0, _tl.int64) df_base = _tl.cast(0, _tl.int64) x_base = _tl.cast(0, _tl.int64) out_base = _tl.cast(0, _tl.int64) acc = _tl.zeros((BLOCK_R,), dtype=_tl.float32) g_offs = _tl.arange(0, GROUPS_K) b_offs = _tl.arange(0, GROUPS_K * 16) x_offs = _tl.arange(0, GROUPS_K * 32) for g0 in range(0, n_groups, GROUPS_K): g = g0 + g_offs g_mask = g < n_groups df_off = df_base + r_i64[:, None] * n_groups + g[None, :] scale = _tl.load(df_ptr + df_off, mask=r_mask[:, None] & g_mask[None, :], other=0.0).to(_tl.float32) xc = g0 * 32 + x_offs xv = _tl.load(x_ptr + x_base + xc, mask=xc < cols_real, other=0.0).to(_tl.float32) x0, x1 = _tl.split(xv.reshape(GROUPS_K * 16, 2)) k_byte = g0 * 16 + b_offs kb_mask = k_byte < pack_cols qp_off = qp_base + r_i64[:, None] * pack_cols + k_byte[None, :] packed = _tl.load(qp_ptr + qp_off, mask=r_mask[:, None] & kb_mask[None, :], other=0).to(_tl.int32) v0 = _tl.load(lut_ptr + (packed & 0x0F)) v1 = _tl.load(lut_ptr + ((packed >> 4) & 0x0F)) dot = (v0 * x0[None, :] + v1 * x1[None, :]).reshape(BLOCK_R, GROUPS_K, 16) acc += _tl.sum(_tl.sum(dot, axis=2) * scale, axis=1) if HAS_BIAS: acc += _tl.load(bias_ptr + r, mask=r_mask, other=0.0).to(_tl.float32) _tl.store(out_ptr + out_base + r_i64, acc.to(out_ptr.dtype.element_ty), mask=r_mask) @_triton.jit def _moe_gu_act_2bit_triton( x_ptr, qp_ptr, df_ptr, lut_ptr, e_ids_ptr, out_ptr, I_dim, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de, G_CAP: _tl.constexpr, U_CAP: _tl.constexpr, BLOCK_R: _tl.constexpr, GROUPS_K: _tl.constexpr, ): """Fused paired gate+up 2-bit MoE GEMV + SwiGLU/SoftcappedSwiGLU epilogue (L0 4-float LUT, 300+ GB/s on RDNA4).""" pid_r = _tl.program_id(0) pid_k = _tl.program_id(1) r = pid_r * BLOCK_R + _tl.arange(0, BLOCK_R) r_mask = r < I_dim rg = r.to(_tl.int64) ru = (r + I_dim).to(_tl.int64) e_raw = _tl.load(e_ids_ptr + pid_k).to(_tl.int64) e_idx = _tl.minimum(_tl.maximum(e_raw, 0), num_experts - 1) qp_base = e_idx * stride_qe df_base = e_idx * stride_de acc_g = _tl.zeros((BLOCK_R,), dtype=_tl.float32) acc_u = _tl.zeros((BLOCK_R,), dtype=_tl.float32) g_offs = _tl.arange(0, GROUPS_K) b_offs = _tl.arange(0, GROUPS_K * 8) x_offs = _tl.arange(0, GROUPS_K * 32) for g0 in range(0, n_groups, GROUPS_K): g = g0 + g_offs g_mask = g < n_groups sg = _tl.load(df_ptr + df_base + rg[:, None] * n_groups + g[None, :], mask=r_mask[:, None] & g_mask[None, :], other=0.0).to(_tl.float32) su = _tl.load(df_ptr + df_base + ru[:, None] * n_groups + g[None, :], mask=r_mask[:, None] & g_mask[None, :], other=0.0).to(_tl.float32) xc = g0 * 32 + x_offs xv = _tl.load(x_ptr + xc, mask=xc < cols_real, other=0.0).to(_tl.float32) xe, xo = _tl.split(xv.reshape(GROUPS_K * 16, 2)) x0, x2 = _tl.split(xe.reshape(GROUPS_K * 8, 2)) x1, x3 = _tl.split(xo.reshape(GROUPS_K * 8, 2)) kb = g0 * 8 + b_offs kbm = kb < pack_cols pg = _tl.load(qp_ptr + qp_base + rg[:, None] * pack_cols + kb[None, :], mask=r_mask[:, None] & kbm[None, :], other=0).to(_tl.int32) pu = _tl.load(qp_ptr + qp_base + ru[:, None] * pack_cols + kb[None, :], mask=r_mask[:, None] & kbm[None, :], other=0).to(_tl.int32) v0 = _tl.load(lut_ptr + (pg & 3)) v1 = _tl.load(lut_ptr + ((pg >> 2) & 3)) v2 = _tl.load(lut_ptr + ((pg >> 4) & 3)) v3 = _tl.load(lut_ptr + ((pg >> 6) & 3)) u0 = _tl.load(lut_ptr + (pu & 3)) u1 = _tl.load(lut_ptr + ((pu >> 2) & 3)) u2 = _tl.load(lut_ptr + ((pu >> 4) & 3)) u3 = _tl.load(lut_ptr + ((pu >> 6) & 3)) dg = (v0 * x0[None, :] + v1 * x1[None, :] + v2 * x2[None, :] + v3 * x3[None, :]).reshape(BLOCK_R, GROUPS_K, 8) du = (u0 * x0[None, :] + u1 * x1[None, :] + u2 * x2[None, :] + u3 * x3[None, :]).reshape(BLOCK_R, GROUPS_K, 8) acc_g += _tl.sum(_tl.sum(dg, axis=2) * sg, axis=1) acc_u += _tl.sum(_tl.sum(du, axis=2) * su, axis=1) tg = (2.0 * _tl.sigmoid(2.0 * (acc_g / G_CAP)) - 1.0) * G_CAP if G_CAP > 0.0 else acc_g tu = (2.0 * _tl.sigmoid(2.0 * (acc_u / U_CAP)) - 1.0) * U_CAP if U_CAP > 0.0 else acc_u res = tg * _tl.sigmoid(acc_g) * tu _tl.store(out_ptr + pid_k.to(_tl.int64) * I_dim + rg, res.to(out_ptr.dtype.element_ty), mask=r_mask) @_triton.jit def _moe_gu_act_p4_triton( x_ptr, qp_ptr, df_ptr, lut_ptr, e_ids_ptr, out_ptr, I_dim, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de, G_CAP: _tl.constexpr, U_CAP: _tl.constexpr, BLOCK_R: _tl.constexpr, GROUPS_K: _tl.constexpr, ): """Fused paired gate+up P4_G32 MoE GEMV + SwiGLU/SoftcappedSwiGLU epilogue.""" pid_r = _tl.program_id(0) pid_k = _tl.program_id(1) r = pid_r * BLOCK_R + _tl.arange(0, BLOCK_R) r_mask = r < I_dim rg = r.to(_tl.int64) ru = (r + I_dim).to(_tl.int64) e_raw = _tl.load(e_ids_ptr + pid_k).to(_tl.int64) e_idx = _tl.minimum(_tl.maximum(e_raw, 0), num_experts - 1) qp_base = e_idx * stride_qe df_base = e_idx * stride_de acc_g = _tl.zeros((BLOCK_R,), dtype=_tl.float32) acc_u = _tl.zeros((BLOCK_R,), dtype=_tl.float32) g_offs = _tl.arange(0, GROUPS_K) b_offs = _tl.arange(0, GROUPS_K * 16) x_offs = _tl.arange(0, GROUPS_K * 32) for g0 in range(0, n_groups, GROUPS_K): g = g0 + g_offs g_mask = g < n_groups sg = _tl.load(df_ptr + df_base + rg[:, None] * n_groups + g[None, :], mask=r_mask[:, None] & g_mask[None, :], other=0.0).to(_tl.float32) su = _tl.load(df_ptr + df_base + ru[:, None] * n_groups + g[None, :], mask=r_mask[:, None] & g_mask[None, :], other=0.0).to(_tl.float32) xc = g0 * 32 + x_offs xv = _tl.load(x_ptr + xc, mask=xc < cols_real, other=0.0).to(_tl.float32) x0, x1 = _tl.split(xv.reshape(GROUPS_K * 16, 2)) kb = g0 * 16 + b_offs kbm = kb < pack_cols pg = _tl.load(qp_ptr + qp_base + rg[:, None] * pack_cols + kb[None, :], mask=r_mask[:, None] & kbm[None, :], other=0).to(_tl.int32) pu = _tl.load(qp_ptr + qp_base + ru[:, None] * pack_cols + kb[None, :], mask=r_mask[:, None] & kbm[None, :], other=0).to(_tl.int32) vg0 = _tl.load(lut_ptr + (pg & 0x0F)); vg1 = _tl.load(lut_ptr + ((pg >> 4) & 0x0F)) vu0 = _tl.load(lut_ptr + (pu & 0x0F)); vu1 = _tl.load(lut_ptr + ((pu >> 4) & 0x0F)) dg = (vg0 * x0[None, :] + vg1 * x1[None, :]).reshape(BLOCK_R, GROUPS_K, 16) du = (vu0 * x0[None, :] + vu1 * x1[None, :]).reshape(BLOCK_R, GROUPS_K, 16) acc_g += _tl.sum(_tl.sum(dg, axis=2) * sg, axis=1) acc_u += _tl.sum(_tl.sum(du, axis=2) * su, axis=1) tg = (2.0 * _tl.sigmoid(2.0 * (acc_g / G_CAP)) - 1.0) * G_CAP if G_CAP > 0.0 else acc_g tu = (2.0 * _tl.sigmoid(2.0 * (acc_u / U_CAP)) - 1.0) * U_CAP if U_CAP > 0.0 else acc_u res = tg * _tl.sigmoid(acc_g) * tu _tl.store(out_ptr + pid_k.to(_tl.int64) * I_dim + rg, res.to(out_ptr.dtype.element_ty), mask=r_mask) @_triton.jit def _moe_weighted_reduce_f32_triton( x_f32_ptr, e_ids_ptr, w_tok_ptr, out_ptr, rows, num_experts, K_EXP: _tl.constexpr, BLOCK_R: _tl.constexpr, ): """Fused FP32 masked weighted reduction across K active experts `[K, rows] -> [1, rows]` (~1.5 us in L2).""" pid = _tl.program_id(0) r = pid * BLOCK_R + _tl.arange(0, BLOCK_R) rm = r < rows r_i64 = r.to(_tl.int64) acc = _tl.zeros((BLOCK_R,), dtype=_tl.float32) for k in range(0, K_EXP): e_raw = _tl.load(e_ids_ptr + k).to(_tl.int64) is_valid = (e_raw >= 0) & (e_raw < num_experts) wk = _tl.where(is_valid, _tl.load(w_tok_ptr + k).to(_tl.float32), 0.0) xv = _tl.load(x_f32_ptr + _tl.cast(k, _tl.int64) * rows + r_i64, mask=rm, other=0.0) acc += wk * xv _tl.store(out_ptr + r_i64, acc.to(out_ptr.dtype.element_ty), mask=rm) _HAS_TRITON_UNPACK = True except Exception: _HAS_TRITON_UNPACK = False def _get_triton_lut(device: torch.device, fmt: str = "p4_0") -> torch.Tensor: key = (device, fmt) lut = _TRITON_LUT_CACHE.get(key) if lut is None: if fmt == "p4_0": vals = P4_LUT_LIST elif fmt == "p2_0": vals = P2_LUT_LIST else: vals = [-2.0, -1.0, 0.0, 1.0] lut = torch.tensor(vals, device=device, dtype=torch.float32).contiguous() _TRITON_LUT_CACHE[key] = lut return lut def _gemv_prime_g32_fast( x_1d: torch.Tensor, qp: torch.Tensor, df: torch.Tensor, bias: Optional[torch.Tensor], fmt: str, rows: int, cols_real: int, pcols: int, ) -> torch.Tensor: """Fused-register Triton GEMV (`y = W @ x + b`) — 64B cacheline-aligned, zero BF16 materialization.""" out = torch.empty((rows,), device=qp.device, dtype=x_1d.dtype) x_c = x_1d.contiguous() n_groups = pcols // 32 pack_cols = qp.shape[1] has_bias = bias is not None b_ptr = bias.contiguous() if has_bias else out lut = _get_triton_lut(qp.device, fmt) if fmt == "p4_0": BLOCK_R = 8 if rows >= 256 else 4 grid = (_triton.cdiv(rows, BLOCK_R),) _gemv_p4_g32_triton[grid]( x_c, qp, df, lut, b_ptr, out, out, rows, cols_real, pack_cols, n_groups, 1, 0, 0, 0, IS_MOE=False, HAS_BIAS=has_bias, BLOCK_R=BLOCK_R, GROUPS_K=4, num_warps=2, ) else: BLOCK_R = 8 if rows >= 256 else 4 grid = (_triton.cdiv(rows, BLOCK_R),) _gemv_2bit_g32_triton[grid]( x_c, qp, df, lut, b_ptr, out, out, rows, cols_real, pack_cols, n_groups, 1, 0, 0, 0, IS_MOE=False, HAS_BIAS=has_bias, BLOCK_R=BLOCK_R, GROUPS_K=8, num_warps=2, ) return out def _gemv_moe_g32_fast( x: torch.Tensor, qp_3d: torch.Tensor, df_3d: torch.Tensor, e_ids: torch.Tensor, fmt: str, rows: int, cols_real: int, pcols: int, shared_x: bool, ) -> torch.Tensor: """Fused-register batched active-expert Triton GEMV (`[K, rows]`) — zero index_select, zero BF16 alloc.""" K = int(e_ids.shape[0]) num_experts = int(qp_3d.shape[0]) out = torch.empty((K, rows), device=qp_3d.device, dtype=x.dtype) x_c = x.contiguous() e_c = e_ids.contiguous() n_groups = pcols // 32 pack_cols = int(qp_3d.shape[2]) stride_qe = int(qp_3d.stride(0)) stride_de = int(df_3d.stride(0)) stride_xk = 0 if shared_x else int(x_c.stride(0)) lut = _get_triton_lut(qp_3d.device, fmt) if fmt == "p4_0": BLOCK_R = 4 grid = (_triton.cdiv(rows, BLOCK_R), K) _gemv_p4_g32_triton[grid]( x_c, qp_3d, df_3d, lut, out, e_c, out, rows, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de, stride_xk, IS_MOE=True, HAS_BIAS=False, BLOCK_R=BLOCK_R, GROUPS_K=4, num_warps=1, ) else: BLOCK_R = 8 if rows >= 256 else 4 grid = (_triton.cdiv(rows, BLOCK_R), K) _gemv_2bit_g32_triton[grid]( x_c, qp_3d, df_3d, lut, out, e_c, out, rows, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de, stride_xk, IS_MOE=True, HAS_BIAS=False, BLOCK_R=BLOCK_R, GROUPS_K=8, num_warps=2, ) return out def _gemv_moe_gu_act_fast( x_1d: torch.Tensor, qp_3d: torch.Tensor, df_3d: torch.Tensor, e_ids: torch.Tensor, fmt: str, inter_dim: int, cols_real: int, pcols: int, num_experts: int, g_cap: float, u_cap: float, ) -> torch.Tensor: """Fused paired gate+up Triton MoE GEMV + SwiGLU/SoftcappedSwiGLU -> `[K, inter_dim]` (300+ GB/s on RDNA4).""" K = int(e_ids.shape[0]) out = torch.empty((K, inter_dim), device=qp_3d.device, dtype=x_1d.dtype) x_c = x_1d.contiguous() e_c = e_ids.contiguous() n_groups = pcols // 32 pack_cols = int(qp_3d.shape[2]) stride_qe = int(qp_3d.stride(0)) stride_de = int(df_3d.stride(0)) lut = _get_triton_lut(qp_3d.device, fmt) if fmt == "p4_0": BLOCK_R = 4 grid = (_triton.cdiv(inter_dim, BLOCK_R), K) _moe_gu_act_p4_triton[grid]( x_c, qp_3d, df_3d, lut, e_c, out, inter_dim, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de, G_CAP=g_cap, U_CAP=u_cap, BLOCK_R=BLOCK_R, GROUPS_K=4, num_warps=1, ) else: BLOCK_R = 8 if inter_dim >= 64 else 4 grid = (_triton.cdiv(inter_dim, BLOCK_R), K) _moe_gu_act_2bit_triton[grid]( x_c, qp_3d, df_3d, lut, e_c, out, inter_dim, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de, G_CAP=g_cap, U_CAP=u_cap, BLOCK_R=BLOCK_R, GROUPS_K=8, num_warps=2, ) return out def _gemv_moe_dn_reduce_fast( x_kh: torch.Tensor, qp_3d: torch.Tensor, df_3d: torch.Tensor, e_ids: torch.Tensor, w_tok: torch.Tensor, fmt: str, rows: int, cols_real: int, pcols: int, num_experts: int, ) -> torch.Tensor: """Parallel-K down_proj Triton GEMV (FP32 L2 intermediate) + fused masked weighted reduce -> `[1, rows]`.""" K = int(e_ids.shape[0]) out_kh_f32 = torch.empty((K, rows), device=qp_3d.device, dtype=torch.float32) out = torch.empty((1, rows), device=qp_3d.device, dtype=x_kh.dtype) x_c = x_kh.contiguous() e_c = e_ids.contiguous() w_c = w_tok.contiguous() n_groups = pcols // 32 pack_cols = int(qp_3d.shape[2]) stride_qe = int(qp_3d.stride(0)) stride_de = int(df_3d.stride(0)) stride_xk = int(x_c.stride(0)) lut = _get_triton_lut(qp_3d.device, fmt) BLOCK_R = 4 grid = (_triton.cdiv(rows, BLOCK_R), K) if fmt == "p4_0": _gemv_p4_g32_triton[grid]( x_c, qp_3d, df_3d, lut, out_kh_f32, e_c, out_kh_f32, rows, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de, stride_xk, IS_MOE=True, HAS_BIAS=False, BLOCK_R=BLOCK_R, GROUPS_K=4, num_warps=1, ) else: _gemv_2bit_g32_triton[grid]( x_c, qp_3d, df_3d, lut, out_kh_f32, e_c, out_kh_f32, rows, cols_real, pack_cols, n_groups, num_experts, stride_qe, stride_de, stride_xk, IS_MOE=True, HAS_BIAS=False, BLOCK_R=BLOCK_R, GROUPS_K=4, num_warps=1, ) _moe_weighted_reduce_f32_triton[(_triton.cdiv(rows, 256),)]( out_kh_f32, e_c, w_c, out, rows, num_experts, K_EXP=K, BLOCK_R=256, num_warps=4, ) return out def _unpack_packed_2d_fast( qp: torch.Tensor, df: torch.Tensor, fmt: str, rows: int, pcols: int, group_size: int, target_dtype: torch.dtype, ) -> torch.Tensor: """Fast Triton (G=32 on CUDA for p4_0/p2_0/q2_0) or byte-LUT fallback unpacker -> [rows, pcols].""" if ( _HAS_TRITON_UNPACK and qp.is_cuda and group_size == 32 and fmt in ("p4_0", "p2_0", "q2_0") and target_dtype in (torch.bfloat16, torch.float16, torch.float32) and (pcols & 31) == 0 ): qp_c = qp.contiguous() df_c = df.contiguous() w2 = torch.empty((rows, pcols), device=qp.device, dtype=target_dtype) nb = rows * (pcols // 32) grid = (_triton.cdiv(nb, 32),) if fmt == "p4_0": _unpack_p4_g32_triton[grid](qp_c, df_c, _get_triton_lut(qp.device, "p4_0"), w2, nb, BLOCK_B=32) elif fmt == "p2_0": _unpack_p2_g32_triton[grid](qp_c, df_c, _get_triton_lut(qp.device, "p2_0"), w2, nb, BLOCK_B=32) else: _unpack_q2_g32_triton[grid](qp_c, df_c, w2, nb, BLOCK_B=32) return w2 lut = _get_byte_lut(qp.device, torch.float32, fmt) cv = F.embedding(qp.to(torch.int32), lut).view(rows, pcols // group_size, group_size) return (cv * df.float().unsqueeze(-1)).to(target_dtype).view(rows, pcols) def _get_byte_lut(device: torch.device, dtype: torch.dtype, fmt: str) -> torch.Tensor: key = (device, dtype, fmt) lut = _BYTE_LUT_CACHE.get(key) if lut is None: idx = torch.arange(256, dtype=torch.int32) if fmt == "q2_0": c0 = (idx & 0x03) - 2 c1 = ((idx >> 2) & 0x03) - 2 c2 = ((idx >> 4) & 0x03) - 2 c3 = ((idx >> 6) & 0x03) - 2 lut = torch.stack([c0, c1, c2, c3], dim=-1).to(device=device, dtype=dtype).contiguous() elif fmt == "p2_0": p2_t = torch.tensor(P2_LUT_LIST, dtype=torch.float32) lut = torch.stack( [p2_t[idx & 0x03], p2_t[(idx >> 2) & 0x03], p2_t[(idx >> 4) & 0x03], p2_t[(idx >> 6) & 0x03]], dim=-1 ).to(device=device, dtype=dtype).contiguous() else: p4_t = torch.tensor(P4_LUT_LIST, dtype=torch.float32) lut = torch.stack([p4_t[idx & 0x0F], p4_t[(idx >> 4) & 0x0F]], dim=-1).to(device=device, dtype=dtype).contiguous() _BYTE_LUT_CACHE[key] = lut return lut def weight_to_2d_tap_separated(mod: nn.Module, G: int = 32) -> Tuple[torch.Tensor, int, int, Tuple[int, ...], bool]: """ Maps `Linear`, `Embedding`, `Conv2d`, or `Conv3d` weights to `[rows, pcols]` (`pcols % G == 0`), isolating spatial/temporal `Conv2d`/`Conv3d` kernel taps `(kT, kH, kW)` into separate rows so that every `G`-element quantization block lies strictly along `C_in` without cross-tap bleeding. """ w = mod.weight.detach().float() orig_shape = tuple(w.shape) if isinstance(mod, (nn.Linear, nn.Embedding)): rows, cols = w.shape tap_perm = False w2 = w elif isinstance(mod, (nn.Conv2d, nn.Conv3d)): spatial_prod = 1 for d in orig_shape[2:]: spatial_prod *= d if spatial_prod > 1 and orig_shape[1] >= G and (orig_shape[1] % G == 0): perm = [0] + list(range(2, len(orig_shape))) + [1] w_p = w.permute(*perm).contiguous() cols = orig_shape[1] rows = w.numel() // cols w2 = w_p.view(rows, cols) tap_perm = True else: rows = orig_shape[0] cols = w.numel() // rows w2 = w.reshape(rows, cols) tap_perm = False else: raise TypeError(f"Unsupported module type: {type(mod)}") pad_c = (G - (cols % G)) % G if pad_c > 0: w2 = F.pad(w2, (0, pad_c), value=0.0) return w2, rows, cols, orig_shape, tap_perm def reconstruct_from_2d(w2: torch.Tensor, orig_shape: Tuple[int, ...], tap_perm: bool, dtype: torch.dtype) -> torch.Tensor: if not tap_perm: return w2.reshape(orig_shape).to(dtype) c_out = orig_shape[0] c_in = orig_shape[1] sp = orig_shape[2:] w_p = w2.view(c_out, *sp, c_in) inv_perm = [0, len(orig_shape) - 1] + list(range(1, len(orig_shape) - 1)) return w_p.permute(*inv_perm).contiguous().to(dtype) class PrimeLiveModule(nn.Module): """ In-VRAM compressed module (`p4_0`, `p2_0`, or `q2_0`, `G=32`) supporting `linear`, `embedding`, `conv2d`, and `conv3d` with on-the-fly Triton unpacking and `_keep_in_fp32_modules` protection. """ def __init__( self, op_kind: str, fmt: str, orig_shape: Tuple[int, ...], cols: int, tap_perm: bool, q_pack: torch.Tensor, d_f16: torch.Tensor, bias: Optional[torch.Tensor] = None, compute_dtype: torch.dtype = torch.bfloat16, conv_kwargs: Optional[Dict[str, Any]] = None, ): super().__init__() assert fmt in ("p4_0", "p2_0", "q2_0") self.op_kind = op_kind self.fmt = fmt self.orig_shape = orig_shape self.rows = q_pack.shape[0] self.cols = cols self.pcols = q_pack.shape[1] * (4 if fmt in ("q2_0", "p2_0") else 2) assert d_f16.ndim == 2 and d_f16.shape[0] == self.rows and (self.pcols % d_f16.shape[1] == 0) self.group_size = self.pcols // d_f16.shape[1] self.tap_perm = tap_perm self.compute_dtype = compute_dtype self.conv_kwargs = conv_kwargs or {} if op_kind == "linear": self.in_features = orig_shape[1] self.out_features = orig_shape[0] elif op_kind == "embedding": self.num_embeddings = orig_shape[0] self.embedding_dim = orig_shape[1] else: self.out_channels = orig_shape[0] self.in_channels = orig_shape[1] * self.conv_kwargs.get("groups", 1) self.kernel_size = orig_shape[2:] self.stride = self.conv_kwargs.get("stride", 1) self.padding = self.conv_kwargs.get("padding", 0) self.dilation = self.conv_kwargs.get("dilation", 1) self.groups = self.conv_kwargs.get("groups", 1) self.register_buffer("q_pack", q_pack.to(torch.uint8).contiguous()) self.register_buffer("d_f16", d_f16.to(torch.float16).contiguous()) self._dtype_anchor = nn.Parameter(torch.empty(0, dtype=compute_dtype), requires_grad=False) if bias is not None: self.register_buffer("bias", bias.to(compute_dtype).contiguous()) else: self.bias = None def _apply(self, fn, recurse=True): # Preserve exact FP16 scale mantissa and FP32-protected bias across dtype casts # (e.g., `model.to(torch.bfloat16)`), while still honoring device transfers. orig_d = self.d_f16 orig_bias = self.bias super()._apply(fn, recurse=recurse) target_dev = self.q_pack.device if not orig_d.is_meta and not self.d_f16.is_meta: if self.d_f16.dtype != torch.float16: self.d_f16 = orig_d if orig_d.device == target_dev else orig_d.to(device=target_dev, dtype=torch.float16) elif self.d_f16.dtype != torch.float16: self.d_f16 = self.d_f16.to(torch.float16) if self.compute_dtype == torch.float32: if self._dtype_anchor.dtype != torch.float32: self._dtype_anchor = nn.Parameter( torch.empty(0, device=target_dev, dtype=torch.float32), requires_grad=False ) if orig_bias is not None and not orig_bias.is_meta and not self.bias.is_meta: if self.bias.dtype != torch.float32: self.bias = orig_bias if orig_bias.device == target_dev else orig_bias.to(device=target_dev, dtype=torch.float32) elif self.bias is not None and self.bias.dtype != torch.float32: self.bias = self.bias.to(torch.float32) return self @property def weight(self) -> torch.Tensor: return self._dtype_anchor def unpack_weight(self, target_dtype: torch.dtype) -> torch.Tensor: w2 = _unpack_packed_2d_fast(self.q_pack, self.d_f16, self.fmt, self.rows, self.pcols, self.group_size, target_dtype) if self.pcols > self.cols: w2 = w2[:, : self.cols] return reconstruct_from_2d(w2, self.orig_shape, self.tap_perm, target_dtype) def forward(self, x: torch.Tensor) -> torch.Tensor: if self.op_kind == "embedding": flat = x.reshape(-1) n_sel = int(flat.numel()) qp_s = self.q_pack.index_select(0, flat) df_s = self.d_f16.index_select(0, flat) w2 = _unpack_packed_2d_fast(qp_s, df_s, self.fmt, n_sel, self.pcols, self.group_size, self.compute_dtype) if self.pcols > self.cols: w2 = w2[:, : self.cols] out = w2.view(*x.shape, self.cols) embed_norm = getattr(self, "embed_norm", None) if embed_norm is not None: out = embed_norm(out) return out dt = x.dtype if ( self.op_kind == "linear" and _HAS_TRITON_UNPACK and self.q_pack.is_cuda and self.group_size == 32 and not self.tap_perm and self.fmt in ("p4_0", "p2_0", "q2_0") and dt in (torch.bfloat16, torch.float16, torch.float32) and x.numel() == self.cols ): y = _gemv_prime_g32_fast( x.reshape(-1), self.q_pack, self.d_f16, self.bias, self.fmt, self.rows, self.cols, self.pcols ) return y.view(*x.shape[:-1], self.rows) w = self.unpack_weight(dt) b = (self.bias if self.bias.dtype == dt else self.bias.to(dt)) if self.bias is not None else None if self.op_kind == "linear": return F.linear(x, w, b) if self.op_kind == "conv2d": return F.conv2d(x, w, b, self.stride, self.padding, self.dilation, self.groups) return F.conv3d(x, w, b, self.stride, self.padding, self.dilation, self.groups) class PrimeLiveMoEExperts(nn.Module): """ In-VRAM compressed 3D Mixture-of-Experts bank (`gate_up_proj` + `down_proj` across `E` experts) in `p2_0`, `q2_0`, or `p4_0`. At decode (`T == 1`), runs fused-register batched Triton GEMV directly over the `top_k` active experts with zero weight materialization; at prefill (`T > 1`), unpacks one hit expert at a time to keep peak VRAM tiny. """ def __init__( self, fmt: str, num_experts: int, hidden_dim: int, intermediate_dim: int, gu_q: torch.Tensor, gu_d: torch.Tensor, dn_q: torch.Tensor, dn_d: torch.Tensor, act_fn: nn.Module, compute_dtype: torch.dtype = torch.bfloat16, dn_fmt: Optional[str] = None, ): super().__init__() import inspect dn_fmt_eff = fmt if dn_fmt is None else dn_fmt assert fmt in ("p4_0", "p2_0", "q2_0") and dn_fmt_eff in ("p4_0", "p2_0", "q2_0") self.fmt = fmt self.dn_fmt = dn_fmt_eff self.num_experts = int(num_experts) self.hidden_dim = int(hidden_dim) self.intermediate_dim = int(intermediate_dim) self.compute_dtype = compute_dtype self.act_fn = act_fn try: sig = inspect.signature(act_fn.forward) self._act_two_arg = len(sig.parameters) >= 2 except Exception: self._act_two_arg = False if hasattr(act_fn, "gate_softcap") and hasattr(act_fn, "up_softcap"): g_sc = getattr(act_fn.gate_softcap, "softcap", None) u_sc = getattr(act_fn.up_softcap, "softcap", None) self._fused_act: Optional[Tuple[float, float]] = ( float(g_sc) if g_sc is not None else 0.0, float(u_sc) if u_sc is not None else 0.0, ) elif isinstance(act_fn, nn.SiLU): self._fused_act = (0.0, 0.0) else: self._fused_act = None gu_pack_mul = 4 if fmt in ("q2_0", "p2_0") else 2 dn_pack_mul = 4 if dn_fmt_eff in ("q2_0", "p2_0") else 2 self.gu_rows = int(gu_q.shape[1]) self.gu_pcols = int(gu_q.shape[2]) * gu_pack_mul self.dn_rows = int(dn_q.shape[1]) self.dn_pcols = int(dn_q.shape[2]) * dn_pack_mul self.group_size = self.gu_pcols // int(gu_d.shape[2]) assert self.dn_pcols // int(dn_d.shape[2]) == self.group_size self.register_buffer("gu_q", gu_q.to(torch.uint8).contiguous()) self.register_buffer("gu_d", gu_d.to(torch.float16).contiguous()) self.register_buffer("dn_q", dn_q.to(torch.uint8).contiguous()) self.register_buffer("dn_d", dn_d.to(torch.float16).contiguous()) def _apply(self, fn, recurse=True): orig_gu_d = self.gu_d orig_dn_d = self.dn_d super()._apply(fn, recurse=recurse) target_dev = self.gu_q.device for attr, orig in (("gu_d", orig_gu_d), ("dn_d", orig_dn_d)): cur = getattr(self, attr) if not orig.is_meta and not cur.is_meta: if cur.dtype != torch.float16: setattr(self, attr, orig if orig.device == target_dev else orig.to(device=target_dev, dtype=torch.float16)) elif cur.dtype != torch.float16: setattr(self, attr, cur.to(torch.float16)) return self def _apply_gate(self, gate_up: torch.Tensor) -> torch.Tensor: gate, up = gate_up.chunk(2, dim=-1) if self._act_two_arg: return self.act_fn(gate, up) return self.act_fn(gate) * up def forward( self, hidden_states: torch.Tensor, top_k_index: torch.Tensor, top_k_weights: torch.Tensor ) -> torch.Tensor: T, H = hidden_states.shape dt = hidden_states.dtype if T == 1: e_raw = top_k_index[0] if ( _HAS_TRITON_UNPACK and self.gu_q.is_cuda and self.group_size == 32 and self.fmt in ("p4_0", "p2_0", "q2_0") and self.dn_fmt in ("p4_0", "p2_0", "q2_0") and dt in (torch.bfloat16, torch.float16, torch.float32) ): if self._fused_act is not None and self.gu_rows == 2 * self.intermediate_dim: h_mid = _gemv_moe_gu_act_fast( hidden_states[0], self.gu_q, self.gu_d, e_raw, self.fmt, self.intermediate_dim, H, self.gu_pcols, self.num_experts, self._fused_act[0], self._fused_act[1], ) else: e_ids = e_raw.clamp(0, self.num_experts - 1) gu_out = _gemv_moe_g32_fast( hidden_states[0], self.gu_q, self.gu_d, e_ids, self.fmt, self.gu_rows, H, self.gu_pcols, shared_x=True, ) h_mid = self._apply_gate(gu_out) return _gemv_moe_dn_reduce_fast( h_mid, self.dn_q, self.dn_d, e_raw, top_k_weights[0], self.dn_fmt, self.dn_rows, self.intermediate_dim, self.dn_pcols, self.num_experts, ) valid = ((e_raw >= 0) & (e_raw < self.num_experts)).to(torch.float32) e_ids = e_raw.clamp(0, self.num_experts - 1) w_tok = (top_k_weights[0].float() * valid).unsqueeze(-1) K = int(e_ids.shape[0]) gu_q_k = self.gu_q.index_select(0, e_ids).reshape(K * self.gu_rows, -1) gu_d_k = self.gu_d.index_select(0, e_ids).reshape(K * self.gu_rows, -1) w_gu = _unpack_packed_2d_fast(gu_q_k, gu_d_k, self.fmt, K * self.gu_rows, self.gu_pcols, self.group_size, dt) if self.gu_pcols > H: w_gu = w_gu[:, :H] w_gu = w_gu.view(K, self.gu_rows, H) gu_out = torch.bmm(hidden_states.expand(K, H).unsqueeze(1), w_gu.transpose(1, 2)).squeeze(1) del w_gu h_mid = self._apply_gate(gu_out) dn_q_k = self.dn_q.index_select(0, e_ids).reshape(K * self.dn_rows, -1) dn_d_k = self.dn_d.index_select(0, e_ids).reshape(K * self.dn_rows, -1) w_dn = _unpack_packed_2d_fast(dn_q_k, dn_d_k, self.dn_fmt, K * self.dn_rows, self.dn_pcols, self.group_size, dt) if self.dn_pcols > self.intermediate_dim: w_dn = w_dn[:, : self.intermediate_dim] w_dn = w_dn.view(K, self.dn_rows, self.intermediate_dim) dn_out = torch.bmm(h_mid.unsqueeze(1), w_dn.transpose(1, 2)).squeeze(1).float() del w_dn return (dn_out * w_tok).sum(dim=0, keepdim=True).to(dt) final_hidden_states = torch.zeros_like(hidden_states, dtype=torch.float32) with torch.no_grad(): expert_mask = F.one_hot(top_k_index, num_classes=self.num_experts + 1).permute(2, 1, 0) expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero() for expert_idx_t in expert_hit: expert_idx = int(expert_idx_t[0].item()) if expert_idx >= self.num_experts: continue top_k_pos, token_idx = torch.where(expert_mask[expert_idx]) current_state = hidden_states[token_idx] w_gu = _unpack_packed_2d_fast( self.gu_q[expert_idx], self.gu_d[expert_idx], self.fmt, self.gu_rows, self.gu_pcols, self.group_size, dt ) if self.gu_pcols > H: w_gu = w_gu[:, :H] h_mid = self._apply_gate(F.linear(current_state, w_gu)) del w_gu w_dn = _unpack_packed_2d_fast( self.dn_q[expert_idx], self.dn_d[expert_idx], self.dn_fmt, self.dn_rows, self.dn_pcols, self.group_size, dt ) if self.dn_pcols > self.intermediate_dim: w_dn = w_dn[:, : self.intermediate_dim] cur_out = F.linear(h_mid, w_dn) del w_dn cur_out = cur_out * top_k_weights[token_idx, top_k_pos, None] final_hidden_states.index_add_(0, token_idx, cur_out.to(torch.float32)) return final_hidden_states.to(dt) def get_submod(root: nn.Module, path: str) -> nn.Module: cur = root for p in path.split("."): cur = cur[int(p)] if p.isdigit() else getattr(cur, p) return cur def set_submod(root: nn.Module, path: str, new_mod: nn.Module) -> None: parts = path.split(".") parent = root for p in parts[:-1]: parent = parent[int(p)] if p.isdigit() else getattr(parent, p) last = parts[-1] if last.isdigit(): parent[int(last)] = new_mod else: setattr(parent, last, new_mod) def _parse_tuple_or_int(s: str): s = s.strip() if s.startswith("(") and s.endswith(")"): return tuple(int(x.strip()) for x in s[1:-1].split(",") if x.strip()) return int(s) def _get_fp32_patterns(model: nn.Module) -> Tuple[str, ...]: pats: List[str] = [] for attr in ("_keep_in_fp32_modules", "_keep_in_fp32_modules_strict"): val = getattr(model, attr, None) if val: pats.extend(str(v) for v in val) return tuple(dict.fromkeys(pats)) def _is_fp32_protected(full_name: str, fp32_patterns: Tuple[str, ...]) -> bool: if not fp32_patterns: return False segs = set(full_name.split(".")) for pat in fp32_patterns: if "." in pat: if ( full_name == pat or full_name.endswith("." + pat) or (f".{pat}." in full_name) or full_name.startswith(f"{pat}.") ): return True elif pat in segs: return True return False @torch.no_grad() def load_prime_safetensors( skeleton_model: nn.Module, safetensors_path: str, device: str = "cuda", compute_dtype: torch.dtype = torch.bfloat16, ) -> Dict[str, Any]: """ Hydrates a `torch.device("meta")` or CPU `skeleton_model` with in-VRAM `PrimeLiveModule` and `PrimeLiveMoEExperts` modules in `<1.5s`, honoring `_keep_in_fp32_modules[_strict]`, persistent buffers (e.g. MoE router bias), normed embeddings, and tied `shared <-> encoder.embed_tokens`. """ fp32_pats = _get_fp32_patterns(skeleton_model) n_2bit, n_4bit = 0, 0 with safe_open(safetensors_path, framework="pt", device="cpu") as f: meta = f.metadata() or {} keys = set(f.keys()) for mk, mval in sorted(meta.items()): if not mk.startswith("mod:"): continue mname = mk[4:] op_kind, fmt, tap_s, cols_s, shape_s, conv_s = mval.split(";", 5) tap_perm = bool(int(tap_s)) cols = int(cols_s) orig_shape = tuple(int(x) for x in shape_s.split(",")) conv_kw = {} if conv_s: st_s, pa_s, di_s, gr_s = conv_s.split("|") conv_kw = { "stride": _parse_tuple_or_int(st_s), "padding": _parse_tuple_or_int(pa_s), "dilation": _parse_tuple_or_int(di_s), "groups": int(gr_s), } qp = f.get_tensor(f"{mname}.__q").to(device) df = f.get_tensor(f"{mname}.__d").to(device) bt = f.get_tensor(f"{mname}.__b").to(device) if f"{mname}.__b" in keys else None is_fp32_mod = _is_fp32_protected(mname, fp32_pats) eff_dt = torch.float32 if is_fp32_mod else compute_dtype old_mod = get_submod(skeleton_model, mname) live_mod = PrimeLiveModule( op_kind=op_kind, fmt=fmt, orig_shape=orig_shape, cols=cols, tap_perm=tap_perm, q_pack=qp, d_f16=df, bias=bt, compute_dtype=eff_dt, conv_kwargs=conv_kw, ).to(device) if op_kind == "embedding" and hasattr(old_mod, "embed_norm") and old_mod.embed_norm is not None: live_mod.embed_norm = old_mod.embed_norm set_submod(skeleton_model, mname, live_mod) if fmt in ("q2_0", "p2_0"): n_2bit += 1 else: n_4bit += 1 for mk, mval in sorted(meta.items()): if not mk.startswith("moe:"): continue mname = mk[4:] fmt_spec, ne_s, hd_s, id_s = mval.split(";", 3) if "/" in fmt_spec: fmt, dn_fmt = fmt_spec.split("/", 1) else: fmt, dn_fmt = fmt_spec, fmt_spec old_mod = get_submod(skeleton_model, mname) act_fn = getattr(old_mod, "act_fn", nn.SiLU()) live_moe = PrimeLiveMoEExperts( fmt=fmt, num_experts=int(ne_s), hidden_dim=int(hd_s), intermediate_dim=int(id_s), gu_q=f.get_tensor(f"{mname}.__gu_q").to(device), gu_d=f.get_tensor(f"{mname}.__gu_d").to(device), dn_q=f.get_tensor(f"{mname}.__dn_q").to(device), dn_d=f.get_tensor(f"{mname}.__dn_d").to(device), act_fn=act_fn, compute_dtype=compute_dtype, dn_fmt=dn_fmt, ).to(device) set_submod(skeleton_model, mname, live_moe) if fmt in ("q2_0", "p2_0") or dn_fmt in ("q2_0", "p2_0"): n_2bit += 1 else: n_4bit += 1 q_suffixes = (".__q", ".__d", ".__b", ".__gu_q", ".__gu_d", ".__dn_q", ".__dn_d") for k in keys: if k.endswith(q_suffixes): continue parts = k.split(".") parent = get_submod(skeleton_model, ".".join(parts[:-1])) if len(parts) > 1 else skeleton_model leaf = parts[-1] if hasattr(parent, "_parameters") and leaf in parent._parameters and parent._parameters[leaf] is not None: p_tgt = parent._parameters[leaf] t_src = f.get_tensor(k) is_fp32_prot = _is_fp32_protected(k, fp32_pats) tgt_dt = ( (torch.float32 if t_src.dtype in (torch.float16, torch.bfloat16) else t_src.dtype) if is_fp32_prot else (compute_dtype if p_tgt.is_floating_point() else p_tgt.dtype) ) parent._parameters[leaf] = nn.Parameter(t_src.to(device=device, dtype=tgt_dt), requires_grad=False) elif hasattr(parent, "_buffers") and leaf in parent._buffers: b_tgt = parent._buffers[leaf] t_src = f.get_tensor(k) is_fp32_prot = _is_fp32_protected(k, fp32_pats) if is_fp32_prot: tgt_dt = torch.float32 if t_src.dtype in (torch.float16, torch.bfloat16) else t_src.dtype elif b_tgt is not None: tgt_dt = t_src.dtype if (t_src.dtype == torch.float32 and b_tgt.dtype == torch.float32) else (compute_dtype if b_tgt.is_floating_point() else b_tgt.dtype) else: tgt_dt = t_src.dtype parent._buffers[leaf] = t_src.to(device=device, dtype=tgt_dt) if hasattr(skeleton_model, "tie_weights"): try: skeleton_model.tie_weights() except Exception: pass if ( hasattr(skeleton_model, "shared") and hasattr(skeleton_model, "encoder") and hasattr(skeleton_model.encoder, "embed_tokens") and isinstance(skeleton_model.shared, PrimeLiveModule) ): skeleton_model.encoder.embed_tokens = skeleton_model.shared vault_mods = {m for m in skeleton_model.modules() if isinstance(m, (PrimeLiveModule, PrimeLiveMoEExperts))} moved_ptrs: Dict[Tuple[int, bool], nn.Parameter] = {} for sub_path, sub in skeleton_model.named_modules(): if sub in vault_mods: continue for pname, p in sub._parameters.items(): if p is not None and not p.is_meta: full_n = f"{sub_path}.{pname}" if sub_path else pname is_fp32_prot = _is_fp32_protected(full_n, fp32_pats) pkey = (p.data_ptr(), is_fp32_prot) if pkey not in moved_ptrs: tgt_dt = ( (torch.float32 if p.dtype in (torch.float16, torch.bfloat16) else p.dtype) if is_fp32_prot else (compute_dtype if p.is_floating_point() else p.dtype) ) moved_ptrs[pkey] = nn.Parameter(p.data.to(device=device, dtype=tgt_dt), requires_grad=p.requires_grad) sub._parameters[pname] = moved_ptrs[pkey] for bname, b in sub._buffers.items(): if b is not None and not b.is_meta: full_bn = f"{sub_path}.{bname}" if sub_path else bname is_fp32_prot = _is_fp32_protected(full_bn, fp32_pats) tgt_bdt = ( (torch.float32 if b.dtype in (torch.float16, torch.bfloat16) else b.dtype) if is_fp32_prot else (compute_dtype if b.is_floating_point() else b.dtype) ) sub._buffers[bname] = b.to(device=device, dtype=tgt_bdt) skeleton_model.eval() vram_bytes = sum(b.numel() * b.element_size() for b in skeleton_model.buffers()) + sum( p.numel() * p.element_size() for p in skeleton_model.parameters() ) return { "modules_2bit": n_2bit, "modules_4bit": n_4bit, "resident_vram_mb": round(vram_bytes / 1e6, 2), "file_mb": round(os.path.getsize(safetensors_path) / 1e6, 2), }