laya / code /tt_laya /tests /test_host_mk_arena.py
changh95's picture
tt-model push laya (container)
f882f26 verified
Raw History Blame Contribute Delete
3.14 kB
# SPDX-License-Identifier: Apache-2.0
"""Host test (no device): the megakernel's weight streams, tables and decomposition (tt/mk/arena.Emu consumes every
column stream in the TRISC's loop order) reproduce the float32 reference model and the official logits.
python -m pytest tt_laya/tests/test_host_mk_arena.py -q (needs the english checkpoint: LAYA_WEIGHTS_DIR or
assets/laya/ckpt/english; skipped otherwise)
"""
from __future__ import annotations
import json
import os
import numpy as np
import pytest
import torch
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", ".."))
CK = os.environ.get("LAYA_WEIGHTS_DIR") or os.path.join(ROOT, "assets", "laya", "ckpt", "english")
GOLD = os.path.join(os.environ.get("LAYA_GOLDEN_DIR") or os.path.join(ROOT, "assets", "laya", "golden"), "english")
def _have():
return os.path.isfile(os.path.join(CK, "model.safetensors")) and os.path.isdir(GOLD)
@pytest.mark.skipif(not _have(), reason="no checkpoint / goldens on this host")
@pytest.mark.parametrize("case", ["ticket00_readme", "ticket01_triage"])
def test_emulation_matches_reference(case):
torch.set_num_threads(2)
from tt_laya import text as T
from tt_laya import weights as Wt
from tt_laya.reference.model import Reference
from tt_laya.tt.mk import arena as A
from tt_laya.tt.mk import geometry as G
ck = Wt.load_checkpoint("english", root=CK)
tok = T.Tokenizer(os.path.join(ck.path, "tokenizer"))
sd = Wt.load_state_dict(ck)
doc = json.load(open(os.path.join(GOLD, case + ".json")))
z = np.load(os.path.join(GOLD, case + ".npz"))
qs = T.normalise_questions(doc["questions"])
rows = T.build_rows(tok, doc["state"], qs, ck.max_len, ck.head_max_len)
ref = Reference(sd, ck.arch)
geo = G.build(12, 10, G.Model.of(ck.arch))
emu = A.Emu(A.Weights(sd, ck.arch), geo, bf16=False)
lr = [G.LaunchRow(len(r.ids), r.qtype) for r in rows]
w, placed = G.plan_rows(lr, 10, 120, ck.arch.layers, ck.arch.head_layers)
e = torch.zeros(32 * w[G.PL_T], ck.arch.hidden)
tab = sd["encoder.embeddings.tok_embeddings.weight"].float()
for p, r in zip(placed, rows):
e[p.start:p.start + len(r.ids)] = tab[torch.tensor(r.ids)]
h = emu.run(e, [(p.start, len(r.ids), r.qtype) for p, r in zip(placed, rows)])
for i, (p, r) in enumerate(zip(placed, rows)):
b = p.start
sel = [b] + [b + m for m in r.markers]
hs = h[sel]
W = ref.sd
y = torch.nn.functional.layer_norm(hs[1:], (hs.shape[1],), W["scorer.0.weight"], W["scorer.0.bias"])
y = torch.nn.functional.gelu(y @ W["scorer.1.weight"].t() + W["scorer.1.bias"])
logits = (y @ W["scorer.3.weight"].t() + W["scorer.3.bias"])[:, 0]
g = z["logits_fp32"][i, :len(r.markers)]
drift = np.abs(z["logits_bf16"][i, :len(r.markers)] - g).max()
# bf16 weights (the streams) are the only rounding: within the official bf16 drift
assert np.abs(logits.numpy() - g).max() < max(0.02, 1.5 * drift), (i, logits, g, drift)