# SPDX-License-Identifier: Apache-2.0 """The numba twins of ``host/fast.py`` (``FRNET_HOST_PRE`` / ``FRNET_HOST_POST=numba``) against the numpy oracles of ``host/preprocess.py`` / ``host/postprocess.py``, byte for byte: every array of ``NetworkInputs`` and ``FramePlan``, and the post-processed (class_id, probability, filter_keep), on the shipped samples, the staged PandaSet sample, EVERY catalogued research golden frame and adversarial clouds (fp16 overflow, NaN / inf intensities, exact depth ties, empty interpolation, all points in one cell, no crop), plus the fp16 conversion on 2^24 float32 patterns (every 256th, and all specials; the exhaustive 2^32 sweep is logged in OPT_REPORT r2.1) and every fp16 pattern. No device, no torch. TT_VISIBLE_DEVICES=none python -m pytest -q code/tt_frnet/tests/test_host_fast.py """ from __future__ import annotations import numpy as np import pytest from tt_frnet.host import fast as F from tt_frnet.host import preprocess as P from tt_frnet.host.frame import POINT_FIELDS, FRNetPreprocessor from tt_frnet.host.postprocess import autoware_argmax, filter_keep_mask from tt_frnet.reference.config import VARIANTS, FRNetConfig from tt_frnet.tests import _data pytestmark = pytest.mark.skipif(not F.available(), reason="numba is not installed") INPUT_KEYS = ("points", "coors", "voxel_coors", "inverse_map", "keep_mask") PLAN_KEYS = ("order", "seg_id", "seg_offsets", "seg_last", "features") @pytest.fixture(scope="module") def configs(): w = _data.weights_dir() return {v: FRNetConfig.from_model_dir(w, v) for v in VARIANTS} @pytest.fixture(scope="module") def pre_norm(): from tt_frnet.reference.weights import load_weights w = load_weights(_data.weights_dir(), "ot128") return (w.pre_norm_scale, w.pre_norm_shift) def _same(a, b, what): a, b = np.asarray(a), np.asarray(b) assert a.dtype == b.dtype and a.shape == b.shape, (what, a.dtype, b.dtype, a.shape, b.shape) assert a.tobytes() == b.tobytes(), what def _check(xyzi, cfg, pre_norm, T12=None, bounds=None): a = P.autoware_preprocess(xyzi, cfg, sensor_to_ref_12=T12, crop_bounds=bounds) b = F.autoware_preprocess(xyzi, cfg, sensor_to_ref_12=T12, crop_bounds=bounds) for k in INPUT_KEYS: _same(getattr(a, k), getattr(b, k), k) assert (a.num_points_raw, a.crop_applied) == (b.num_points_raw, b.crop_applied) g0, f0 = P.interpolation_grid(a.points[: a.num_points_raw], cfg) g1, f1 = F.interpolation_grid(a.points[: a.num_points_raw], cfg) _same(g0.view(np.uint16), g1.view(np.uint16), "grid") _same(f0, f1, "filled") _same(P.interpolate_points(g0, f0, cfg), F.interpolate_points(g1, f1, cfg), "interp") if a.num_points > cfg.n_cap or a.num_voxels > cfg.m_cap: return a, None pa = P.build_plan(a, cfg, pre_norm=pre_norm) pb = F.build_plan(a, cfg, pre_norm=pre_norm) for k in PLAN_KEYS: _same(getattr(pa, k), getattr(pb, k), k) for s in pa.strides: _same(pa.point2pix[s], pb.point2pix[s], f"point2pix[{s}]") _same(pa.pix2vox[s], pb.pix2vox[s], f"pix2vox[{s}]") assert (pa.n, pa.m, pa.max_segment_length) == (pb.n, pb.m, pb.max_segment_length) _same(P.build_plan(a, cfg).features, F.build_plan(a, cfg).features, "features without pre_norm") _check_post(pa, cfg, seed=a.num_points) return a, pa def _check_post(plan, cfg, seed=0): rng = np.random.default_rng(seed) rows = rng.dirichlet(np.ones(cfg.num_classes), size=plan.n_cap).astype(np.float32) rows = np.concatenate([rows, np.zeros((plan.n_cap, 32 - cfg.num_classes), np.float32)], axis=1) k = min(plan.n, 64) rows[:k:4] = np.nan # all NaN -> class C - 1, prob -1e9 rows[1:k:4, :cfg.num_classes] = -2e9 # nothing beats the -1e9 start rows[2:k:4, 3] = rows[2:k:4, 5] = 2.0 # ties: the first maximum rows[3:k:4, 0] = 0.05 # == the threshold for idx, thr in ((cfg.filter_class_indices(), cfg.class_probability_threshold), ((0, 2, 26), 0.3), ((), 0.5)): probs = plan.unsort(rows[:, :cfg.num_classes]) c0, p0 = autoware_argmax(probs) k0 = filter_keep_mask(probs, idx, thr) c1, p1, k1 = F.postprocess_rows(rows, plan, cfg.num_classes, idx, thr) _same(c0, c1, "class_id") _same(p0, p1, "probability") _same(k0, k1, "filter_keep") c2, p2, k2 = F.postprocess_tiles(F.tilize_rows(rows), rows.shape[1], plan, cfg.num_classes, idx, thr) _same(c0, c2, "class_id (tiles)") _same(p0, p2, "probability (tiles)") _same(k0, k2, "filter_keep (tiles)") def test_tilize_model_matches_the_tile_layout(): """The host model of the TILE layout: element (r, c) of tile (r // 32, c // 32), face (r % 32 // 16, c % 32 // 16), row r % 16, column c % 16.""" rows = np.arange(64 * 64, dtype=np.float32).reshape(64, 64) t = F.tilize_rows(rows) for r, c in ((0, 0), (0, 17), (17, 0), (31, 31), (32, 5), (40, 50), (63, 63)): off = ((r // 32) * 2 + c // 32) * 1024 + ((r % 32) // 16 * 2 + (c % 32) // 16) * 256 + (r % 16) * 16 + c % 16 assert t[off] == rows[r, c] def test_f16_conversions_equal_numpy(): bits = np.arange(0, 1 << 32, 256, dtype=np.uint64).astype(np.uint32) specials = np.array([0x7f800000, 0xff800000, 0x7f800001, 0x7fc00000, 0xffc00001, 0x7f801fff, 0x7f802000, 0x477fefff, 0x477ff000, 0x47800000, 0x33000000, 0x33000001, 0x32ffffff, 0x38800000, 0x387fffff, 0x38000000, 0x80000001, 0x00000001], np.uint32) for b in (bits, specials, bits + np.uint32(1), bits + np.uint32(0x1000), bits | np.uint32(0xff)): x = b.reshape(-1, 1).view(np.float32) _same(F._f16(x), x.astype(np.float16).view(np.uint16), "f32 -> f16") h = np.arange(1 << 16, dtype=np.uint32).astype(np.uint16).reshape(-1, 1) _same(F._f32(h).view(np.uint32), h.view(np.float16).astype(np.float32).view(np.uint32), "f16 -> f32") @pytest.mark.parametrize("variant", VARIANTS) def test_shipped_and_pandaset_samples(configs, pre_norm, variant): from tt_frnet.ttaw import io as tio cfg = configs[variant] pre = FRNetPreprocessor(cfg, pre_norm=pre_norm) srcs = [(_data.shipped(variant), _data.shipped_calib(variant))] if _data.SAMPLE.is_file() and _data.SAMPLE_CALIB is not None: srcs.append((_data.SAMPLE, _data.SAMPLE_CALIB)) for src, calib in srcs: T12, bounds, _ = pre.crop_setup(calib) xyzi = np.ascontiguousarray(tio.load_points(src).select(POINT_FIELDS), np.float32) _check(xyzi, cfg, pre_norm, T12, bounds) # the request path with each backend: identical prepared frames a = FRNetPreprocessor(cfg, pre_norm=pre_norm, backend="numpy")(src, calib) b = FRNetPreprocessor(cfg, pre_norm=pre_norm, backend="numba")(src, calib) for k in INPUT_KEYS: _same(getattr(a.inputs, k), getattr(b.inputs, k), k) for k in PLAN_KEYS: _same(getattr(a.plan, k), getattr(b.plan, k), k) @pytest.mark.parametrize("frame", sorted(_data.FRAMES)) def test_every_research_golden_frame(configs, pre_norm, frame): _, prefix, variant = _data.FRAMES[frame] _, _, g = _data.load_frame(frame) cfg = configs[variant] raw = np.ascontiguousarray(g["raw_points"], np.float32)[:, :4] if "crop_sensor_to_ref_12" in g.files: _check(raw, cfg, pre_norm, g["crop_sensor_to_ref_12"], g["crop_bounds"].astype(np.float64)) else: _check(raw, cfg, pre_norm, None, (0, 0, 0, 0, 0, 0)) @pytest.mark.parametrize("variant", VARIANTS) def test_adversarial_clouds(configs, pre_norm, variant): cfg = configs[variant] rng = np.random.default_rng(7) off = (0, 0, 0, 0, 0, 0) base = np.c_[rng.uniform(-60, 60, (30000, 3)), rng.uniform(0, 255, 30000)].astype(np.float32) _check(base, cfg, pre_norm, None, off) # exact depth ties in one pixel (same point repeated, mirrored signs) and NaN / inf intensities t = base.copy() t[1000:1100] = t[1000] t[2000:2010, 3] = np.nan t[2010:2020, 3] = np.inf t[2020:2030, 3] = -np.inf t[3000:3100] = t[3000] * np.array([1, 1, 1, 1], np.float32) _check(t, cfg, pre_norm, None, off) # fp16 overflow of x / y / z (|v| > 65504: inf depth^2) and subnormal-size values o = base.copy() o[:50, 0] = 7e4 o[50:100, 1] = -1e5 o[100:150, :3] = 1e-6 o[150:160, :3] = 0.0 # depth 0: NaN pitch -> row 0 _check(o, cfg, pre_norm, None, off) # every point in one frustum cell (one long segment), and a frame with no interpolation candidates one = np.tile(np.array([[10.0, 0.0, 0.0, 5.0]], np.float32), (3000, 1)) one[:, 0] += rng.uniform(0, 1e-3, 3000).astype(np.float32) _check(one, cfg, pre_norm, None, off) # the crop path: an identity transform and a box around the origin T12 = np.array([1, 0, 0, 0, 1, 0, 0, 0, 1, 0.5, -0.25, 0.1], np.float32) _check(base, cfg, pre_norm, T12, (-20, -10, -5, 20, 10, 5)) # nothing left after the crop _check(base[:100] * np.float32(0.01), cfg, pre_norm, T12, (-20, -10, -5, 20, 10, 5)) def test_numba_backend_falls_back_without_numba(configs, monkeypatch): monkeypatch.setattr(F, "_nb", None) pre = FRNetPreprocessor(configs["ot128"], backend="numba") assert pre.backend == "numpy" def test_warm_up_compiles_the_read_only_post_specialisations(): """The served path passes READ-ONLY arrays to the post-processing kernels (the DLPack view of the device output's host buffer with FRNET_HOST_POST=tiles); numba compiles a separate specialisation for them, so ``warm_up`` (model load) must compile it too, or the first call after the load pays ~0.5 s of JIT (republish 2026-10-14).""" assert F.warm_up() k = F._kernels() for name in ("post_rows", "post_tiles"): readonly = [not sig[0].mutable for sig in k[name].signatures] assert True in readonly and False in readonly, (name, k[name].signatures)