# SPDX-License-Identifier: Apache-2.0 """GLM-OCR decoder weights for the DEC megakernel (CPU only), adapted from this workspace's Qwen3-ASR DEC (bundles/qwen3-asr tt/mk_dec/weights.py, Apache-2.0). Kernel numerics: residual fp32; norm input bf16(x); rstd from the bf16 values; the input / post_attention RMSNorm gammas folded into the following weight rows (``diag(g) W^T``) and the matmul result scaled by rstd; q / k rows permuted per head to the half-split rope layout (GLM rotates adjacent pairs); rope + the q scale 128^-0.5 in fp32 (tables), bf16 KV; fp32 softmax statistics, bf16 P; SwiGLU in fp32 -> bf16; sandwich norms: x += g * y * rstd(bf16 y); head = ``(bf16(x) @ Q(diag(g_final) lm_head^T)) * rstd``. """ from __future__ import annotations import os from dataclasses import dataclass from typing import Dict, List import torch N_LAYERS, NQ, NKV, HD = 16, 16, 8, 128 EPS = 1e-5 THETA = 10000.0 MROPE = (16, 24, 24) PFX = "model.language_model." SEGMENTS = ("qkv", "o", "gate", "up", "down", "head") def expand_recipe(recipe: Dict[str, str]) -> Dict[str, str]: out = {} for k in SEGMENTS: grp = "attn" if k in ("qkv", "o") else ("mlp" if k in ("gate", "up", "down") else None) out[k] = recipe.get(k, recipe.get(grp, "bf16") if grp else "bf16") return out RECIPES = { "bf16": {"attn": "bf16", "mlp": "bf16", "head": "bf16"}, "bfp8": {"attn": "bfp8", "mlp": "bfp8", "head": "bf16"}, "bfp8h8": {"attn": "bfp8", "mlp": "bfp8", "head": "bfp8"}, } def half_perm() -> torch.Tensor: return torch.cat([torch.arange(0, HD, 2), torch.arange(1, HD, 2)]) def rope_tables(positions: torch.Tensor): """cos / sin [P, 128] of text positions (t = h = w) in the half-split layout (pair j at dims j, 64 + j).""" inv = 1.0 / (THETA ** (torch.arange(0, HD, 2, dtype=torch.float64) / HD)) fr = positions.double()[:, None] * inv[None, :] emb = torch.cat([fr, fr], dim=-1) return emb.cos().float(), emb.sin().float() @dataclass class DecWeights: d: int i: int layers: List[Dict[str, torch.Tensor]] norm: torch.Tensor head: torch.Tensor # lm_head [V, D] embed: torch.Tensor # embed_tokens [V, D] def load_dec(src, n_layers: int = N_LAYERS) -> DecWeights: """From a checkpoint dir / safetensors path, a {name: tensor} dict or a reference ``Weights`` (fp32 copies).""" if hasattr(src, "t") and isinstance(getattr(src, "t"), dict): src = src.t if isinstance(src, dict): return _build(lambda k: src[k].float(), n_layers) from safetensors import safe_open p = os.path.join(src, "model.safetensors") if os.path.isdir(src) else src with safe_open(p, framework="pt") as f: return _build(lambda k: f.get_tensor(k).float(), n_layers) def _build(g, n_layers): perm = half_perm() qp = torch.cat([h * HD + perm for h in range(NQ)]) kp = torch.cat([h * HD + perm for h in range(NKV)]) layers = [] for l in range(n_layers): p = PFX + f"layers.{l}." gu = g(p + "mlp.gate_up_proj.weight") i = gu.shape[0] // 2 layers.append({ "g1": g(p + "input_layernorm.weight"), "g2": g(p + "post_attention_layernorm.weight"), "gpsa": g(p + "post_self_attn_layernorm.weight"), "gpm": g(p + "post_mlp_layernorm.weight"), "wq": g(p + "self_attn.q_proj.weight")[qp], "wk": g(p + "self_attn.k_proj.weight")[kp], "wv": g(p + "self_attn.v_proj.weight"), "wo": g(p + "self_attn.o_proj.weight"), "wg": gu[:i], "wu": gu[i:], "wd": g(p + "mlp.down_proj.weight"), }) norm = g(PFX + "norm.weight") return DecWeights(norm.numel(), layers[0]["wg"].shape[0], layers, norm, g("lm_head.weight"), g(PFX + "embed_tokens.weight"))