schift-ocr-1-beta / code /tt_dsocr /tests /test_host_dash.py
changh95's picture
tt-model push schift-ocr-1-beta (container)
ca1a504 verified
Raw History Blame Contribute Delete
6.57 kB
# SPDX-License-Identifier: Apache-2.0
"""Host tests of the Unlimited-OCR-2 DASH pieces of the device path (tt/dash_host.py) against the clean-room
reference (reference/uocr2.py, itself checked against the official model: research/dsocr/golden/
check_uocr_reference.py): the block-bias mask the device expands equals the reference attention; the incremental
decode router (one block summary per step) equals the reference's full recomputation."""
from __future__ import annotations
import math
import os
import sys
import torch
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(os.path.dirname(HERE)))
from tt_dsocr.reference import model as R # noqa: E402
from tt_dsocr.reference import uocr2 as U # noqa: E402
from tt_dsocr.tt import dash_host as DH # noqa: E402
class FakeW:
def __init__(self, seed=0):
g = torch.Generator().manual_seed(seed)
self.t = {}
for l in range(R.NL):
p = R.PFX + f"layers.{l}.self_attn.dash_router."
self.t[p + "head_cls"] = torch.randn(128, generator=g)
self.t[p + "q_norm.weight"] = 0.1 * torch.randn(128, generator=g)
self.t[p + "k_norm.weight"] = 0.1 * torch.randn(128, generator=g)
def get(self, k, cache=True):
return self.t[k]
def prompt_ids(pages=(273, 273), text=5):
ids = [0]
for n in pages:
ids += [U.PAGE_ID] + [U.IMAGE_ID] * n
return ids + [100 + i for i in range(text)]
def test_block_candidates_vectorized_matches_rowwise():
ids = prompt_ids((150, 273, 90))
tok, page, st = U.page_coords(ids)
ip, qp = U.prefill_page_ids(ids, st["n_pages"], st["last_img"])
nblk = -(-len(ids) // 32)
got = U.block_candidates(ip, qp, nblk)
ipb = torch.nn.functional.pad(ip, (0, nblk * 32 - len(ids)), value=-1).view(nblk, 32)
for i in range(len(ids)):
if qp[i] < 0:
ref = torch.ones(nblk, dtype=torch.bool)
else:
c = (ipb == qp[i]).any(-1)
ref = c if bool(c.any()) else torch.ones(nblk, dtype=torch.bool)
assert torch.equal(got[i], ref), i
def test_mask_expansion_equals_reference_attention():
g = torch.Generator().manual_seed(1)
S, H = 300, 3
nblk = -(-S // 32)
iq = torch.randn(S, 128, generator=g)
ik = torch.randn(S, 128, generator=g)
kbar, nonempty = U.block_summaries(ik, torch.randn(128, generator=g))
q_pos = torch.arange(S)
cand = torch.rand(S, nblk, generator=g) > 0.3
sel, bias, valid = U.route(iq, kbar, nonempty, q_pos, cand)
q, k, v = (torch.randn(H, S, 128, generator=g) for _ in range(3))
ref = U.attend(q, k, v, sel, bias, valid, q_pos)
Lb, nbp = 320, 32
B = DH.block_bias(sel, bias, valid, Lb, nbp)
m = DH.mask_from_blocks(B, DH.expansion(nbp, Lb), DH.notlocal(torch.arange(Lb), Lb))[:S, :S]
s = (q @ k.transpose(1, 2)) / math.sqrt(128) + m[None]
got = s.softmax(-1) @ v
assert (got - ref).abs().max() < 1e-5
# rows >= 160 really use the bias (not plain causal attention)
causal = torch.ones(S, S).tril().bool()
plain = ((q @ k.transpose(1, 2)) / math.sqrt(128)).masked_fill(~causal, float("-inf")).softmax(-1) @ v
assert (plain[:, 200:] - ref[:, 200:]).abs().max() > 1e-2
def test_router_prefill_and_incremental_decode_match_reference():
W = FakeW()
ids = prompt_ids((273, 120), text=4)
L = len(ids)
rt = DH.DashRouter(W, max_pos=1024)
rt.begin(ids)
g = torch.Generator().manual_seed(2)
r = torch.randn(L, 256, generator=g)
l = 3
sel, bias, valid = rt.prefill_layer(l, r)
tok, page, st = U.page_coords(ids)
cos, sin = U.rope2d(tok, page)
p = R.PFX + f"layers.{l}.self_attn.dash_router."
iq = U.rotate(U.gemma_rms(r[:, :128], W.get(p + "q_norm.weight")), cos, sin)
ik = U.rotate(U.gemma_rms(r[:, 128:], W.get(p + "k_norm.weight")), cos, sin)
kbar, ne = U.block_summaries(ik, W.get(p + "head_cls"))
ip, qp = U.prefill_page_ids(ids, st["n_pages"], st["last_img"])
s2, b2, v2 = U.route(iq, kbar, ne, torch.arange(L), U.block_candidates(ip, qp, -(-L // 32)))
assert torch.equal(sel, s2) and torch.equal(valid, v2) and torch.allclose(bias, b2)
# decode: the reference decoder's coordinate / allow machinery + full kbar recomputation
ref = U.UocrDecoder.__new__(U.UocrDecoder)
ref.begin(ids)
ik_all = ik.clone()
toks = [U.PAGE_ID] + [500 + i for i in range(70)] + [U.PAGE_ID] + [700 + i for i in range(40)]
for n, t in enumerate(toks):
pos = L + n
cos1, sin1 = rt.step_begin(t, pos)
ref.mcum += int(t == U.PAGE_ID)
tc, pc = U.decode_coord(ref.state, t)
c2, s2_ = U.rope2d(torch.tensor([tc]), torch.tensor([pc]))
assert torch.allclose(cos1, c2) and torch.allclose(sin1, s2_)
rr = torch.randn(1, 256, generator=g)
sel, bias, valid = rt.step_layer(l, rr)
iq1 = U.rotate(U.gemma_rms(rr[:, :128], W.get(p + "q_norm.weight")), c2, s2_)
ik1 = U.rotate(U.gemma_rms(rr[:, 128:], W.get(p + "k_norm.weight")), c2, s2_)
ik_all = torch.cat([ik_all, ik1], 0)
kb, ne = U.block_summaries(ik_all, W.get(p + "head_cls"))
nblk = -(-(pos + 1) // 32)
allow = ref.decode_allow(nblk)
cand = None if allow is None else allow[None, :nblk]
s3, b3, v3 = U.route(iq1, kb, ne, torch.tensor([pos]), cand)
assert torch.equal(valid, v3), n
assert torch.equal(sel[valid], s3[v3]) and torch.allclose(bias, b3, atol=1e-5), n
def test_fast_decode_route_equals_reference():
"""DashRouter.step_layer_fast (numpy, the device decode path) == step_layer (torch, the reference math)."""
W = FakeW(seed=4)
ids = prompt_ids((273, 200), text=3)
L = len(ids)
a, b = DH.DashRouter(W, max_pos=1024), DH.DashRouter(W, max_pos=1024)
g = torch.Generator().manual_seed(6)
for rt in (a, b):
rt.begin(ids)
for l in (0, 5):
r = torch.randn(L, 256, generator=g)
a.prefill_layer(l, r)
b.prefill_layer(l, r)
toks = [U.PAGE_ID] + [300 + i for i in range(50)] + [U.PAGE_ID] + [400 + i for i in range(50)]
for n, t in enumerate(toks):
a.step_begin(t, L + n)
b.step_begin(t, L + n)
for l in (0, 5):
rr = torch.randn(1, 256, generator=g)
sel, bias, valid = a.step_layer(l, rr)
ref = DH.block_bias(sel, bias, valid, 1, a.nb_dec_pad)[0]
got = torch.from_numpy(b.step_layer_fast(l, rr.numpy()))
assert torch.allclose(got, ref, atol=2e-4), (n, l, (got - ref).abs().max())