Files
alzeo/cpu_layers.py
T

73 lines
2.8 KiB
Python

#!/usr/bin/env python3
"""What the CPU embedding models are made of, in plain torch: the matrix product on the cores' bf16 instructions, the norm, the
feed-forward block and the vector of norm 1 (clipstral_model.py, pplx_model.py).
On the ten Cortex-A725 cores of a GB10 a product of bf16 matrices takes a third to a half of a float32 one's time. What it
reads is rounded on the way in and its sums stay in float32, so the vectors are the float32 ones to a cosine of 0.9999 or more:
both models' pages have it, measured."""
import torch
import torch.nn.functional as F
from torch import nn
MATMUL = "ieee" # how Linear multiplies: "ieee", in float32, or "bf16", on the cores' bf16 instructions
class Linear(nn.Linear):
"""A matrix product, computed as MATMUL says: on the cores' bf16 instructions its float32s are rounded to them on the way
in, twice as fast, and everything else stays in float32. oneDNN's own switch (DNNL_DEFAULT_FPMATH_MODE=BF16) rounds the
convolutions too, and moves the vectors of images (docs/clipstral-lane.md has both, measured)."""
def forward(self, x):
precision = torch.backends.mkldnn.matmul
precision.fp32_precision = MATMUL
try:
return F.linear(x, self.weight)
finally:
precision.fp32_precision = "ieee"
class RMSNorm(nn.Module):
"""Root-mean-square norm, computed in float32 and scaled in the layer's own type."""
def __init__(self, width, eps):
super().__init__()
self.weight = nn.Parameter(torch.ones(width))
self.eps = eps
def forward(self, x):
return F.rms_norm(x.float(), (x.shape[-1],), eps=self.eps).type_as(x) * self.weight
class SwiGLU(nn.Module):
def __init__(self, width, ffn):
super().__init__()
self.gate_proj = Linear(width, ffn, bias=False)
self.up_proj = Linear(width, ffn, bias=False)
self.down_proj = Linear(ffn, width, bias=False)
def forward(self, x):
return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
def unit(v):
"""Norm 1, in float32 whatever the model's type."""
return F.normalize(v.float(), p=2, dim=-1)
def weights(folder, model, dtype=torch.float32):
"""The model, its tensors read from folder/model.safetensors (those it has no place for are left there)."""
from pathlib import Path
from safetensors import safe_open
state = {}
with safe_open(str(Path(folder) / "model.safetensors"), framework="pt") as f:
want = set(model.state_dict())
for name in f.keys():
if name in want:
state[name] = f.get_tensor(name).to(dtype)
missing = want - set(state)
if missing:
raise ValueError(f"model.safetensors lacks {sorted(missing)[:3]} ({len(missing)} of its tensors): not this model")
model.load_state_dict(state, assign=True)
return model.eval()