File size: 2,566 Bytes
dadc4db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""RoPE tables fed to the ONNX graphs. The browser computes the same values in JS.

All angles: float64 product, rounded to float32, then sin/cos rounded to float32.
"""
from __future__ import annotations

import numpy as np

F32 = np.float32


def _axis_freqs(dim: int, theta: float) -> np.ndarray:
    return 1.0 / (theta ** (np.arange(0, dim, 2, dtype=np.float64) / float(dim)))


def dflow_rows(pos: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """``pos`` [N, 3] float64 -> (sin, cos) [N, 128] float32, adjacent-pair layout."""
    sins, coses = [], []
    for axis, dim in enumerate((32, 48, 48)):
        ang = np.outer(pos[:, axis], _axis_freqs(dim, 10000.0)).astype(F32)
        sins.append(np.repeat(np.sin(ang), 2, axis=1))
        coses.append(np.repeat(np.cos(ang), 2, axis=1))
    return np.concatenate(sins, 1).astype(F32), np.concatenate(coses, 1).astype(F32)


def text_positions(length: int) -> np.ndarray:
    p = np.zeros((length, 3), np.float64)
    p[:, 0] = np.arange(1, length + 1)
    return p


def joint_positions(text_length: int, gh: int, gw: int) -> np.ndarray:
    idx = np.arange(gh * gw)
    row, col = idx // gw, idx % gw
    img = np.stack([np.full(gh * gw, text_length + 1.0), row - (gh - 1) / 2, col - (gw - 1) / 2], 1)
    return np.concatenate([img.astype(np.float64), text_positions(text_length)], 0)


def gemma_tables(length: int) -> dict[str, np.ndarray]:
    """Gemma encoder RoPE, [L, 1, 256] cos/sin for sliding and full layers."""
    out = {}
    exps = np.arange(0, 256, 2, dtype=np.int64).astype(F32)
    for name, theta, factor in (("s", 10000.0, 1.0), ("f", 1_000_000.0, 8.0)):
        inv = (F32(1.0) / (F32(theta) ** (exps / F32(256.0)))).astype(F32) / F32(factor)
        freqs = np.arange(length, dtype=F32)[:, None] * inv[None, :]
        emb = np.concatenate([freqs, freqs], 1).astype(F32)
        out[f"g_cos_{name}"] = np.cos(emb)[:, None, :].astype(F32)
        out[f"g_sin_{name}"] = np.sin(emb)[:, None, :].astype(F32)
    return out


def vae_tables(gh: int, gw: int) -> tuple[np.ndarray, np.ndarray]:
    """dinac3 decoder axial RoPE (head_dim 64): (sin, cos) [gh*gw, 64]."""
    periods = (F32(10000.0) ** (F32(2.0) * np.arange(16, dtype=F32) / F32(32))).astype(F32)
    rr, cc = np.meshgrid(np.arange(gh, dtype=F32), np.arange(gw, dtype=F32), indexing="ij")
    coords = np.stack([rr, cc], -1).reshape(-1, 2)
    ang = (coords[:, :, None] / periods[None, None, :]).astype(F32)
    ang = np.repeat(ang, 2, axis=-1).reshape(gh * gw, 64)
    return np.sin(ang).astype(F32), np.cos(ang).astype(F32)