frnet-p150 / code /scripts /diag /kcat_order_probe.py
changh95's picture
tt-model push frnet-p150 (container)
7a24154 verified
Raw History Blame Contribute Delete
6.83 kB
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Precision probe of the two-term point linear's accumulation orders (verification F1 of OPT round 1).
bin/devrun -t 600 -- python -u code/scripts/diag/kcat_order_probe.py [--n 4096]
Every variant computes ``x @ W + b`` (no activation) for fp32 x / W split into bf16 hi / lo terms, against fp64:
* ``base`` -- the 3-matmul form of ``FRNET_KCAT=0`` (``PointLinear(kcat=0)``: fp32 outputs + fp32 adds);
* ``kcat_pp`` -- r1.1 KCAT: per part ``[x_hi | x_hi | x_lo] @ [W_hi; W_lo; W_hi]``, one fp32 DEST accumulation;
* ``kcat_lohi``-- per part ``[x_hi | x_lo | x_hi] @ [W_lo; W_hi; W_hi]`` (the correction terms of a part first);
* ``kcat_glo`` -- global order: every part's corrections first, then every part's ``x_hi @ W_hi``;
* ``kcat_ghi`` -- global order: every ``x_hi @ W_hi`` first, then the corrections;
* ``split2`` -- two matmuls (main ``x_hi @ W_hi`` K-concatenated over parts, corrections K-concatenated) + fp32 add;
* ``hi_only`` -- ``x_hi @ W_hi`` alone (the one-term bf16 floor).
Reported per variant: rms(err) / rms(ref), mean(err) / rms(ref) (signed bias), mean(err * sign(ref)) / rms(ref)
(bias toward / away from zero) and the max |err| / max |ref|.
"""
from __future__ import annotations
import argparse
import sys
import numpy as np
import torch
sys.path.insert(0, __file__.rsplit("/scripts/", 1)[0])
import ttnn # noqa: E402
from tt_frnet.reference.weights import Linear # noqa: E402
from tt_frnet.tt.layers import PointLinear # noqa: E402
from tt_frnet.ttaw.device import close_device, open_device # noqa: E402
from tt_frnet.ttaw.precision import Precision # noqa: E402
from tt_frnet.ttaw.tensors import round_to_bf16 # noqa: E402
def dev_t(a, dev, dt):
return ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(a)), dtype=dt, layout=ttnn.TILE_LAYOUT, device=dev,
memory_config=ttnn.DRAM_MEMORY_CONFIG)
def host(t):
return ttnn.to_torch(t).float().numpy().astype(np.float64)
def split(v):
hi = round_to_bf16(v)
return hi, round_to_bf16(v - hi)
def stats(y, ref):
e = y - ref
r = np.sqrt(np.mean(ref ** 2))
return (np.sqrt(np.mean(e ** 2)) / r, np.mean(e) / r, np.mean(e * np.sign(ref)) / r,
np.abs(e).max() / np.abs(ref).max())
def run_case(dev, rng, n, parts, out, cfgs, label):
k = sum(parts)
x = [(np.maximum(rng.standard_normal((1, 1, n, p)), 0) * 3).astype(np.float32) for p in parts]
w = (rng.standard_normal((k, out)) / np.sqrt(k)).astype(np.float32)
b = (rng.standard_normal(out) * 0.1).astype(np.float32)
ws, s = [], 0
for p in parts:
ws.append(w[s:s + p])
s += p
ref = np.concatenate(x, -1).astype(np.float64)[0, 0] @ w.astype(np.float64) + b.astype(np.float64)
xs = [split(a[0, 0]) for a in x]
wt = [split(a) for a in ws]
blocks = {
"kcat_pp": [blk for (xh, xl), (wh, wl) in zip(xs, wt) for blk in ((xh, wh), (xh, wl), (xl, wh))],
"kcat_lohi": [blk for (xh, xl), (wh, wl) in zip(xs, wt) for blk in ((xh, wl), (xl, wh), (xh, wh))],
"kcat_glo": [blk for (xh, xl), (wh, wl) in zip(xs, wt) for blk in ((xh, wl), (xl, wh))]
+ [(xh, wh) for (xh, _), (wh, _) in zip(xs, wt)],
"kcat_ghi": [(xh, wh) for (xh, _), (wh, _) in zip(xs, wt)]
+ [blk for (xh, xl), (wh, wl) in zip(xs, wt) for blk in ((xh, wl), (xl, wh))],
}
bt = dev_t(b.reshape(1, -1), dev, ttnn.float32)
res = {}
for cname, cfg in cfgs.items():
def mm(bl, bias=True):
xa = dev_t(np.concatenate([a for a, _ in bl], -1)[None, None], dev, ttnn.bfloat16)
wa = dev_t(np.concatenate([c for _, c in bl], 0), dev, ttnn.bfloat16)
y = ttnn.linear(xa, wa, bias=bt if bias else None, compute_kernel_config=cfg,
memory_config=ttnn.DRAM_MEMORY_CONFIG, dtype=ttnn.float32)
ttnn.deallocate(xa)
ttnn.deallocate(wa)
return y
for v, bl in blocks.items():
y = mm(bl)
res[f"{v}/{cname}"] = stats(host(y)[0, 0], ref)
ttnn.deallocate(y)
# bias as a K' column: a ones tile [1, 1, 1, 0 ..] x [b_hi; b_lo; b_lo2; 0 ..] (no fused bias epilogue)
one = np.zeros((n, 32), np.float32)
one[:, :3] = 1.0
bh, bl = split(b)
brow = np.zeros((32, out), np.float32)
brow[0], brow[1], brow[2] = bh, bl, round_to_bf16(b - bh - bl)
for v in ("kcat_pp", "kcat_glo"):
for where in ("first", "last"):
bl_ = list(blocks[v])
bl_ = [(one, brow)] + bl_ if where == "first" else bl_ + [(one, brow)]
y = mm(bl_, bias=False)
res[f"{v}+bcol_{where}/{cname}"] = stats(host(y)[0, 0], ref)
ttnn.deallocate(y)
y = mm(blocks["kcat_pp"], bias=False)
res[f"kcat_pp_nobias/{cname}"] = stats(host(y)[0, 0], ref - b.astype(np.float64))
ttnn.deallocate(y)
y1 = mm([(xh, wh) for (xh, _), (wh, _) in zip(xs, wt)])
res[f"hi_only/{cname}"] = stats(host(y1)[0, 0], ref)
y2 = mm([blk for (xh, xl), (wh, wl) in zip(xs, wt) for blk in ((xh, wl), (xl, wh))], bias=False)
y = ttnn.add(y1, y2, memory_config=ttnn.DRAM_MEMORY_CONFIG)
res[f"split2/{cname}"] = stats(host(y)[0, 0], ref)
for t in (y, y1, y2):
ttnn.deallocate(t)
lin = Linear(name=label, weight=w, bias=b, relu=False, onnx_node="-", onnx_output="-")
pl = PointLinear(lin, parts=list(parts), terms=2, kcat=0, name=label)
xd = [dev_t(a, dev, ttnn.float32) for a in x]
y = pl(xd)
res["base/point"] = stats(host(y)[0, 0], ref)
pl.release()
for t in xd + [y, bt]:
ttnn.deallocate(t)
print(f"== {label}: n={n} parts={parts} out={out}", flush=True)
for key, (rms, bias, tz, mx) in res.items():
print(f" {key:22s} rms {rms:.3e} bias {bias:+.3e} toward-|ref| {tz:+.3e} max {mx:.3e}", flush=True)
return res
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--n", type=int, default=4096)
ap.add_argument("--seed", type=int, default=0)
a = ap.parse_args()
rng = np.random.default_rng(a.seed)
dev = open_device(0, dispatch="eth")
cfgs = {"fp32": Precision.parse("HiFi4+fp32").compute_kernel_config(),
"fp32+l1acc": Precision.parse("HiFi4+fp32+l1acc").compute_kernel_config()}
try:
for parts, out, label in (((128,), 128, "one128"), ((256,), 128, "one256"), ((128,) * 5, 256, "fuse1"),
((128, 128), 128, "fusion")):
run_case(dev, rng, a.n, parts, out, cfgs if label == "fuse1" else {"fp32": cfgs["fp32"]}, label)
print("PROBE OK", flush=True)
finally:
close_device(dev)
if __name__ == "__main__":
main()