Files
alzeo/pplx_model.py
T

94 lines
4.0 KiB
Python

#!/usr/bin/env python3
"""pplx-embed v1 0.6B (perplexity-ai/pplx-embed-v1-0.6b, MIT), texts, in plain torch.
Qwen3's 28 layers, 1,024 wide, every token attending to every token of its text, both ways: the mean of the last hidden
states, in the int8 values the model was trained to give (its hyperbolic tangent, in steps of 1/127), of norm 1.
Written for this lane from the model's configuration, its weights' names and shapes, and its published description; the
weights are read, the repository's own Python is never run by this lane. Its vectors are the int8 ones of the repository's
ONNX export (docs/embed-lane.md): vectors-check.py compares a lane with the ones it gave."""
import torch
import torch.nn.functional as F
from torch import nn
from cpu_layers import Linear, RMSNorm, SwiGLU, unit, weights
DIM = 1024
VOCAB, LAYERS, HEADS, PAIRS, FFN, THETA, EPS = 151936, 28, 16, 8, 3072, 1_000_000.0, 1e-6
HEAD = 128 # values a head; PAIRS heads of keys and values, each read by two of queries
class Attention(nn.Module):
def __init__(self):
super().__init__()
self.q_proj = Linear(DIM, HEADS * HEAD, bias=False)
self.k_proj = Linear(DIM, PAIRS * HEAD, bias=False)
self.v_proj = Linear(DIM, PAIRS * HEAD, bias=False)
self.o_proj = Linear(HEADS * HEAD, DIM, bias=False)
self.q_norm, self.k_norm = RMSNorm(HEAD, EPS), RMSNorm(HEAD, EPS)
def forward(self, x, turn, mask):
b, n, _ = x.shape
q = rotated(self.q_norm(self.q_proj(x).view(b, n, HEADS, HEAD)), turn)
k = rotated(self.k_norm(self.k_proj(x).view(b, n, PAIRS, HEAD)), turn)
v = self.v_proj(x).view(b, n, PAIRS, HEAD)
q, k, v = (t.transpose(1, 2) for t in (q, k.repeat_interleave(HEADS // PAIRS, 2), v.repeat_interleave(HEADS // PAIRS, 2)))
out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
return self.o_proj(out.transpose(1, 2).reshape(b, n, HEADS * HEAD))
class Block(nn.Module):
def __init__(self):
super().__init__()
self.input_layernorm, self.self_attn = RMSNorm(DIM, EPS), Attention()
self.post_attention_layernorm, self.mlp = RMSNorm(DIM, EPS), SwiGLU(DIM, FFN)
def forward(self, x, turn, mask):
x = x + self.self_attn(self.input_layernorm(x), turn, mask)
return x + self.mlp(self.post_attention_layernorm(x))
def turns(n, device):
"""The cosines and sines of each place's rotary angles."""
rate = 1.0 / THETA ** (torch.arange(0, HEAD, 2, device=device, dtype=torch.float32) / HEAD)
angle = torch.outer(torch.arange(n, device=device, dtype=torch.float32), rate).view(1, n, 1, HEAD // 2)
return angle.cos(), angle.sin()
def rotated(x, turn):
"""A rotary position: a head's first half and its second, pair by pair, turned by their angle."""
(cos, sin), (a, b) = turn, x.chunk(2, -1)
return torch.cat([a * cos - b * sin, b * cos + a * sin], -1)
def int8(mean):
"""The vector its card publishes: -127 to 127, whole numbers, kept as floats."""
return torch.round(torch.tanh(mean) * 127)
class Pplx(nn.Module):
def __init__(self):
super().__init__()
self.embed_tokens = nn.Embedding(VOCAB, DIM)
self.layers = nn.ModuleList(Block() for _ in range(LAYERS))
self.norm = RMSNorm(DIM, EPS)
@classmethod
def load(cls, folder, dtype=torch.float32):
with torch.device("meta"):
model = cls()
return weights(folder, model, dtype)
@torch.inference_mode()
def texts(self, ids, keep, between=None):
"""ids (batch, length); keep, the same shape, True where a token is not padding. between, when given, is called
after each layer: what a caller has to do meanwhile."""
x, turn = self.embed_tokens(ids), turns(ids.shape[1], ids.device)
mask = None if bool(keep.all()) else keep[:, None, None, :]
for layer in self.layers:
x = layer(x, turn, mask)
if between:
between()
kept = keep[:, :, None].to(x.dtype)
return unit(int8((self.norm(x) * kept).sum(1) / kept.sum(1)))