File size: 15,542 Bytes
5c33f00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# 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