centerpoint-p150 / code /tt_centerpoint /tests /test_reference_rewrites_host.py
changh95's picture
tt-model push centerpoint-p150 (container)
2230fab verified
Raw History Blame Contribute Delete
5.3 kB
# SPDX-License-Identifier: Apache-2.0
"""The TT-friendly forms of ``reference/rewrites.py`` equal the literal modules of ``reference/model.py`` (float32
summation order aside) with the real v4.1 weights, before any device time is spent:
- PFN layer 1 split ``h @ W1a + bcast(max h @ W1b)`` (no concat) == ``concat[h, tile(max h)] @ W1``;
- shared conv as a 3-way K-split ``sum_i conv(d_i, W_i)`` == ``conv(concat[d0, d1, d2], W)``;
- six heads as one 64 -> 384 + ReLU and one block-diagonal 384 -> 15 == the six 1x1 heads;
- ConvTranspose k = s (k2 s2 deblock1, k4 s4 deblock2) as ``linear(Cin -> s*s*Cout)`` + depth-to-space ==
``conv_transpose2d``;
- the gather-form canvas ``table[canvas_index]`` (zero sentinel row) == the scatter of the reference, on a real sample.
CPU only (torch); runs in tt-env with the fake ttnn and in the research venv.
TT_VISIBLE_DEVICES=none python -m pytest -q code/tt_centerpoint/tests/test_reference_rewrites_host.py
"""
from __future__ import annotations
import numpy as np
import pytest
torch = pytest.importorskip("torch")
from tt_centerpoint.host.preprocess import CenterPointPreprocessor # noqa: E402
from tt_centerpoint.reference import rewrites as R # noqa: E402
from tt_centerpoint.reference.config import CenterPointConfig # noqa: E402
from tt_centerpoint.reference.model import CenterPointTorch # noqa: E402
from tt_centerpoint.reference.weights import load_weights # noqa: E402
from tt_centerpoint.tests import _data # noqa: E402
from tt_centerpoint.ttaw.metrics import pcc # noqa: E402
@pytest.fixture(scope="module", params=["base", "tiny"])
def net(request):
torch.set_num_threads(2)
return CenterPointTorch(load_weights(_data.weights_dir(), request.param), threads=2)
def _close(a, b, rel=2e-5):
a, b = np.asarray(a), np.asarray(b)
scale = max(float(np.abs(b).max()), 1e-6)
assert float(np.abs(a - b).max()) <= rel * scale, (float(np.abs(a - b).max()), scale)
assert pcc(a, b) > 0.9999999
def test_pfn_split_equals_concat(net):
rng = np.random.default_rng(0)
x = rng.normal(0, 3, (500, 32, 9)).astype(np.float32)
x[:, 20:] = 0.0 # padded slots: still part of the max
enc = net.weights.encoder
t = lambda a: torch.from_numpy(np.array(a, dtype=np.float32)) # noqa: E731
with torch.no_grad():
ref = net.pfn(x).numpy()
alt = R.pfn_split(t(x), t(enc.w0), t(enc.b0), t(enc.w1a), t(enc.w1b), t(enc.b1)).numpy()
_close(alt, ref)
def test_k_split_shared_conv(net):
rng = np.random.default_rng(1)
shared = net.weights.head.shared
ds = [torch.from_numpy(rng.random((1, d.out_channels, 24, 24), dtype=np.float32))
for d in net.weights.head.deblocks]
with torch.no_grad():
ref = net.layer("head.shared", torch.cat(ds, dim=1)).numpy()
alt = R.k_split_torch(ds, shared).numpy()
_close(alt, ref)
parts = R.k_split_weights(shared, [128, 128, 128])
assert [p.shape[1] for p in parts] == [128, 128, 128]
with pytest.raises(ValueError):
R.k_split_weights(shared, [128, 128])
def test_merged_heads(net):
rng = np.random.default_rng(2)
x = torch.from_numpy(rng.random((1, 64, 20, 30), dtype=np.float32))
merged = R.merged_head_weights(net.weights.head)
wh, bh, wo, bo, slices = merged
assert wh.shape == (64, 384) and wo.shape == (384, 15) and [s[0] for s in slices][:2] == ["heatmap", "reg"]
assert np.count_nonzero(wo) <= 64 * 15 # block-diagonal
with torch.no_grad():
alt = R.merged_heads_torch(x, merged)
for name, hidden, final in net.weights.head.heads:
ref = net.layer(final.name, net.layer(hidden.name, x)).numpy()
_close(alt[name].numpy(), ref)
@pytest.mark.parametrize("index", [1, 2])
def test_deconv_as_linear_plus_depth_to_space(net, index):
layer = net.weights.head.deblocks[index]
rng = np.random.default_rng(3)
x = torch.from_numpy(rng.random((1, layer.in_channels, 12, 10), dtype=np.float32))
with torch.no_grad():
ref = net.layer(layer.name, x).numpy()
alt = R.deconv_linear_torch(x, layer).numpy()
assert alt.shape == ref.shape == (1, layer.out_channels, 12 * layer.stride, 10 * layer.stride)
_close(alt, ref)
wl, bl = R.deconv_as_linear(layer) # numpy path, the port's NHWC row order
y = x[0].permute(1, 2, 0).reshape(-1, layer.in_channels).numpy() @ wl + bl
nhwc = np.maximum(R.depth_to_space_nhwc(y, 12, 10, layer.stride, layer.out_channels), 0)
_close(nhwc.transpose(2, 0, 1)[None], ref)
def test_gather_canvas_equals_the_reference_scatter(net):
cfg = CenterPointConfig.from_weights(_data.weights_dir(), net.variant)
prep = CenterPointPreprocessor(cfg)(_data.SAMPLES / "test_pcd.npz")
with torch.no_grad():
pf = net.pfn(prep.features[:prep.num_pillars])
canvas = net.scatter(pf, prep.coords, prep.num_pillars, cfg.grid_x, cfg.grid_y).numpy()
table = np.zeros((cfg.max_voxel_size + 1, 32), np.float32) # pillar rows + the zero row (index 40,000)
table[:prep.num_pillars] = pf.numpy()
nhwc = table[prep.canvas_index.astype(np.int64)].reshape(cfg.grid_y, cfg.grid_x, 32)
assert np.array_equal(nhwc.transpose(2, 0, 1)[None], canvas)