# SPDX-License-Identifier: Apache-2.0 """Float32 CPU reference of the laya classic decision model (ModernBERT encoder + decision head), written from the architecture for this port: the oracle of the device engines and the ``cpu`` engine of the server. Inputs per row (one row = one (state, question) sequence): token ids, valid length, [MASK] marker positions, the question type. Rows may have different lengths; each row is computed on its own valid tokens only (no padding: mathematically what the official padded batch computes for the valid positions). """ from __future__ import annotations import math from typing import Dict, List, Optional, Sequence, Tuple import torch import torch.nn.functional as F from ..weights import Arch def rope_tables(n: int, head_dim: int, theta: float) -> Tuple[torch.Tensor, torch.Tensor]: inv = 1.0 / (theta ** (torch.arange(0, head_dim, 2, dtype=torch.float32) / head_dim)) fr = torch.arange(n, dtype=torch.float32)[:, None] * inv[None, :] emb = torch.cat([fr, fr], dim=-1) return emb.cos(), emb.sin() def rotate(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: h = x.shape[-1] // 2 rot = torch.cat([-x[..., h:], x[..., :h]], dim=-1) return x * cos + rot * sin def ln(x, w, b=None, eps=1e-5): return F.layer_norm(x, (x.shape[-1],), w, b, eps) class Reference: def __init__(self, sd: Dict[str, torch.Tensor], arch: Arch, keep: bool = False): self.a = arch self.sd = {k: v.float() for k, v in sd.items()} self.keep = keep # record intermediates (debugging / per-layer checks) self.inter: Dict[str, torch.Tensor] = {} self._rope: Dict[Tuple[int, float], Tuple[torch.Tensor, torch.Tensor]] = {} def _tables(self, n: int, theta: float): key = (n, theta) if key not in self._rope: self._rope[key] = rope_tables(n, self.a.head_dim, theta) return self._rope[key] # ------------------------------------------------------------------ encoder (one row) def embed(self, ids: torch.Tensor) -> torch.Tensor: W = self.sd return ln(W["encoder.embeddings.tok_embeddings.weight"][ids], W["encoder.embeddings.norm.weight"], eps=self.a.norm_eps) def attention(self, x: torch.Tensor, l: int) -> torch.Tensor: a, W, p = self.a, self.sd, "encoder.layers.%d." % l n, H, hd = x.shape[0], a.heads, a.head_dim qkv = x @ W[p + "attn.Wqkv.weight"].t() q, k, v = qkv.view(n, 3, H, hd).unbind(1) # [n, H, hd] theta = a.theta_global if a.is_global(l) else a.theta_local cos, sin = self._tables(n, theta) q, k = rotate(q, cos[:, None], sin[:, None]), rotate(k, cos[:, None], sin[:, None]) s = torch.einsum("qhd,khd->hqk", q, k) / math.sqrt(hd) if not a.is_global(l): i = torch.arange(n) s = s.masked_fill(((i[:, None] - i[None, :]).abs() > a.window)[None], float("-inf")) ctx = torch.einsum("hqk,khd->qhd", torch.softmax(s, -1), v).reshape(n, H * hd) return ctx @ W[p + "attn.Wo.weight"].t() def layer(self, x: torch.Tensor, l: int) -> torch.Tensor: W, p, eps = self.sd, "encoder.layers.%d." % l, self.a.norm_eps y = x if l == 0 else ln(x, W[p + "attn_norm.weight"], eps=eps) x = x + self.attention(y, l) g = ln(x, W[p + "mlp_norm.weight"], eps=eps) @ W[p + "mlp.Wi.weight"].t() u, gate = g.chunk(2, dim=-1) return x + (F.gelu(u) * gate) @ W[p + "mlp.Wo.weight"].t() def encoder(self, ids: torch.Tensor) -> torch.Tensor: x = self.embed(ids) if self.keep: self.inter["emb"] = x for l in range(self.a.layers): x = self.layer(x, l) if self.keep: self.inter["layer%02d" % l] = x x = ln(x, self.sd["encoder.final_norm.weight"], eps=self.a.norm_eps) if self.keep: self.inter["final_norm"] = x return x # ------------------------------------------------------------------ decision head (one row) def head_layer(self, h: torch.Tensor, i: int, rows: Optional[torch.Tensor] = None) -> torch.Tensor: """nn.TransformerEncoderLayer (norm_first, ReLU, biases); ``rows``: compute only these query rows.""" W, p, d, H = self.sd, "head.layers.%d." % i, self.a.hidden, self.a.heads hd = d // H a = ln(h, W[p + "norm1.weight"], W[p + "norm1.bias"]) wi, bi = W[p + "self_attn.in_proj_weight"], W[p + "self_attn.in_proj_bias"] qx = a if rows is None else a[rows] hq = h if rows is None else h[rows] q = qx @ wi[:d].t() + bi[:d] kv = a @ wi[d:].t() + bi[d:] k, v = kv.chunk(2, dim=-1) n, m = q.shape[0], k.shape[0] s = torch.einsum("qhd,khd->hqk", q.view(n, H, hd), k.view(m, H, hd)) / math.sqrt(hd) ctx = torch.einsum("hqk,khd->qhd", torch.softmax(s, -1), v.view(m, H, hd)).reshape(n, d) x = hq + ctx @ W[p + "self_attn.out_proj.weight"].t() + W[p + "self_attn.out_proj.bias"] f = torch.relu(ln(x, W[p + "norm2.weight"], W[p + "norm2.bias"]) @ W[p + "linear1.weight"].t() + W[p + "linear1.bias"]) return x + f @ W[p + "linear2.weight"].t() + W[p + "linear2.bias"] def head(self, h: torch.Tensor, qtype: int, markers: Sequence[int]) -> Tuple[torch.Tensor, torch.Tensor]: W = self.sd h = h + W["type_emb.weight"][qtype] nl = self.a.head_layers sel = torch.tensor([0] + list(markers), dtype=torch.long) for i in range(nl): last = i == nl - 1 h = self.head_layer(h, i, rows=sel if last else None) if self.keep: self.inter["head%d" % i] = h pooled, m = h[0], h[1:] y = ln(m, W["scorer.0.weight"], W["scorer.0.bias"]) @ W["scorer.1.weight"].t() + W["scorer.1.bias"] logits = (F.gelu(y) @ W["scorer.3.weight"].t() + W["scorer.3.bias"])[:, 0] return logits, self.act_head(pooled, logits) def act_head(self, pooled: torch.Tensor, logits: torch.Tensor) -> torch.Tensor: W = self.sd p = torch.softmax(logits, -1) K = logits.shape[0] k = float(max(K, 2)) ent = -(p * torch.log(p.clamp_min(1e-9))).sum() / math.log(k) top = torch.topk(p, 2).values if K >= 2 else torch.cat([p, torch.zeros(1)]) feats = torch.stack([top[0], top[0] - top[1], ent, torch.tensor(k / 255.0)]) z = torch.cat([pooled, feats]) z = F.gelu(z @ W["act_head.0.weight"].t() + W["act_head.0.bias"]) return z @ W["act_head.2.weight"].t() + W["act_head.2.bias"] # ------------------------------------------------------------------ rows @torch.no_grad() def run_rows(self, rows) -> Tuple[List[torch.Tensor], List[torch.Tensor]]: """rows: text.Row list -> (raw logits per row [K], act probabilities per row [n_act]).""" out_l, out_a = [], [] for r in rows: h = self.encoder(torch.tensor(r.ids, dtype=torch.long)) logits, act = self.head(h, r.qtype, r.markers) out_l.append(logits) out_a.append(torch.softmax(act, -1)) return out_l, out_a