all-MiniLM-L6-v2 / code /tt_minilm /tests /mk_protocol_sim.py
changh95's picture
tt-model push all-minilm-l6-v2 (container)
1e8fbed verified
Raw History Blame Contribute Delete
18.5 kB
# SPDX-License-Identifier: Apache-2.0
"""Host model of the megakernel's synchronization protocol (no device, no data): the three RISC schedules of
``tt/mk/kernels/mm_{brisc,ncrisc,trisc}.cpp`` as Python generators over the same plan, run under randomized
interleavings with delayed NoC deliveries (in order per source / destination pair: linked multicasts and the write
barrier before every counter increment). It checks that every wait is eventually satisfied (no deadlock) and that
every landing tile the TRISC consumes carries the tag (round) the consumer expects (no WAR overwrite, no stale read).
Keep in lock-step with the kernels (each generator names the kernel it mirrors). It found the shared-in0-buffer race
of the first design (an attention output overwriting x tiles a slower column had not used yet)."""
from __future__ import annotations
import random
from collections import defaultdict, deque
from typing import List
from ..tt.mk import program as P
D = P.D
C = D["C"]
MAXK = D["MAXK"]
PP_T = D["PP_T"]
CAP = {D["CB_AX0"]: 6, D["CB_AX1"]: 6, D["CB_AC0"]: 6, D["CB_AC1"]: 6, D["CB_AH0"]: 6, D["CB_AH1"]: 6,
D["CB_F0"]: 24, D["CB_F1"]: 24, D["CB_PP"]: PP_T, D["CB_KV"]: 4 * MAXK, D["CB_STL"]: C,
D["CB_POOLL"]: D["POOLL_T"], D["CB_E"]: 1, D["CB_OB"]: 4, D["CB_PO"]: 4, D["CB_KVO"]: 2, D["CB_STO"]: 1,
D["CB_TOK"]: 1, D["CB_DONE"]: 1, D["CB_POUT"]: 1}
KIND_CB = {"x": ("CB_AX0", "CB_AX1"), "ctx": ("CB_AC0", "CB_AC1"), "h": ("CB_AH0", "CB_AH1"), "f": ("CB_F0", "CB_F1")}
PP_OFF = {"qkv": (D["PP_QKV"], 3), "o": (D["PP_O"], 1), "w1": (D["PP_W1"], 4), "w2": (D["PP_W2"], 1)}
def kcb(kind, f):
return D[KIND_CB[kind][f]]
class Deadlock(RuntimeError):
pass
class Stale(RuntimeError):
pass
def view_of(words, ci, g, h, G):
"""mm_plan.hpp view_of."""
def slot(s):
base = D["PL_CHUNK"] + ci * D["PL_CSTRIDE"]
used = (int(words[base]) >> s) & 1
return {"used": bool(used), "id": int(words[base + 1 + 4 * s]), "seq": int(words[base + 2 + 4 * s]),
"pos": int(words[base + 3 + 4 * s]), "nval": int(words[base + 4 + 4 * s])}
sf, sp = h * G + g, (1 - h) * G + g
v = {"fin": slot(sf), "par": slot(sp), "nk": 0, "mask_n": 32, "kv_rows": 0}
if v["fin"]["used"]:
for s in range(2 * G):
o = slot(s)
if o["used"] and o["seq"] == v["fin"]["seq"]:
v["kv_rows"] |= 1 << (2 * (s % G) + s // G)
b = v["fin"]["seq"]
v["nk"] = int(words[D["PL_SEQ"] + 2 * b + 1])
v["mask_n"] = int(words[D["PL_SEQ"] + 2 * b]) - 32 * (v["nk"] - 1)
return v
class Sim:
def __init__(self, lengths: List[int], G: int = 5, nlayer: int = 6, seed: int = 0, max_delay: int = 6,
uni: bool = False):
self.uni = uni # MM_UNI: row all-gathers as unicast fan-out (+1 per sender word) instead of multicast sets
self.G, self.R = G, 2 * G
self.plan = P.build_plan(lengths, G, 0, 0, nlayer=nlayer)
self.w = self.plan.words
self.nl = nlayer
self.rng = random.Random(seed)
self.max_delay = max_delay
self.cores = [(x, y) for y in range(self.R) for x in range(C)]
self.rcv = defaultdict(int)
self.ack = defaultdict(int)
self.sync = defaultdict(int)
self.tag = {}
self.order = defaultdict(deque)
# ------------------------------------------------------------------ NoC
def send(self, src, dst, actions):
self.order[(src, dst)].append([self.rng.randint(0, self.max_delay), actions])
def deliver(self):
for q in self.order.values():
if q:
q[0][0] -= 1
if q[0][0] <= 0:
for act in q.popleft()[1]:
act()
def pending(self):
return any(self.order.values())
def setmax(self, d, w, v):
self.sync[(d, w)] = max(self.sync[(d, w)], v)
def inc(self, d, w):
self.sync[(d, w)] += 1
@staticmethod
def _space(cb, tiles):
# CB_POOLL is a view of CB_F0's memory: one tag space (fp32 tile t = bf16 tiles 2t, 2t + 1)
if cb == D["CB_POOLL"]:
return D["CB_F0"], [u for t in tiles for u in (2 * t, 2 * t + 1)]
return cb, list(tiles)
def write_tags(self, d, cb, tiles, tag):
cb, tiles = self._space(cb, tiles)
for t in tiles:
self.tag[(d, cb, t)] = tag
# ------------------------------------------------------------------ helpers
def wait_front(self, core, cb, n):
return lambda: self.rcv[(core, cb)] - self.ack[(core, cb)] >= n
def room(self, core, cb, n):
return lambda: CAP[cb] - (self.rcv[(core, cb)] - self.ack[(core, cb)]) >= n
def check(self, core, cb, tiles, want, what):
cb, tiles = self._space(cb, tiles)
for t in tiles:
got = self.tag.get((core, cb, t))
if got != want:
raise Stale(f"{core} {what}: CB {cb} tile {t} holds {got}, expected {want}")
def landed(self, core, cb, n):
yield self.room(core, cb, n)
self.rcv[(core, cb)] += n
# ------------------------------------------------------------------ BRISC (mm_brisc.cpp)
def brisc(self, core):
x, y = core
g, h, G = y // 2, y % 2, self.G
st = {"in0": 0, "st": 0, "pp": 0, "kv": [0, 0], "ein": [0, 0], "est": 0}
def land_in0(f, kind):
if self.uni:
st["ein"][f] += 1
want = st["ein"][f]
else:
want = st["in0"]
for c in range(6 * h, 6 * h + 6):
yield lambda c=c, want=want: self.sync[(core, D["W_IN0"] + f * C + c)] >= want
yield from self.landed(core, kcb(kind, f), 24 if kind == "f" else 6)
def land_pp():
st["pp"] += 1
yield lambda: self.sync[(core, D["W_PP"])] >= st["pp"]
yield from self.landed(core, D["CB_PP"], PP_T)
def land_stats():
if self.uni:
st["est"] += 1
want = st["est"]
else:
want = st["st"]
for c in range(C):
yield lambda c=c, want=want: self.sync[(core, D["W_ST"] + c)] >= want
yield from self.landed(core, D["CB_STL"], C)
for ci in range(self.plan.nchunk):
v = view_of(self.w, ci, g, h, G)
fin, par = v["fin"]["used"], v["par"]["used"]
hf, pf = h, 1 - h
if fin:
yield from self.landed(core, D["CB_E"], 1)
st["st"] += 1
if fin:
yield from land_stats()
st["in0"] += 1
for l in range(self.nl):
last = l + 1 == self.nl
if par:
yield from land_in0(pf, "x")
if fin:
yield from land_in0(hf, "x")
yield from land_pp()
st["kv"][l & 1] += v["nk"]
yield lambda l=l: self.sync[(core, D["W_KV0"] + (l & 1))] >= st["kv"][l & 1]
yield from self.landed(core, D["CB_KV"], 2 * MAXK)
st["in0"] += 1
if par:
yield from land_in0(pf, "ctx")
st["st"] += 1
if fin:
yield from land_in0(hf, "ctx")
yield from land_pp()
yield from land_stats()
st["in0"] += 1
if par:
yield from land_in0(pf, "h")
if fin:
yield from land_in0(hf, "h")
yield from land_pp()
st["in0"] += 1
if par:
yield from land_in0(pf, "f")
st["st"] += 1
if fin:
yield from land_in0(hf, "f")
yield from land_pp()
yield from land_stats()
if not last:
st["in0"] += 1
if fin:
yield self.wait_front(core, D["CB_TOK"], 1)
self.ack[(core, D["CB_TOK"])] += 1
if y == 0:
yield lambda: self.sync[(core, D["W_POOL"])] >= self.R - 1
yield from self.landed(core, D["CB_POOLL"], D["POOLL_T"])
yield self.wait_front(core, D["CB_POUT"], 1)
self.ack[(core, D["CB_POUT"])] += 1
# ------------------------------------------------------------------ NCRISC (mm_ncrisc.cpp)
def ncrisc(self, core):
x, y = core
g, h, G = y // 2, y % 2, self.G
st = {"in0": 0, "st": 0, "bar": 0}
def mcast(dests, cb, tiles, flag, val, tag):
for d in dests:
if self.uni: # unicast write, write barrier, +1
self.send(core, d, [lambda d=d: self.write_tags(d, cb, tiles, tag),
lambda d=d: self.inc(d, flag)])
else: # linked multicast, flag := round
self.send(core, d, [lambda d=d: self.write_tags(d, cb, tiles, tag),
lambda d=d: self.setmax(d, flag, val)])
def send_in0(kind, tag):
yield self.wait_front(core, D["CB_OB"], 4)
tr = 2 * g + x // 6
n = 4 if kind == "f" else 1
tiles = [(x % 6) * n + j for j in range(n)]
mcast([(xx, tr) for xx in range(C)], kcb(kind, h), tiles, D["W_IN0"] + h * C + x, st["in0"], tag)
self.ack[(core, D["CB_OB"])] += 4
def send_pp(kind, tag):
yield self.wait_front(core, D["CB_PO"], 4)
d = (x, 2 * g + 1 - h)
off, nj = PP_OFF[kind]
self.send(core, d, [lambda: self.write_tags(d, D["CB_PP"], range(off, off + nj), tag),
lambda: self.inc(d, D["W_PP"])])
self.ack[(core, D["CB_PO"])] += 4
def send_kv(v, l, tag):
yield self.wait_front(core, D["CB_KVO"], 2)
off = (l & 1) * 2 * MAXK + 2 * v["fin"]["pos"]
for r in range(self.R):
if v["kv_rows"] >> r & 1:
d = (x, r)
self.send(core, d, [lambda d=d: self.write_tags(d, D["CB_KV"], [off, off + 1], tag),
lambda d=d: self.inc(d, D["W_KV0"] + (l & 1))])
self.ack[(core, D["CB_KVO"])] += 2
def send_stats(tag):
yield self.wait_front(core, D["CB_STO"], 1)
mcast([(xx, y) for xx in range(C)], D["CB_STL"], [x], D["W_ST"] + x, st["st"], tag)
self.ack[(core, D["CB_STO"])] += 1
def barrier():
st["bar"] += 1
hub = (0, 0)
self.send(core, hub, [lambda: self.inc(hub, D["W_BCNT"])])
if core == hub:
yield lambda: self.sync[(hub, D["W_BCNT"])] >= st["bar"] * len(self.cores)
val = st["bar"]
for d in self.cores:
self.send(core, d, [lambda d=d: self.setmax(d, D["W_BAR"], val)])
yield lambda: self.sync[(core, D["W_BAR"])] >= st["bar"]
for ci in range(self.plan.nchunk):
if ci > 0:
yield from barrier()
v = view_of(self.w, ci, g, h, G)
fin, par = v["fin"]["used"], v["par"]["used"]
st["st"] += 1
if fin:
yield from send_stats(("st", ci, -1, 0))
st["in0"] += 1
if fin:
yield from send_in0("x", ("in0", ci, 0, "x"))
for l in range(self.nl):
last = l + 1 == self.nl
if par:
yield from send_pp("qkv", ("pp", ci, l, "qkv"))
if fin:
yield from send_kv(v, l, ("kv", ci, l))
st["in0"] += 1
if fin:
yield from send_in0("ctx", ("in0", ci, l, "ctx"))
if par:
yield from send_pp("o", ("pp", ci, l, "o"))
st["st"] += 1
if fin:
yield from send_stats(("st", ci, l, 1))
st["in0"] += 1
if fin:
yield from send_in0("h", ("in0", ci, l, "h"))
if par:
yield from send_pp("w1", ("pp", ci, l, "w1"))
st["in0"] += 1
if fin:
yield from send_in0("f", ("in0", ci, l, "f"))
if par:
yield from send_pp("w2", ("pp", ci, l, "w2"))
st["st"] += 1
if fin:
yield from send_stats(("st", ci, l, 2))
if not last:
st["in0"] += 1
if fin:
yield from send_in0("x", ("in0", ci, l + 1, "x"))
yield self.wait_front(core, D["CB_DONE"], 1)
self.ack[(core, D["CB_DONE"])] += 1
if y == 0 and self.R > 1:
for yy in range(1, self.R):
d = (x, yy)
self.send(core, d, [lambda d=d: self.setmax(d, D["W_PDONE"], 1)])
if y != 0:
yield lambda: self.sync[(core, D["W_PDONE"])] >= 1
yield self.wait_front(core, D["CB_POUT"], 1)
d = (x, 0)
self.send(core, d, [lambda: self.write_tags(d, D["CB_POOLL"], [y], ("pool", y)),
lambda: self.inc(d, D["W_POOL"])])
self.ack[(core, D["CB_POUT"])] += 1
# ------------------------------------------------------------------ TRISC (mm_trisc.cpp)
def trisc(self, core):
x, y = core
g, h, G = y // 2, y % 2, self.G
def consume_in0(kind, f, ci, l):
cb = kcb(kind, f)
n = 24 if kind == "f" else 6
yield self.wait_front(core, cb, n)
self.check(core, cb, range(n), ("in0", ci, l, kind), f"in0 {kind} l{l}")
self.ack[(core, cb)] += n
def produce(cb, n):
yield self.room(core, cb, n)
self.rcv[(core, cb)] += n
def final_pp(ci, l, kind):
yield self.wait_front(core, D["CB_PP"], PP_T)
off, nj = PP_OFF[kind]
self.check(core, D["CB_PP"], range(off, off + nj), ("pp", ci, l, kind), f"pp {kind}")
self.ack[(core, D["CB_PP"])] += PP_T
def ln(ci, l, k):
yield from produce(D["CB_STO"], 1)
yield self.wait_front(core, D["CB_STL"], C)
self.check(core, D["CB_STL"], range(C), ("st", ci, l, k), f"stats {k}")
self.ack[(core, D["CB_STL"])] += C
for ci in range(self.plan.nchunk):
v = view_of(self.w, ci, g, h, G)
fin, par = v["fin"]["used"], v["par"]["used"]
hf, pf = h, 1 - h
if fin:
yield self.wait_front(core, D["CB_E"], 1)
self.ack[(core, D["CB_E"])] += 1
yield from ln(ci, -1, 0)
yield from produce(D["CB_OB"], 4)
for l in range(self.nl):
last = l + 1 == self.nl
if par:
yield from consume_in0("x", pf, ci, l)
yield from produce(D["CB_PO"], 4)
if fin:
yield from consume_in0("x", hf, ci, l)
yield from final_pp(ci, l, "qkv")
yield from produce(D["CB_KVO"], 2)
yield self.wait_front(core, D["CB_KV"], 2 * MAXK)
base = (l & 1) * 2 * MAXK
self.check(core, D["CB_KV"], range(base, base + 2 * v["nk"]), ("kv", ci, l), "kv")
self.ack[(core, D["CB_KV"])] += 2 * MAXK
yield from produce(D["CB_OB"], 4)
if par:
yield from consume_in0("ctx", pf, ci, l)
yield from produce(D["CB_PO"], 4)
if fin:
yield from consume_in0("ctx", hf, ci, l)
yield from final_pp(ci, l, "o")
yield from ln(ci, l, 1)
yield from produce(D["CB_OB"], 4)
if par:
yield from consume_in0("h", pf, ci, l)
yield from produce(D["CB_PO"], 4)
if fin:
yield from consume_in0("h", hf, ci, l)
yield from final_pp(ci, l, "w1")
yield from produce(D["CB_OB"], 4)
if par:
yield from consume_in0("f", pf, ci, l)
yield from produce(D["CB_PO"], 4)
if fin:
yield from consume_in0("f", hf, ci, l)
yield from final_pp(ci, l, "w2")
yield from ln(ci, l, 2)
yield from produce(D["CB_TOK"] if last else D["CB_OB"], 1 if last else 4)
yield from produce(D["CB_DONE"], 1)
if y != 0:
yield from produce(D["CB_POUT"], 1)
else:
yield self.wait_front(core, D["CB_POOLL"], D["POOLL_T"])
for r in range(1, self.R):
self.check(core, D["CB_POOLL"], [r], ("pool", r), "pooled partial")
self.ack[(core, D["CB_POOLL"])] += D["POOLL_T"]
yield from produce(D["CB_POUT"], 1)
# ------------------------------------------------------------------ run
def run(self, max_steps: int = 20_000_000):
threads = []
for c in self.cores:
for f in (self.brisc, self.ncrisc, self.trisc):
threads.append([f.__name__, c, f(c), None])
live = list(range(len(threads)))
steps = 0
while live:
steps += 1
if steps > max_steps:
raise Deadlock("step limit")
progressed = False
self.rng.shuffle(live)
for i in list(live):
name, c, gen, cond = threads[i]
if cond is not None and not cond():
continue
try:
threads[i][3] = next(gen)
except StopIteration:
live.remove(i)
progressed = True
break
if self.pending():
self.deliver()
progressed = True
if not progressed:
stuck = [(threads[i][0], threads[i][1]) for i in live][:12]
raise Deadlock(f"no thread can progress; waiting: {stuck}")
return steps