# SPDX-License-Identifier: Apache-2.0 """Clean-room fp32 CPU reference of google/embeddinggemma-2 (no transformers / sentence-transformers): plain torch ops on the safetensors weights, in the order of transformers 5.24.1 ``modeling_embedding_gemma2.py`` / ``modeling_gemma4.py`` (eager attention). Stages (ARCH.md section 1): text_backbone(inputs_embeds, mask) -> token embeddings [B, n, 768] (final norm + embedding_projection) vision_tower(patches, positions, k) -> soft tokens [n_tok, 768] fp32 (pooled, * sqrt(768)) embed_vision / embed_audio -> [n, 512] (RMSNorm without scale + linear) audio_tower(features, mask) -> [T', 1536], valid mask [T'] pool_normalize(tok, mask) -> mean over real tokens, L2 normalize """ from __future__ import annotations import math from typing import Dict, List, Optional, Tuple from .. import model_spec as S def _torch(): import torch import torch.nn.functional as F return torch, F def rms(x, w=None, eps=S.EPS): torch, _ = _torch() y = x * torch.pow(x.pow(2).mean(-1, keepdim=True) + eps, -0.5) return y * w if w is not None else y def gelu_tanh(x): _, F = _torch() return F.gelu(x, approximate="tanh") def rotate_half(x): torch, _ = _torch() h = x.shape[-1] // 2 return torch.cat((-x[..., h:], x[..., :h]), dim=-1) def rope_cos_sin(positions, dim: int, theta: float): """positions [n] (int) -> cos, sin [n, dim] (HF default rope, rotate_half layout).""" torch, _ = _torch() inv = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim)) f = positions.float()[:, None] * inv[None, :] e = torch.cat((f, f), dim=-1) return e.cos(), e.sin() # ------------------------------------------------------------------------------------------------ text backbone def text_embed(table, ids): """table [V, 512] (any dtype) -> fp32 embeddings * sqrt(512).""" return table[ids].float() * S.EMBED_SCALE def text_masks(mask, n: int): """mask [B, n] (1 = real token) -> additive masks {full, sliding} [B, 1, n, n] fp32.""" torch, _ = _torch() neg = torch.finfo(torch.float32).min key_ok = mask.bool()[:, None, None, :] i = torch.arange(n) band = ((i[:, None] - i[None, :]).abs() <= S.SLIDING_RADIUS)[None, None] full = torch.where(key_ok, 0.0, neg) sliding = torch.where(key_ok & band, 0.0, neg) return {"full": full, "sliding": sliding} def text_backbone(W: Dict, inputs_embeds, mask, keep: Optional[Dict] = None, layers: Optional[int] = None): """inputs_embeds [B, n, 512] fp32, mask [B, n] -> token embeddings [B, n, 768] fp32. ``keep`` (dict) receives 'ple' [B, n, 24, 512] and 'layerXX' [B, n, 512].""" torch, F = _torch() p = "language_model." B, n, _ = inputs_embeds.shape x = inputs_embeds ple = F.linear(x, W[p + "ple.per_layer_model_projection.weight"]) * (S.HIDDEN ** -0.5) ple = rms(ple.reshape(B, n, S.LAYERS, S.PLE_DIM), W[p + "ple.per_layer_projection_norm.weight"]) if keep is not None: keep["ple"] = ple masks = text_masks(mask, n) pos = torch.arange(n) rope = {t: rope_cos_sin(pos, S.HEAD_DIM[t], S.ROPE_THETA[t]) for t in ("sliding", "full")} for l in range(S.LAYERS if layers is None else layers): q_ = f"{p}layers.{l}." t = S.LAYER_TYPES[l] hd, kvh = S.HEAD_DIM[t], S.KV_HEADS[t] r = x h = rms(x, W[q_ + "input_layernorm.weight"]) q = F.linear(h, W[q_ + "self_attn.q_proj.weight"]).view(B, n, S.HEADS, hd).transpose(1, 2) k = F.linear(h, W[q_ + "self_attn.k_proj.weight"]).view(B, n, kvh, hd).transpose(1, 2) v = F.linear(h, W[q_ + "self_attn.v_proj.weight"]).view(B, n, kvh, hd).transpose(1, 2) q = rms(q, W[q_ + "self_attn.q_norm.weight"]) k = rms(k, W[q_ + "self_attn.k_norm.weight"]) v = rms(v) cos, sin = rope[t] q = q * cos + rotate_half(q) * sin k = k * cos + rotate_half(k) * sin rep = S.HEADS // kvh k = k.repeat_interleave(rep, dim=1) v = v.repeat_interleave(rep, dim=1) s = torch.matmul(q, k.transpose(2, 3)) + masks[t] # scaling 1.0 (q/k norms) a = torch.matmul(torch.softmax(s, dim=-1), v).transpose(1, 2).reshape(B, n, S.HEADS * hd) o = F.linear(a, W[q_ + "self_attn.o_proj.weight"]) x = r + rms(o, W[q_ + "post_attention_layernorm.weight"]) r = x h = rms(x, W[q_ + "pre_feedforward_layernorm.weight"]) h = F.linear(gelu_tanh(F.linear(h, W[q_ + "mlp.gate_proj.weight"])) * F.linear(h, W[q_ + "mlp.up_proj.weight"]), W[q_ + "mlp.down_proj.weight"]) x = r + rms(h, W[q_ + "post_feedforward_layernorm.weight"]) r = x g = gelu_tanh(F.linear(x, W[q_ + "ple_block.per_layer_input_gate.weight"])) * ple[:, :, l] g = F.linear(g, W[q_ + "ple_block.per_layer_projection.weight"]) x = r + rms(g, W[q_ + "ple_block.post_per_layer_input_norm.weight"]) x = x * W[q_ + "layer_scalar"] if keep is not None: keep[f"layer{l:02d}"] = x x = rms(x, W[p + "norm.weight"]) if keep is not None: keep["norm"] = x return F.linear(x, W[p + "embedding_projection.weight"]) def pool_normalize(tok, mask): """tok [B, n, 768], mask [B, n] -> (pooled [B, 768], emb [B, 768]) (sentence-transformers mean + Normalize).""" torch, F = _torch() m = mask.float()[..., None] pooled = (tok * m).sum(1) / m.sum(1).clamp(min=1e-9) return pooled, F.normalize(pooled, p=2, dim=-1) def mrl(emb, dim: int, normalize: bool = True): """Matryoshka truncation: keep the leading ``dim`` values, re-normalize.""" _, F = _torch() e = emb[..., :dim] return F.normalize(e, p=2, dim=-1) if normalize else e # ------------------------------------------------------------------------------------------------ embedders def embed_mm(W: Dict, prefix: str, x): """Gemma4MultimodalEmbedder: RMSNorm without scale (eps 1e-6) + linear -> [.., 512].""" _, F = _torch() return F.linear(rms(x), W[prefix + ".embedding_projection.weight"]) # ------------------------------------------------------------------------------------------------ vision tower def vision_rope(positions): """positions [P, 2] (x, y; -1 = padding) -> cos, sin [P, 64] for the axial 2-D rope (H-H-W-W layout).""" torch, _ = _torch() dim = S.V_HEAD_DIM // 2 inv = 1.0 / (S.V_ROPE_THETA ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim)) # 16 f = positions.float()[..., None] * inv # [P, 2, 16] fx, fy = f[:, 0], f[:, 1] c = torch.cat([fx.cos(), fx.cos(), fy.cos(), fy.cos()], dim=-1) s = torch.cat([fx.sin(), fx.sin(), fy.sin(), fy.sin()], dim=-1) return c, s def vision_apply_rope(x, cos, sin): """x [.., P, 64]: rotate the two 32-channel halves independently (apply_multidimensional_rope, ndim 2).""" torch, _ = _torch() h = S.V_HEAD_DIM // 2 a = x[..., :h] * cos[..., :h] + rotate_half(x[..., :h]) * sin[..., :h] b = x[..., h:] * cos[..., h:] + rotate_half(x[..., h:]) * sin[..., h:] return torch.cat([a, b], dim=-1) def vision_encoder(W: Dict, patches, positions, keep: Optional[Dict] = None): """patches [P, 768] in [0, 1] (unpadded or padded), positions [P, 2] (-1 = padding) -> hidden [P, 768].""" torch, F = _torch() p = "vision_tower." pad = (positions == -1).all(-1) x = F.linear(2.0 * (patches - 0.5), W[p + "patch_embedder.input_proj.weight"]) cl = positions.clamp(min=0) tab = W[p + "patch_embedder.position_embedding_table"] pe = tab[0][cl[:, 0]] + tab[1][cl[:, 1]] x = x + torch.where(pad[:, None], 0.0, pe) if keep is not None: keep["patch_embed"] = x P = x.shape[0] cos, sin = vision_rope(positions) add = torch.where(pad[None, None, :], torch.finfo(torch.float32).min, 0.0) # [1, 1, P] for l in range(S.V_LAYERS): q_ = f"{p}encoder.layers.{l}." r = x h = rms(x, W[q_ + "input_layernorm.weight"]) def proj(nm): return F.linear(h, W[q_ + f"self_attn.{nm}.linear.weight"]).view(P, S.V_HEADS, S.V_HEAD_DIM) q = vision_apply_rope(rms(proj("q_proj"), W[q_ + "self_attn.q_norm.weight"]).transpose(0, 1), cos, sin) k = vision_apply_rope(rms(proj("k_proj"), W[q_ + "self_attn.k_norm.weight"]).transpose(0, 1), cos, sin) v = rms(proj("v_proj")).transpose(0, 1) s = torch.matmul(q, k.transpose(1, 2)) + add a = torch.matmul(torch.softmax(s, dim=-1), v).transpose(0, 1).reshape(P, S.V_HIDDEN) x = r + rms(F.linear(a, W[q_ + "self_attn.o_proj.linear.weight"]), W[q_ + "post_attention_layernorm.weight"]) r = x h = rms(x, W[q_ + "pre_feedforward_layernorm.weight"]) h = F.linear(gelu_tanh(F.linear(h, W[q_ + "mlp.gate_proj.linear.weight"])) * F.linear(h, W[q_ + "mlp.up_proj.linear.weight"]), W[q_ + "mlp.down_proj.linear.weight"]) x = r + rms(h, W[q_ + "post_feedforward_layernorm.weight"]) if keep is not None: keep[f"layer{l:02d}"] = x return x def vision_pool(hidden, positions, n_tokens_max: int): """3x3 average pooling by patch position, * sqrt(768); strips empty output slots -> [n_tok, 768] fp32.""" torch, F = _torch() pad = (positions == -1).all(-1) h = hidden.masked_fill(pad[:, None], 0.0) k = S.V_POOL cl = positions.clamp(min=0) max_x = cl[:, 0].max() + 1 idx = torch.div(cl, k, rounding_mode="floor") idx = idx[:, 0] + (max_x // k) * idx[:, 1] w = F.one_hot(idx.long(), n_tokens_max).float() / (k * k) # [P, L] out = w.t() @ h # [L, 768] keep = ~(w == 0).all(0) return out[keep] * math.sqrt(S.V_HIDDEN) def vision_tower(W: Dict, patches, positions, max_soft_tokens: int, keep: Optional[Dict] = None): """One image / frame -> soft tokens [n_tok, 768] fp32 (Gemma4VisionModel.forward, standardize off).""" hid = vision_encoder(W, patches, positions, keep) return vision_pool(hid, positions, max_soft_tokens) # ------------------------------------------------------------------------------------------------ audio tower def _clip_lin(W, name, x, bias=False): torch, F = _torch() x = torch.clamp(x, W[name + ".input_min"], W[name + ".input_max"]) y = F.linear(x, W[name + ".linear.weight"]) return torch.clamp(y, W[name + ".output_min"], W[name + ".output_max"]) def audio_rel_pos(device=None): """Sinusoidal relative positions for d = 12 .. 0 -> [13, 1024] ([sin..., cos...]).""" torch, _ = _torch() n = S.A_HIDDEN // 2 inc = math.log(10000.0) / max(n - 1, 1) inv = torch.exp(torch.arange(n, dtype=torch.float32) * -inc) pos = torch.arange((S.A_CHUNK + S.A_LEFT + S.A_RIGHT) // 2, -1, -1, dtype=torch.float32)[:, None] st = pos * inv[None, :] return torch.cat([st.sin(), st.cos()], dim=-1) def audio_subsample(W: Dict, feats, mask): """feats [T, 128] (masked), mask [T] bool -> x [T', 1024], mask' [T'].""" torch, F = _torch() p = "audio_tower.subsample_conv_projection." x = feats[None, None] # [1, 1, T, 128] m = mask for i, ch in enumerate(S.A_SUB_CH): x = x * m[None, None, :, None].float() x = F.conv2d(x, W[p + f"layer{i}.conv.weight"], stride=2, padding=1) x = F.layer_norm(x.permute(0, 2, 3, 1), (ch,), W[p + f"layer{i}.norm.weight"], None, S.EPS) x = F.relu(x).permute(0, 3, 1, 2) m = m[::2] _, C, T, Fq = x.shape x = x.permute(0, 2, 3, 1).reshape(T, Fq * C) return F.linear(x, W[p + "input_proj_linear.weight"]), m[:T] def audio_attention(W: Dict, q_, x, valid): """Chunked local attention as a dense banded form: logits(i, j) = q_i . (k_j + R(i - j)) for 0 <= i - j < 12.""" torch, F = _torch() T = x.shape[0] H, D = S.A_HEADS, S.A_HEAD_DIM q = _clip_lin(W, q_ + "q_proj", x).view(T, H, D) k = _clip_lin(W, q_ + "k_proj", x).view(T, H, D) v = _clip_lin(W, q_ + "v_proj", x).view(T, H, D) q = q * ((D ** -0.5) / math.log(2)) * F.softplus(W[q_ + "per_dim_scale"]) k = k * (math.log(1 + math.e) / math.log(2)) R = F.linear(audio_rel_pos(), W[q_ + "relative_k_proj.weight"]).view(-1, H, D) # row p <-> d = 12 - p R = R.flip(0) # row d s = torch.einsum("ihd,jhd->hij", q, k) i = torch.arange(T) d = i[:, None] - i[None, :] # [T, T] dc = d.clamp(0, S.A_WINDOW) qr = torch.einsum("ihd,phd->hip", q, R) # [H, T, 13] s = s + torch.gather(qr, 2, dc[None].expand(H, T, T)) s = torch.tanh(s / S.A_LOGIT_CAP) * S.A_LOGIT_CAP ok = (d >= 0) & (d < S.A_WINDOW) & valid[None, :] s = torch.where(ok[None], s, torch.tensor(S.A_INVALID)) pr = torch.softmax(s, dim=-1) a = torch.einsum("hij,jhd->ihd", pr, v).reshape(T, H * D) return _clip_lin(W, q_ + "post", a) def audio_ffw(W, q_, x): torch, F = _torch() r = x h = rms(x, W[q_ + "pre_layer_norm.weight"]) h = _clip_lin(W, q_ + "ffw_layer_2", F.silu(_clip_lin(W, q_ + "ffw_layer_1", h))) return r + rms(h, W[q_ + "post_layer_norm.weight"]) * S.A_RESIDUAL_W def audio_lconv(W, q_, x): torch, F = _torch() r = x h = rms(x, W[q_ + "pre_layer_norm.weight"]) h = F.glu(_clip_lin(W, q_ + "linear_start", h), dim=-1) # [T, 1024] h = F.conv1d(F.pad(h.t()[None], (S.A_CONV_K - 1, 0)), W[q_ + "depthwise_conv1d.weight"], groups=S.A_HIDDEN)[0].t() h = F.silu(rms(h, W[q_ + "conv_norm.weight"])) return r + _clip_lin(W, q_ + "linear_end", h) def audio_tower(W: Dict, feats, mask, keep: Optional[Dict] = None): """feats [T, 128] fp32 log-mel (zero where masked), mask [T] bool -> (out [T', 1536], valid [T']).""" torch, F = _torch() x, valid = audio_subsample(W, feats, mask) if keep is not None: keep["subsample"] = x for l in range(S.A_LAYERS): q_ = f"audio_tower.layers.{l}." x = audio_ffw(W, q_ + "feed_forward1.", x) r = x h = rms(x, W[q_ + "norm_pre_attn.weight"]) h = audio_attention(W, q_ + "self_attn.", h, valid) x = r + rms(h, W[q_ + "norm_post_attn.weight"]) x = audio_lconv(W, q_ + "lconv1d.", x) x = audio_ffw(W, q_ + "feed_forward2.", x) x = rms(x, W[q_ + "norm_out.weight"]) if keep is not None: keep[f"layer{l:02d}"] = x out = F.linear(x, W["audio_tower.output_proj.weight"], W["audio_tower.output_proj.bias"]) return out, valid # ------------------------------------------------------------------------------------------------ full model def build_inputs_embeds(W: Dict, table, ids, mm_rows: List[Tuple[int, "torch.Tensor"]]): # noqa: F821 """ids [n] -> inputs_embeds [n, 512]: token embeddings (* sqrt(512)) with multimodal rows written over the placeholder positions. ``mm_rows``: (start position, [m, 512] rows) in order.""" torch, _ = _torch() ids = torch.as_tensor(ids, dtype=torch.long) is_mm = (ids == S.IMAGE_TOKEN_ID) | (ids == S.AUDIO_TOKEN_ID) | (ids == S.VIDEO_TOKEN_ID) e = text_embed(table, torch.where(is_mm, S.PAD_ID, ids)) for start, rows in mm_rows: e[start: start + rows.shape[0]] = rows return e