# SPDX-License-Identifier: Apache-2.0 """Decoder weights of the DEC megakernel (CPU only): the ERNIE-4.5-0.3B text decoder of a PaddleOCR-VL checkpoint as fp32 tensors in the kernel's Qwen3-0.6B-shaped layout (copied from this workspace's Qwen3-ASR DEC megakernel, Apache-2.0): * 16 q heads, 2 kv heads (GQA 8 : 1) -> the kernel's 8 kv groups of 2 q heads: real kv head j is repeated 4 times (virtual group g = real head g // 4; q heads 2g, 2g + 1 belong to group g, the same real kv head as in ERNIE's repeat_kv: q head h -> kv head h // 8). The KV cache holds the 8 virtual heads (the ttnn prefill repeats K / V). * no q / k RMSNorm: gq / gk = ones (the kernel runs with MT_QKNORM 0: q x 128^-0.5 only). * the untied LM head (lm_head.weight) feeds the H stream; embed_tokens is the step input table. Kernel numerics (as the talker megakernel): residual fp32; norm input bf16(x); rstd from the bf16 values; RMSNorm gammas folded into the following weight rows (``diag(g) W^T``) and the matmul result scaled by rstd; RoPE in fp32, bf16 KV; fp32 softmax statistics, bf16 P; SwiGLU in fp32 -> bf16; head = ``(bf16(x) @ Q(diag(g_final) H^T)) * rstd``. """ from __future__ import annotations import os from dataclasses import dataclass from typing import Dict, List import torch N_LAYERS, NQ, NKV, HD = 18, 16, 8, 128 # NKV = the kernel's (virtual) kv groups NKV_REAL = 2 KV_REP = NKV // NKV_REAL EPS = 1e-5 THETA = 500000.0 PFX = "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 rope_tables(positions: torch.Tensor): inv = 1.0 / (THETA ** (torch.arange(0, HD, 2, dtype=torch.int64).float() / HD)) fr = positions.float()[:, 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 # [V, D] lm_head embed: torch.Tensor # [V, D] embed_tokens def load_dec(path_or_dict, n_layers: int = N_LAYERS) -> DecWeights: """From a checkpoint dir / safetensors path or a {name: tensor} dict (any dtype; converted to fp32).""" if isinstance(path_or_dict, dict): return _build(lambda k: path_or_dict[k].float(), n_layers) from safetensors import safe_open p = os.path.join(path_or_dict, "model.safetensors") if os.path.isdir(path_or_dict) else path_or_dict with safe_open(p, framework="pt") as f: return _build(lambda k: f.get_tensor(k).float(), n_layers) def expand_kv(w: torch.Tensor) -> torch.Tensor: """[NKV_REAL * HD, D] -> [NKV * HD, D] (each real head repeated KV_REP times, consecutively).""" d = w.shape[1] return w.reshape(NKV_REAL, 1, HD, d).expand(NKV_REAL, KV_REP, HD, d).reshape(NKV * HD, d).contiguous() def _build(g, n_layers): layers = [] ones = torch.ones(HD) for l in range(n_layers): p = PFX + f"layers.{l}." layers.append({ "g1": g(p + "input_layernorm.weight"), "g2": g(p + "post_attention_layernorm.weight"), "wq": g(p + "self_attn.q_proj.weight"), "wk": expand_kv(g(p + "self_attn.k_proj.weight")), "wv": expand_kv(g(p + "self_attn.v_proj.weight")), "wo": g(p + "self_attn.o_proj.weight"), "gq": ones, "gk": ones, "wg": g(p + "mlp.gate_proj.weight"), "wu": g(p + "mlp.up_proj.weight"), "wd": g(p + "mlp.down_proj.weight"), }) norm = g(PFX + "norm.weight") head = g("lm_head.weight") embed = g(PFX + "embed_tokens.weight") d = norm.numel() return DecWeights(d, layers[0]["wg"].shape[0], layers, norm, head, embed)