tt-model push auto_e2e-p150 (container)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+9
- README.md+29-8
- build_info.json+7-7
- code/tt_autoe2e/api.py+24-8
- code/tt_autoe2e/host/geometry.py+88-24
- code/tt_autoe2e/tests/dev_api.py+7-4
- code/tt_autoe2e/tests/dev_cm_probe.pyAdded+135
- code/tt_autoe2e/tests/dev_encoder.py+2-2
- code/tt_autoe2e/tests/dev_eval.py+2-2
- code/tt_autoe2e/tests/dev_frame_prof.pyAdded+102
- code/tt_autoe2e/tests/dev_layer_ops.pyAdded+189
- code/tt_autoe2e/tests/dev_msda_probe.py+16-2
- code/tt_autoe2e/tests/dev_msda_riscs.pyAdded+102
- code/tt_autoe2e/tests/dev_msda_unit.py+8-2
- code/tt_autoe2e/tests/dev_prof.pyAdded+172
- code/tt_autoe2e/tests/dev_runner.py+4-3
- code/tt_autoe2e/tests/dev_step.py+2-2
- code/tt_autoe2e/tests/dev_t8_prof.pyAdded+104
- code/tt_autoe2e/tests/dev_t8_sweep.pyAdded+120
- code/tt_autoe2e/tests/host_geometry.pyAdded+91
- code/tt_autoe2e/tt/encoder.py+277-37
- code/tt_autoe2e/tt/image.py+7-1
- code/tt_autoe2e/tt/kernels/msda_cm_compute.cppAdded+360
- code/tt_autoe2e/tt/kernels/msda_cm_reader.cppAdded+338
- code/tt_autoe2e/tt/kernels/msda_k_compute.cpp+100-13
- code/tt_autoe2e/tt/kernels/msda_k_reader.cpp+285-35
- code/tt_autoe2e/tt/kernels/pairmap2_dm.cpp+43-13
- code/tt_autoe2e/tt/msda_cm.pyAdded+125
- code/tt_autoe2e/tt/msda_k.py+25-12
- code/tt_autoe2e/tt/pairmap.py+6-3
- code/tt_autoe2e/tt/runner.py+64-18
- code/tt_autoe2e/tt/t8.py+39-8
- image/blobs/sha256/0ee85adffdf6df32309b3e71402c5c982f7c6fd6e52c7a5143a979548cd172d0Added+1
- image/blobs/sha256/0f4b5bb0adf19a18c065d16e0056ab8b28f2982602edbe333d5f45d51b47f3feAdded+1
- image/blobs/sha256/188ff78ba17c8232a2f3aba4b35f5c7dbd5307be0d492e11ef26c958623660d3Added
- image/blobs/sha256/1ae0d5f9058b59d711d64697b6fd66f7352eb6f99d0acabcaedc0756af0d5bc4Added+1
- image/blobs/sha256/1c431ceec10d195155444a08b220938ba6cc6892d72cd0ca32e6e3dee371532aAdded+1
- image/blobs/sha256/241d4a5b2a827d8e1238d9227a5ebde070af2a9a0b0918ec8cf3839c7691e3deAdded+3
- image/blobs/sha256/2e540ce4b247929a60b17412f50ddc77ce0374487a916f7b85c4873cf2f6d17aAdded+1
- image/blobs/sha256/30e958a3682167e11e043ef27b0bba08a720570a9a5a848b6afb9c97b1db44dbAdded+1
- image/blobs/sha256/37ffd05da440e151828a5098fe24b8cc4eb2b747f1536dffccd223ccd5f5b4bdAdded+1
- image/blobs/sha256/3ba05941cae059ea9b5b3f14cf8b93a664c9de02d175acda61f7c0c7446a5edbAdded+1
- image/blobs/sha256/3eaf130059f3e4080f8dc71afcb2ed53310ee60187b4bca947458c563849a457Added+3
- image/blobs/sha256/508946978b347a9317dcda6349a6e3a9468f6446dfc6ae299f2862ba38d300b3Added
- image/blobs/sha256/50d4519dcf5bd619f82687a07c264641bb7731831868a3f16ba0736edf10f3e5Added+1
- image/blobs/sha256/5b7a27d05e6bed4da52cefef7e59cb1f91ea8214a022a1e6e62ec6081f3df589Added
- image/blobs/sha256/5d611147b10a84989047de9d9456d5e3e7ebdbae72b4d7042a1ecf0db2c5d4d8Added+1
- image/blobs/sha256/6706e1ed57bf105dc9cd1e3eef974838bbc2d69aca3c7d5a31d8f6224337e6feAdded+3
- image/blobs/sha256/6b1f63635e5e7cd962ea3f65b6036e86d4e838a24de9559a546834c1b49ed396Added+3
- image/blobs/sha256/6b4c3d2493d54e0d53054e8fbeaa0ad99b0ab33907187485a62dd2b7b74e3a72Added+1
47 unmodified lines48495047 unmodified linesimage/blobs/sha256/e6942d2ab497950845c7fe0c45ea02ace8546e0348dc0c7870c8962bb4214ef1 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/ea16cace89338c84eb6bcb91a7efdfcae6838fff359efe951858227436486c34 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/f8107acf65e5f33d4d8eeff9372d6c7c69467c202c43e8c2f6ede74685e99647 filter=lfs diff=lfs merge=lfs -text47 unmodified lines48495051525354555657585947 unmodified linesimage/blobs/sha256/e6942d2ab497950845c7fe0c45ea02ace8546e0348dc0c7870c8962bb4214ef1 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/ea16cace89338c84eb6bcb91a7efdfcae6838fff359efe951858227436486c34 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/f8107acf65e5f33d4d8eeff9372d6c7c69467c202c43e8c2f6ede74685e99647 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/241d4a5b2a827d8e1238d9227a5ebde070af2a9a0b0918ec8cf3839c7691e3de filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/3eaf130059f3e4080f8dc71afcb2ed53310ee60187b4bca947458c563849a457 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/6706e1ed57bf105dc9cd1e3eef974838bbc2d69aca3c7d5a31d8f6224337e6fe filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/6b1f63635e5e7cd962ea3f65b6036e86d4e838a24de9559a546834c1b49ed396 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/8ba27c0105636d886344b2db6eeb3f7c41fc587c486aa74e11d069912840ef55 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/911536ee12614e924d480b52f58e8682139a877f7f74730411615e86203779e1 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/9df66ea49aa0dedf21915ca1731ec8ec470892518778685652756275ba89eea5 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/be2c3263fa139c48ac5163fb402a10ff90827fd38c3c613a372549bacde47ee0 filter=lfs diff=lfs merge=lfs -textimage/blobs/sha256/eafd2f0c5ccfc07ea4fc93c0763b5b6b72eaa55f8cf8535f5c7d6e90a09cb988 filter=lfs diff=lfs merge=lfs -text
80 unmodified lines8182838485868788899091929394953 unmodified lines991001011021031041051061 unmodified line1081091101111121131141157 unmodified lines12312412512612712811 unmodified lines14014114214314414580 unmodified lines(real past steps used: a new or reset stream starts with the current step copied into the history, upstream'sbehaviour without history).## Expected performanceKITScenes Multimodal val (KIT-MRT), 12 scenes not in AutoE2E's training split, 626 steps (one evaluator lane: every 500 ms of each scene, the stateful stream of the upstream evaluator), through AutoE2E's own preprocessed `kitscenes-val/v3.5` shards; references: upstream `predict_control` on an RTX 5090 in fp32 (TF32 off) and in upstream's bf16 autocast, the precision of the published metrics.| | this package (p150) | upstream's own bf16 autocast (CUDA) || --- | --- | --- || Controls (acceleration, curvature), relative L2 to the fp32 reference, median / p95 | 0.93% / 4.32% | 1.40% / 5.08% || Trajectory distance to the fp32 reference's at 1 / 3 / 5 s, median (m) | 0.001 / 0.011 / 0.034 | 0.004 / 0.036 / 0.103 || Same, p95 (m) | 0.006 / 0.034 / 0.108 | 0.013 / 0.097 / 0.272 || ADE against the logged trajectory at 1 / 3 / 5 s (m) | value || --- | --- |3 unmodified lines| speed (one stream, warm) | value || --- | --- || One step on the device (traced replay: image branch, 8 BEV frames, fusion) | 1.76 s || Served `POST /predict` (decode, pre-processing, device, planner) | 3.30 s |The spread of upstream's own bf16 run from fp32 is the scale of a bf16 implementation's differences. Measured with this package's code on one p150a (32-thread AMD host shared with an Autoware simulation).1 unmodified line- Do not use it to drive or control a vehicle or as any safety function: AutoE2E is research software and thisis not a certified component.- About 3.3 s per step on one p150 (the model's design cadence is 2 Hz): the 8 BEV frames arerecomputed every step (each step rebuilds the history BEVs in the current ego frame), 1.8 s of device time.- One stream at a time (a new stream id restarts the history); batch 1.- Trained on KITScenes (Karlsruhe, Frankfurt): other rigs and regions are out of distribution.- bf16 activations with fp32 accumulation (see the performance table for the spread).7 unmodified lineskernels extend those of the BEVFormer p150 port (Apache-2.0).- Samples `code/tt_autoe2e/samples/synthetic_drive*` and `calib/synthetic_rig.json`: generated by`tools/make_sample.py` (no third-party data), Apache-2.0.## Related packages11 unmodified lines| component | built from || --- | --- || tt-metal | a local checkout — commit not published *(dirty tree — the image includes uncommitted changes)* || `code/` digest | `7ef6b9a0d647149f` (sha256, first 16 hex digits) || built | 2026-12-05T01:17:56+00:00 by tt-model 0.1.0 |80 unmodified lines818283848586878889909192939495969798991001011021031041051061071081091103 unmodified lines1141151161171181191201211221 unmodified line1241251261271281291301311327 unmodified lines14014114214314414514614714814911 unmodified lines16116216316416516680 unmodified lines(real past steps used: a new or reset stream starts with the current step copied into the history, upstream'sbehaviour without history).### Example output: AutoE2E on KITScenes<video controls muted playsinline width="880" poster="https://huggingface.co/changh95/auto_e2e-p150/resolve/main/media/auto_e2e_p150_kitscenes_demo.jpg" src="https://huggingface.co/changh95/auto_e2e-p150/resolve/main/media/auto_e2e_p150_kitscenes_demo.mp4"></video>This package on one p150 driving two [KITScenes Multimodal](https://kitscenes.com) val scenes (not in AutoE2E'straining split: a right turn in Frankfurt, a left turn and city streets in Karlsruhe): every 500 ms the6 cameras, the front camera at 1024 px, the calibration, the ego history and the navigation rasters go throughthe traced stateful runner, andthe 6.4 s plan (upstream's rollout of the p150 controls) is drawn in green on the front camera at 10 Hz, carriedthrough the logged poses until the next step; dashed white is the logged future path. The inset shows the planfrom above with upstream's own fp32 run of the same step on an RTX 5090 (thin magenta, on top of the green) andthe logged path. 1280x720, 10 fps: [MP4](media/auto_e2e_p150_kitscenes_demo.mp4). Camera frames: KITScenesMultimodal (KIT-MRT), CC BY-NC 4.0 with the KITScenes terms, faces and licence plates anonymised by the dataset;sources and licences of every file in `media/`: [`media/ATTRIBUTION.md`](media/ATTRIBUTION.md).## Expected performanceKITScenes Multimodal val (KIT-MRT), 12 scenes not in AutoE2E's training split, 626 steps (one evaluator lane: every 500 ms of each scene, the stateful stream of the upstream evaluator), through AutoE2E's own preprocessed `kitscenes-val/v3.5` shards; references: upstream `predict_control` on an RTX 5090 in fp32 (TF32 off) and in upstream's bf16 autocast, the precision of the published metrics.| | this package (p150) | upstream's own bf16 autocast (CUDA) || --- | --- | --- || Controls (acceleration, curvature), relative L2 to the fp32 reference, median / p95 | 0.97% / 4.38% | 1.40% / 5.08% || Trajectory distance to the fp32 reference's at 1 / 3 / 5 s, median (m) | 0.001 / 0.011 / 0.034 | 0.004 / 0.036 / 0.103 || Same, p95 (m) | 0.006 / 0.034 / 0.107 | 0.013 / 0.097 / 0.272 || ADE against the logged trajectory at 1 / 3 / 5 s (m) | value || --- | --- |3 unmodified lines| speed (one stream, warm) | value || --- | --- || One step on the device (traced replay: image branch, 8 BEV frames, fusion) | 0.81 s || Python API call of a streaming step (pre-processing / device with uploads / planner) | 1.05 s (158 / 883 / 22 ms) || API call after a reset (the 7 history steps pushed, then the step) | 1.47 s |The spread of upstream's own bf16 run from fp32 is the scale of a bf16 implementation's differences. Measured with this package's code on one p150a (32-thread AMD host shared with an Autoware simulation).1 unmodified line- Do not use it to drive or control a vehicle or as any safety function: AutoE2E is research software and thisis not a certified component.- About 1.05 s per streaming step on one p150 (the model's design cadence is 2 Hz): the 8 BEVframes are recomputed every step (each step rebuilds the history BEVs in the current ego frame), 0.81 s ofdevice time.- One stream at a time (a new stream id restarts the history); batch 1.- Trained on KITScenes (Karlsruhe, Frankfurt): other rigs and regions are out of distribution.- bf16 activations with fp32 accumulation (see the performance table for the spread).7 unmodified lineskernels extend those of the BEVFormer p150 port (Apache-2.0).- Samples `code/tt_autoe2e/samples/synthetic_drive*` and `calib/synthetic_rig.json`: generated by`tools/make_sample.py` (no third-party data), Apache-2.0.- Demo video and its poster in `media/`: renders, not part of the package. Camera frames from KITScenesMultimodal (KIT-MRT, [kitscenes.com](https://kitscenes.com)), CC BY-NC 4.0 with the KITScenes terms; theoverlays are this package's outputs. KIT-MRT and the Autoware Foundation do not endorse this work. Details:[`media/ATTRIBUTION.md`](media/ATTRIBUTION.md).## Related packages11 unmodified lines| component | built from || --- | --- || tt-metal | a local checkout — commit not published *(dirty tree — the image includes uncommitted changes)* || `code/` digest | `7fd49e16113dbe1c` (sha256, first 16 hex digits) || built | 2026-12-05T13:54:00+00:00 by tt-model 0.1.0 |
1234567891011121314{"schema": "ttaw-build-info/1","bundle": "auto_e2e-p150","recorded_at": "2026-12-05T01:28:17Z","image": {"tag": "tt-model/auto_e2e-p150:b6f032f80564","digest": "sha256:b6f032f805643a5cfbff7f37465397d45451a9734cec1b25800bd7199080277d","digest_kind": "image config (classic Docker image store); the OCI manifest that names it: sha256:6f8f1df61712064ed700db428734c42533dbfb95c4f634687ac0f542ee1386d8","built_at": "2026-12-05T01:28:04Z","code_sha256": "7ef6b9a0d647149f93f5241fc8c1c27b7ca1f774f80e331ab613fc2e03f96c1a","size_bytes": 2998495096,"layers": 23},"base_images": {1234567891011121314{"schema": "ttaw-build-info/1","bundle": "auto_e2e-p150","recorded_at": "2026-12-05T14:10:04Z","image": {"tag": "tt-model/auto_e2e-p150:0f4b5bb0adf1","digest": "sha256:0f4b5bb0adf19a18c065d16e0056ab8b28f2982602edbe333d5f45d51b47f3fe","digest_kind": "image config (classic Docker image store); the OCI manifest that names it: sha256:30e958a3682167e11e043ef27b0bba08a720570a9a5a848b6afb9c97b1db44db","built_at": "2026-12-05T13:59:45Z","code_sha256": "7fd49e16113dbe1c24aa9be624e03bdb857fd86d53077c5ffc3b8878e8c535cd","size_bytes": 2995233011,"layers": 23},"base_images": {
125 unmodified lines1261271281291301311326 unmodified lines13914014114214314414536 unmodified lines1821831841851861871881891901911921931941951961975 unmodified lines203204205206207208209125 unmodified linesif getattr(self, "_executor", None) is None:from concurrent.futures import ThreadPoolExecutorself._executor = ThreadPoolExecutor(max_workers=4, thread_name_prefix="autoe2e-host")return self._executordef _warm_one(self, variant: Any) -> None:6 unmodified linesdef _prepare(self, *, images: Any = None, calibration: Any = None, stream: Optional[Mapping] = None,inputs: Any = None, **_: Any) -> Dict[str, Any]:from .host import head as Hfrom .host.geometry import frame_geometryfrom .tt.fusion import FRONT_CAPfrom .tt.image import backbone_input36 unmodified lines# the geometry of the 9 frames and the navigation encoder are independent: run them concurrently (torch /# numpy release the GIL), the navigation encoder first since it is the longestpool = self._pool()nav_f = pool.submit(H.navigation, self.state, mc, rm, map_valid, route_valid)geo_f = [pool.submit(frame_geometry, p.astype(np.float32), 512) for p in P_hist + [P]]front_f = pool.submit(frame_geometry, P_front.astype(np.float32), 1024, r_cap=FRONT_CAP, k_cams=1)geos = [f.result() for f in geo_f]geo_front = front_f.result()nav, _ = nav_f.result()ego = np.asarray(inputs["egomotion_history"], np.float32).reshape(64, 4).copy()ego[-1, 1] = 0.0 # the KITScenes policy: mask the latest history accelerationreturn {"cams": cams_in, "front": front_in, "geos": geos, "geo_front": geo_front,"nav": np.ascontiguousarray(nav.reshape(256, -1).T), "ego": ego.reshape(-1),"v0": float(ego[-1, 0]), "reset": reset, "sid": sid, "P": P, "pose": pose,"map_valid": map_valid, "route_valid": route_valid}5 unmodified linesself.history.clear()self.history.extend([(prep["P"], prep["pose"])] * 7)self.real_steps = 0fused = self.dev.step(prep["cams"], prep["front"], prep["geos"], prep["geo_front"], prep["nav"])history_steps = self.real_stepsself.history.append((prep["P"], prep["pose"]))self.real_steps = min(self.real_steps + 1, 7)125 unmodified lines1261271281291301311321331341356 unmodified lines14214314414514614714836 unmodified lines1851861871881891901911921931941951961971981992002012022032042052062072082092102115 unmodified lines217218219220221222223224225125 unmodified linesif getattr(self, "_executor", None) is None:from concurrent.futures import ThreadPoolExecutorimport osn = int(os.environ.get("AE_HOST_THREADS", "8"))self._executor = ThreadPoolExecutor(max_workers=n, thread_name_prefix="autoe2e-host")return self._executordef _warm_one(self, variant: Any) -> None:6 unmodified linesdef _prepare(self, *, images: Any = None, calibration: Any = None, stream: Optional[Mapping] = None,inputs: Any = None, **_: Any) -> Dict[str, Any]:from .host import head as Hfrom .host.geometry import bev_geometry, frame_geometryfrom .tt.fusion import FRONT_CAPfrom .tt.image import backbone_input36 unmodified lines# the geometry of the 9 frames and the navigation encoder are independent: run them concurrently (torch /# numpy release the GIL), the navigation encoder first since it is the longestpool = self._pool()def nav_rows():import torchnav, _ = H.navigation(self.state, mc, rm, map_valid, route_valid)# [Q, 256] bf16 rows for the device, converted here (on the pool) rather than in the uploadreturn torch.from_numpy(np.ascontiguousarray(nav.reshape(256, -1).T)).to(torch.bfloat16)nav_f = pool.submit(nav_rows)# one geometry per distinct matrix set (after a reset the 7 history frames repeat the current one)mats = [p.astype(np.float32) for p in P_hist + [P]]uniq: Dict[bytes, Any] = {}for m in mats:if m.tobytes() not in uniq:uniq[m.tobytes()] = pool.submit(bev_geometry, m, 512)front_f = pool.submit(frame_geometry, P_front.astype(np.float32), 1024, r_cap=FRONT_CAP, k_cams=1)geos = [uniq[m.tobytes()].result() for m in mats]geo_front = front_f.result()ego = np.asarray(inputs["egomotion_history"], np.float32).reshape(64, 4).copy()ego[-1, 1] = 0.0 # the KITScenes policy: mask the latest history accelerationreturn {"cams": cams_in, "front": front_in, "geos": geos, "geo_front": geo_front,"nav_f": nav_f, "ego": ego.reshape(-1),"v0": float(ego[-1, 0]), "reset": reset, "sid": sid, "P": P, "pose": pose,"map_valid": map_valid, "route_valid": route_valid}5 unmodified linesself.history.clear()self.history.extend([(prep["P"], prep["pose"])] * 7)self.real_steps = 0# step_a runs on the device while the navigation BEV finishes on the host poolself.dev.step_begin(prep["cams"], prep["front"], prep["geos"], prep["geo_front"])fused = self.dev.step_end(prep["nav_f"].result())history_steps = self.real_stepsself.history.append((prep["P"], prep["pose"]))self.real_steps = min(self.real_steps + 1, 7)
13 unmodified lines1415161718192027 unmodified lines48495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979813 unmodified linesK cameras do): the scatter-add over cameras as K gathers;- ``scale`` ``[Q, 1]`` float32: ``1 / max(count, 1)``; ``observed`` ``[Q, 1]``: 1 where any camera sees the cell.Positions are computed in float64 from upstream's float32 ``uv`` (``reference/port_form.reference_points``)."""from __future__ import annotations27 unmodified linesdef frame_geometry(P: np.ndarray, image: int = 512, *, r_cap: int = R_CAP, k_cams: int = K_CAMS) -> FrameGeometry:"""``P`` ``[V, 3, 4]`` (ego -> pixels of the ``image`` x ``image`` model input) -> :class:`FrameGeometry`."""import torchuv, mask = reference_points(torch.as_tensor(np.asarray(P, np.float32)), image)uv = uv.numpy().astype(np.float64) # [V, Q, 4, 2]vis = mask.numpy().any(-1) # [V, Q]V = vis.shape[0]rows = [np.nonzero(vis[v])[0] for v in range(V)]seg_rows = [int(-(-len(r) // 32) * 32) for r in rows]total = sum(seg_rows)if total > r_cap:raise ValueError(f"frame_geometry: {total} rebatched rows exceed the capacity {r_cap}")if V > 8:raise ValueError("frame_geometry: at most 8 cameras")sca_index = np.full((1, r_cap), Q, np.uint32)base = np.full((r_cap, LEVELS * 16), FAR, np.float32)cams_of = np.zeros(Q, np.int64)gather = np.full((k_cams, Q), r_cap, np.uint32)anchors = np.arange(POINTS) % PILLARSsizes = level_sizes(image)start = 0ends = np.zeros((1, 1, 1, 16), np.uint32)for v, r in enumerate(rows):n = len(r)sca_index[0, start:start + n] = ra = uv[v, r][:, anchors] # [n, 8, 2]for lvl, (h, w) in enumerate(sizes):px = (a[..., 0] * w - 0.5) * 65536.0py = (a[..., 1] * h - 0.5) * 65536.0blk = np.stack([px, py], -1).reshape(n, 16)base[start:start + n, lvl * 16:(lvl + 1) * 16] = blk.astype(np.float32)slot = cams_of[r]if n and slot.max() >= k_cams:raise ValueError(f"frame_geometry: a cell is seen by more than {k_cams} cameras")gather[slot, r] = np.arange(start, start + n, dtype=np.uint32)cams_of[r] += 1start += seg_rows[v]ends[0, 0, 0, v] = start // 32ends[0, 0, 0, V:8] = r_cap // 32# the last segment owns the padding blocks after it (its rows there are padding: cell Q, FAR positions)ends[0, 0, 0, V - 1] = r_cap // 32cnt = cams_of.astype(np.float32)scale = (1.0 / np.maximum(cnt, 1.0)).reshape(Q, 1).astype(np.float32)observed = (cnt > 0).astype(np.float32).reshape(Q, 1)return FrameGeometry(sca_index, base, ends, seg_rows, gather, scale, observed, [int(len(r)) for r in rows])def tsa_base() -> np.ndarray:13 unmodified lines1415161718192027 unmodified lines4849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116213 unmodified linesK cameras do): the scatter-add over cameras as K gathers;- ``scale`` ``[Q, 1]`` float32: ``1 / max(count, 1)``; ``observed`` ``[Q, 1]``: 1 where any camera sees the cell.Positions come from upstream's float32 ``uv`` (``reference/port_form.reference_points``)."""from __future__ import annotations27 unmodified linesdef frame_geometry(P: np.ndarray, image: int = 512, *, r_cap: int = R_CAP, k_cams: int = K_CAMS) -> FrameGeometry:"""``P`` ``[V, 3, 4]`` (ego -> pixels of the ``image`` x ``image`` model input) -> :class:`FrameGeometry`.Vectorized over the cameras' rows in float32: the level sizes are powers of two, so ``uv * size`` is exact and``(uv * size - 0.5) * 2^16`` rounds once, like the float64 computation cast to float32 (``tests/host_geometry``checks the two bit for bit)."""import torchuv, mask = reference_points(torch.as_tensor(np.asarray(P, np.float32)), image)uv = uv.numpy() # [V, Q, 4, 2] float32vis = mask.numpy().any(-1) # [V, Q]V = vis.shape[0]if V > 8:raise ValueError("frame_geometry: at most 8 cameras")rows = [np.flatnonzero(vis[v]) for v in range(V)]counts = [len(r) for r in rows]seg_rows = [int(-(-n // 32) * 32) for n in counts]total = sum(seg_rows)if total > r_cap:raise ValueError(f"frame_geometry: {total} rebatched rows exceed the capacity {r_cap}")sizes = level_sizes(image)wh = np.array([[w, h] for h, w in sizes], np.float32) # [L, 2]if any(int(x) & (int(x) - 1) for x in wh.ravel()):raise ValueError(f"frame_geometry: level sizes {sizes} are not powers of two")starts = np.concatenate([[0], np.cumsum(seg_rows)[:-1]]).astype(np.int64)cam = np.repeat(np.arange(V), counts)cell = np.concatenate(rows) if V else np.zeros(0, np.int64)dst = np.concatenate([s + np.arange(n) for s, n in zip(starts, counts)]) if V else np.zeros(0, np.int64)a = uv[cam, cell][:, np.arange(POINTS) % PILLARS] # [N, 8, 2]blk = (a[:, None] * wh[None, :, None, :] - np.float32(0.5)) * np.float32(65536.0) # [N, L, 8, 2]base = np.full((r_cap, LEVELS * 16), FAR, np.float32)base[dst] = blk.reshape(len(dst), LEVELS * 16)sca_index = np.full((1, r_cap), Q, np.uint32)sca_index[0, dst] = cellcams_of = np.zeros(Q, np.int64)gather = np.full((k_cams, Q), r_cap, np.uint32)ends = np.zeros((1, 1, 1, 16), np.uint32)for v, r in enumerate(rows):slot = cams_of[r]if len(r) and slot.max() >= k_cams:raise ValueError(f"frame_geometry: a cell is seen by more than {k_cams} cameras")gather[slot, r] = np.arange(starts[v], starts[v] + len(r), dtype=np.uint32)cams_of[r] += 1ends[0, 0, 0, v] = (starts[v] + seg_rows[v]) // 32ends[0, 0, 0, V:8] = r_cap // 32# the last segment owns the padding blocks after it (its rows there are padding: cell Q, FAR positions)ends[0, 0, 0, V - 1] = r_cap // 32cnt = cams_of.astype(np.float32)scale = (1.0 / np.maximum(cnt, 1.0)).reshape(Q, 1).astype(np.float32)observed = (cnt > 0).astype(np.float32).reshape(Q, 1)return FrameGeometry(sca_index, base, ends, seg_rows, gather, scale, observed, counts)CM_SLOTS = 2 # cameras per cell of the cell-major cross-attention (KITScenes / the synthetic rig: at most 2)@dataclassclass CmGeometry:"""The cell-major cross-attention's per-frame geometry (``tt/msda_cm.py``): ``table`` ``[Q, 32]`` int32 (per slotk the 4 anchors as ``round(uv * 2^(16 + smax))`` in columns ``8 k + 2 a + (x, y)``, the camera in ``16 + k`` (-1:none), the count in 18), ``observed`` ``[Q, 1]`` float32 (1 where a camera sees the cell), ``counts`` per camera."""table: np.ndarrayobserved: np.ndarrayvisible_rows: List[int]def cm_geometry(P: np.ndarray, image: int = 512, *, slots: int = CM_SLOTS) -> CmGeometry:"""``P`` ``[V, 3, 4]`` -> :class:`CmGeometry`. Slot k of a cell is its k-th visible camera (ascending camera order,the order of upstream's sum over the cameras). Anchors far outside are clamped to |uv| <= 64 (still outside everymap: their points read nothing). Raises if a cell is seen by more than ``slots`` cameras (the rebatched pathhandles up to ``K_CAMS``)."""import torchuv, mask = reference_points(torch.as_tensor(np.asarray(P, np.float32)), image)uv = uv.numpy() # [V, Q, 4, 2] float32vis = mask.numpy().any(-1) # [V, Q]cnt = vis.sum(0)if cnt.max(initial=0) > slots:raise ValueError(f"cm_geometry: a cell is seen by {int(cnt.max())} cameras (> {slots} slots)")smax = int(round(np.log2(level_sizes(image)[0][1])))scale = float(1 << (16 + smax))table = np.zeros((Q, 32), np.int32)table[:, 16:16 + slots] = -1slot = np.cumsum(vis, axis=0) - 1 # [V, Q]: the slot of a visible (camera, cell)for v in range(vis.shape[0]):cells = np.flatnonzero(vis[v])if not len(cells):continueu = np.round(np.clip(uv[v, cells].astype(np.float64), -64.0, 64.0) * scale).astype(np.int64) # [n, 4, 2]k = slot[v, cells]for s in range(slots):sel = k == stable[cells[sel], 8 * s:8 * s + 8] = u[sel].reshape(-1, 8).astype(np.int32)table[cells[sel], 16 + s] = vtable[:, 18] = cntobserved = (cnt > 0).astype(np.float32).reshape(Q, 1)return CmGeometry(table, observed, [int(x) for x in vis.sum(1)])def use_cm() -> bool:"""The BEV frames' cross-attention form: cell-major (``tt/msda_cm.py``, default) or rebatched (``AE_CM=0``)."""import osreturn os.environ.get("AE_CM", "1") != "0"def bev_geometry(P: np.ndarray, image: int = 512):"""The geometry of one BEV frame for the encoder's form: :class:`CmGeometry` (cell-major) or:class:`FrameGeometry` (rebatched)."""return cm_geometry(P, image) if use_cm() else frame_geometry(P, image)def tsa_base() -> np.ndarray:
48 unmodified lines4950515253545526 unmodified lines828384858687884 unmodified lines9394959697989910048 unmodified linesargs = ap.parse_args(argv)from ..api import AutoE2E, COLUMNSfrom ..host import head as Hfrom ..host.geometry import frame_geometryfrom ..tt.fusion import FRONT_CAPfrom ..tt.image import backbone_input26 unmodified linescams = backbone_input(g["camera_tiles"][0])for _ in range(7):model.dev.push(cams)geo = frame_geometry(P, 512)gf = frame_geometry(g["front_camera_projection_matrix"][0], 1024, r_cap=FRONT_CAP, k_cams=1)nav, _ = H.navigation(model.state, g["map_context"][0], g["route_mask"][0], bool(g["map_valid"][0]),bool(g["route_valid"][0]))4 unmodified linesres["api_vs_runner_controls_rel_l2"] = float(np.linalg.norm(api_ctrl - ref_ctrl) / np.linalg.norm(ref_ctrl))res["projection_max_abs_err_px"] = Nonemodel.stream_id = None # the direct runner calls changed the ring: start the stream oversteps = [call(True).meta["history_steps"]] + [call(False).meta["history_steps"] for _ in range(2)]res["history_steps_sequence"] = stepsres["columns"] = list(COLUMNS)res["first_poses"] = out.poses[:3].round(4).tolist()finally:48 unmodified lines4950515253545526 unmodified lines828384858687884 unmodified lines9394959697989910010110210348 unmodified linesargs = ap.parse_args(argv)from ..api import AutoE2E, COLUMNSfrom ..host import head as Hfrom ..host.geometry import bev_geometry, frame_geometryfrom ..tt.fusion import FRONT_CAPfrom ..tt.image import backbone_input26 unmodified linescams = backbone_input(g["camera_tiles"][0])for _ in range(7):model.dev.push(cams)geo = bev_geometry(P, 512)gf = frame_geometry(g["front_camera_projection_matrix"][0], 1024, r_cap=FRONT_CAP, k_cams=1)nav, _ = H.navigation(model.state, g["map_context"][0], g["route_mask"][0], bool(g["map_valid"][0]),bool(g["route_valid"][0]))4 unmodified linesres["api_vs_runner_controls_rel_l2"] = float(np.linalg.norm(api_ctrl - ref_ctrl) / np.linalg.norm(ref_ctrl))res["projection_max_abs_err_px"] = Nonemodel.stream_id = None # the direct runner calls changed the ring: start the stream overouts = [call(True)] + [call(False) for _ in range(3)]res["history_steps_sequence"] = [o.meta["history_steps"] for o in outs[:3]]# a streaming call (no reset: one image branch, 8 BEV frames, the navigation BEV overlapped)res["stream_timing_ms"] = {k: round(float(np.median([o.timing_ms[k] for o in outs[1:]])), 1)for k in outs[1].timing_ms}res["columns"] = list(COLUMNS)res["first_poses"] = out.poses[:3].round(4).tolist()finally:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135# SPDX-License-Identifier: Apache-2.0"""Where ``msda_cm``'s time goes (bin/devrun): the real inputs of layer 1's cross-attention on the golden frame(captured while the encoder runs), the kernel timed as is and with parts switched off (debug defines; the outputs ofthose are wrong by design, only the times matter):
- ``rdnone``: the reader hands over the pages without work (compute alone); ``cpnone``: the compute consumes them without work (reader alone); ``noread``: no value reads;- with ``rdnone``: ``now`` (no weights), ``notl`` (no tilize), ``nomul`` (no product), ``nosteps``;- ``new_hifi3``: HiFi3 products (compared with the HiFi4 output).
bin/devrun python -m tt_autoe2e.tests.dev_cm_probe [--out /logs/x.json] [--variants a,b,..]"""from __future__ import annotations
import argparseimport globimport jsonimport osimport time
import numpy as np
CKPT = "/ae2e/881e6a8367746da1eaae044a68077d0e7ce6fc1b/models/kitscenes-epoch-5/checkpoint.pt"
VARIANTS = { "new": (), "new_hifi3": ("fid:HiFi3",), "rdnone": ("rdnone",), "cpnone": ("cpnone",), "cpnone_noread": ("cpnone", "noread"), "rdnone_cpnone": ("rdnone", "cpnone"), "rdnone_now": ("rdnone", "now"), "rdnone_notl": ("rdnone", "notl"), "rdnone_nomul": ("rdnone", "nomul"), "rdnone_nosteps": ("rdnone", "nosteps"),}EXACT = ("new", "new_hifi3")
def main(argv=None) -> int: ap = argparse.ArgumentParser() ap.add_argument("--out", default="/logs/cm_probe.json") ap.add_argument("--variants", default=",".join(VARIANTS)) ap.add_argument("--reps", type=int, default=5) args = ap.parse_args(argv) import torch import ttnn
from ..host.geometry import bev_geometry from ..reference.tree import load_tree from ..tt import encoder as E from ..tt.encoder import TtBevEncoder from ..ttaw.device import DeviceConfig, close_device
names = [v for v in args.variants.split(",") if v] gpath = glob.glob("/ae2e/ref/autoe2e_kitscenes_epoch5_*f000045.npz")[0] g = np.load(gpath) inter = np.load(gpath.replace(".npz", "_intermediates.npz")) tree = load_tree(CKPT) geo = bev_geometry(g["camera_projection_matrix"][0], 512) feats = [inter[f"fpn_current_l{i}"] for i in range(4)] res = {"variants_ms": {}, "exact_vs_new": {}} dev = DeviceConfig(trace_region_size=64 << 20).open() orig = E.msda_cm state = {"n": 0}
def run(maps, loc, att, table, dbg): fid = next((d[4:] for d in dbg if d.startswith("fid:")), None) dbg = tuple(d for d in dbg if not d.startswith("fid:")) old = os.environ.get("AE_MSDA_FIDELITY") if fid: os.environ["AE_MSDA_FIDELITY"] = fid try: return orig(maps, loc, att, table, debug=dbg) finally: if fid: if old is None: os.environ.pop("AE_MSDA_FIDELITY", None) else: os.environ["AE_MSDA_FIDELITY"] = old
def variants(maps, loc, att, table): ref = None for name in names: dbg = VARIANTS[name] o = run(maps, loc, att, table, dbg) ttnn.synchronize_device(dev) if name in EXACT: a = ttnn.to_torch(o).float().numpy() if name == "new": ref = a elif ref is not None: d = np.abs(a - ref) res["exact_vs_new"][name] = {"identical": bool(np.array_equal(a, ref)), "max_abs": float(d.max()), "rel_l2": float(np.linalg.norm(a - ref) / np.linalg.norm(ref))} ttnn.deallocate(o) ts = [] for _ in range(args.reps): t = time.perf_counter() o = run(maps, loc, att, table, dbg) ttnn.synchronize_device(dev) ts.append(time.perf_counter() - t) ttnn.deallocate(o) res["variants_ms"][name] = round(float(np.median(ts)) * 1e3, 3) print(name, res["variants_ms"][name], "ms", flush=True)
def hook(maps, loc, att, table, **kw): state["n"] += 1 if state["n"] == 2: # layer 1: offsets / weights from the real query variants(maps, loc, att, table) return orig(maps, loc, att, table, **kw)
try: enc = TtBevEncoder(dev, tree) up = lambda a: ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(a, np.float32)), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev) levels = [up(f.transpose(0, 2, 3, 1).reshape(1, 1, -1, 256)) for f in feats] gd = enc.upload_geometry(geo) E.msda_cm = hook out = enc.frame(levels, gd) ttnn.synchronize_device(dev) ttnn.deallocate(out) finally: E.msda_cm = orig close_device(dev) with open(args.out, "w") as f: json.dump(res, f, indent=1) print(json.dumps(res, indent=1)) return 0
if __name__ == "__main__": raise SystemExit(main())37 unmodified lines383940414243448 unmodified lines5354555657585937 unmodified linesimport torchimport ttnnfrom ..host.geometry import frame_geometryfrom ..reference.port_form import PortForm, Qfrom ..reference.tree import load_treefrom ..tt.encoder import TtBevEncoder8 unmodified linesfeats = [inter[f"fpn_current_l{i}"] for i in range(4)] # [6, 256, h, w]res = {"golden": os.path.basename(gpath)}t = time.perf_counter()geo = frame_geometry(P, 512)res["geometry_s"] = time.perf_counter() - tres["visible_rows"] = geo.visible_rowspf_trace = None37 unmodified lines383940414243448 unmodified lines5354555657585937 unmodified linesimport torchimport ttnnfrom ..host.geometry import bev_geometry, frame_geometryfrom ..reference.port_form import PortForm, Qfrom ..reference.tree import load_treefrom ..tt.encoder import TtBevEncoder8 unmodified linesfeats = [inter[f"fpn_current_l{i}"] for i in range(4)] # [6, 256, h, w]res = {"golden": os.path.basename(gpath)}t = time.perf_counter()geo = bev_geometry(P, 512)res["geometry_s"] = time.perf_counter() - tres["visible_rows"] = geo.visible_rowspf_trace = None
35 unmodified lines3637383940414230 unmodified lines7374757677787935 unmodified linesimport torchfrom ..host import head as Hfrom ..host.geometry import frame_geometryfrom ..reference.tree import load_treefrom ..tt.fusion import FRONT_CAPfrom ..tt.image import state_dict_of30 unmodified linestm["prime_s"] += time.perf_counter() - ttm["primes"] += 1t = time.perf_counter()geos = [frame_geometry(z["P_hist"][k], 512) for k in range(7)] + [frame_geometry(z["P"], 512)]gf = frame_geometry(z["P_front"], 1024, r_cap=FRONT_CAP, k_cams=1)nav, _ = H.navigation(state, z["map_context"], z["route_mask"], bool(z["map_valid"]),bool(z["route_valid"]))35 unmodified lines3637383940414230 unmodified lines7374757677787935 unmodified linesimport torchfrom ..host import head as Hfrom ..host.geometry import bev_geometry, frame_geometryfrom ..reference.tree import load_treefrom ..tt.fusion import FRONT_CAPfrom ..tt.image import state_dict_of30 unmodified linestm["prime_s"] += time.perf_counter() - ttm["primes"] += 1t = time.perf_counter()geos = [bev_geometry(z["P_hist"][k], 512) for k in range(7)] + [bev_geometry(z["P"], 512)]gf = frame_geometry(z["P_front"], 1024, r_cap=FRONT_CAP, k_cams=1)nav, _ = H.navigation(state, z["map_context"], z["route_mask"], bool(z["map_valid"]),bool(z["route_valid"]))
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102# SPDX-License-Identifier: Apache-2.0"""Device-profiler view of one BEV frame (bin/devrun, TT_METAL_DEVICE_PROFILER=1, AE_MSDA_DEBUG=timing): everyprogram of the frame with its kernel time (max over cores), and for the msda calls the per-RISC phase timers.
TT_METAL_DEVICE_PROFILER=1 AE_MSDA_DEBUG=timing bin/devrun python -m tt_autoe2e.tests.dev_frame_prof --out /logs/x.json"""from __future__ import annotations
import argparseimport csvimport globimport jsonimport osimport shutilfrom collections import defaultdict
import numpy as np
CKPT = "/ae2e/881e6a8367746da1eaae044a68077d0e7ce6fc1b/models/kitscenes-epoch-5/checkpoint.pt"PHASES = ("res", "hdr", "loop", "bar", "out", "geo", "in", "w", "tl", "st", "fin", "acq", "pw")
def parse(path): starts, spans, data, names = {}, defaultdict(list), defaultdict(list), {} with open(path) as f: f.readline() rd = csv.reader(f) hdr = [h.strip() for h in next(rd)] ix = {h: i for i, h in enumerate(hdr)} for row in rd: row = [c.strip() for c in row] zone, run = row[ix["zone name"]], row[ix["run host ID"]] risc = row[ix["RISC processor type"]] if zone in PHASES: data[(run, risc, zone)].append(int(row[ix["data"]])) continue if not zone.endswith("-KERNEL"): continue src = row[ix.get("source file", 12)] if len(row) > 12 else "" key = (row[ix["core_x"]], row[ix["core_y"]], risc, run) t = int(row[ix["time[cycles since reset]"]]) if row[ix["type"]] == "ZONE_START": starts[key] = t elif key in starts: spans[run].append(t - starts.pop(key)) if src and "kernels" in src: names.setdefault(run, set()).add(os.path.basename(src)) return spans, data, names
def main(argv=None) -> int: ap = argparse.ArgumentParser() ap.add_argument("--out", default="/logs/prof/frame_prof.json") args = ap.parse_args(argv) import torch import ttnn
from ..host.geometry import bev_geometry, frame_geometry from ..reference.port_form import Q from ..reference.tree import load_tree from ..tt.encoder import TtBevEncoder from ..ttaw.device import DeviceConfig, close_device
gpath = glob.glob("/ae2e/ref/autoe2e_kitscenes_epoch5_*f000045.npz")[0] g = np.load(gpath) inter = np.load(gpath.replace(".npz", "_intermediates.npz")) tree = load_tree(CKPT) geo = bev_geometry(g["camera_projection_matrix"][0], 512) feats = [inter[f"fpn_current_l{i}"] for i in range(4)] dev = DeviceConfig(trace_region_size=64 << 20).open() try: enc = TtBevEncoder(dev, tree) up = lambda a: ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(a, np.float32)), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev) levels = [up(f.transpose(0, 2, 3, 1).reshape(1, 1, -1, 256)) for f in feats] gd = enc.upload_geometry(geo) for _ in range(2): out = enc.frame(levels, gd) ttnn.synchronize_device(dev) ttnn.deallocate(out) ttnn.ReadDeviceProfiler(dev) finally: close_device(dev) path = glob.glob("/opt/tt-metal/generated/profiler/.logs/profile_log_device.csv")[0] shutil.copy(path, args.out.replace(".json", ".csv")) spans, data, names = parse(path) runs = sorted(spans, key=lambda s: int(s)) half = runs[len(runs) // 2:] # the second frame rows = [] for r in half: ph = {f"{risc}.{z}": int(np.mean(v)) for (rr, risc, z), v in data.items() if rr == r} rows.append({"run": r, "kernel_max_cycles": int(max(spans[r])), "kernels": sorted(names.get(r, [])), **({"phases": ph} if ph else {})}) tot = sum(x["kernel_max_cycles"] for x in rows) res = {"programs": len(rows), "kernel_cycles_total": tot, "kernel_ms_total": round(tot / 1.35e6, 2), "rows": rows} with open(args.out, "w") as f: json.dump(res, f, indent=1) print(json.dumps({k: v for k, v in res.items() if k != "rows"})) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189# SPDX-License-Identifier: Apache-2.0"""Per-op device time of one encoder layer (layer 1) on random BEV rows (bin/devrun): every ttnn op of the layeroutside the two attention kernels, each run eagerly and synchronized (median of N), plus alternative forms(L1 outputs, sharded L1 row stages) for the same ops.
bin/devrun python -m tt_autoe2e.tests.dev_layer_ops [--out /logs/x.json]"""from __future__ import annotations
import argparseimport jsonimport time
import numpy as np
CKPT = "/ae2e/881e6a8367746da1eaae044a68077d0e7ce6fc1b/models/kitscenes-epoch-5/checkpoint.pt"
def main(argv=None) -> int: ap = argparse.ArgumentParser() ap.add_argument("--out", default="/logs/layer_ops.json") ap.add_argument("--reps", type=int, default=7) ap.add_argument("--sweep", action="store_true") ap.add_argument("--skip-ops", action="store_true") args = ap.parse_args(argv) import torch import ttnn
from ..reference.port_form import HEADS, Q from ..reference.tree import load_tree from ..tt.encoder import TtBevEncoder, linear_l1 from ..ttaw.device import DeviceConfig, close_device
tree = load_tree(CKPT) dev = DeviceConfig(trace_region_size=64 << 20).open() res = {} try: enc = TtBevEncoder(dev, tree) L = enc.layers[1] rng = np.random.default_rng(0) up = lambda a, dt=ttnn.bfloat16, mc=ttnn.DRAM_MEMORY_CONFIG: ttnn.from_torch( torch.from_numpy(np.ascontiguousarray(a, np.float32)), dtype=dt, layout=ttnn.TILE_LAYOUT, device=dev, memory_config=mc) q = up(rng.standard_normal((1, 1, Q, 256))) q2 = up(rng.standard_normal((1, 1, Q, 256))) h512 = up(rng.standard_normal((1, 1, Q, 512))) f512 = up(rng.standard_normal((1, 1, Q, 512)), ttnn.float32) f256 = up(rng.standard_normal((1, 1, Q, 256)), ttnn.float32) f128 = up(rng.standard_normal((1, 1, Q, 128)), ttnn.float32)
def timed(name, fn): o = fn() ttnn.synchronize_device(dev) outs = o if isinstance(o, (list, tuple)) else [o] for x in outs: ttnn.deallocate(x) ts = [] for _ in range(args.reps): t = time.perf_counter() o = fn() ttnn.synchronize_device(dev) ts.append(time.perf_counter() - t) outs = o if isinstance(o, (list, tuple)) else [o] for x in outs: ttnn.deallocate(x) res[name] = round(float(np.median(ts)) * 1e3, 3) print(f"{name:40s} {res[name]:8.3f} ms", flush=True)
timed("noop_sync", lambda: ttnn.add(q, q2, memory_config=ttnn.DRAM_MEMORY_CONFIG)) run_op = timed if not args.skip_ops else (lambda name, fn: None) # ---- TSA run_op("tsa.off linear 256->128 fp32", lambda: L.tsa_off(q)) run_op("tsa.off add const fp32", lambda: ttnn.add(f128, L.tsa_off_dev, memory_config=ttnn.DRAM_MEMORY_CONFIG)) run_op("tsa.off typecast int32 [Q,128]", lambda: ttnn.typecast(f128, ttnn.int32)) run_op("tsa.att linear 256->64 fp32", lambda: L.tsa_att(q)) run_op("tsa.v linear L1", lambda: linear_l1(L.tsa_v, q)) run_op("tsa.out linear 512->256", lambda: L.tsa_out(h512)) # ---- SCA run_op("sca.off linear 256->512 fp32", lambda: L.sca_off(q)) run_op("sca.off typecast int32 [Q,512]", lambda: ttnn.typecast(f512, ttnn.int32)) run_op("sca.att linear 256->256 fp32", lambda: L.sca_att(q)) run_op("sca.att heads [Q,256]->[8,Q,32] fp32", lambda: enc._heads(f256, HEADS)) lh = enc._heads(f256, HEADS) run_op("sca.att softmax fp32 [8,Q,32]", lambda: ttnn.softmax(lh, dim=-1, compute_kernel_config=enc.cfg)) ttnn.deallocate(lh) run_op("sca.out linear 256->256", lambda: L.sca_out(q)) # ---- LN / FFN run_op("ln residual", lambda: L.norms[1](q2, residual=q, cfg=enc.cfg)) run_op("ffn1 256->512 relu", lambda: L.ffn1(q)) run_op("ffn2 512->256", lambda: L.ffn2(h512)) # ---- references for the memory-traffic floor run_op("copy [Q,256] bf16 dram->dram", lambda: ttnn.clone(q, memory_config=ttnn.DRAM_MEMORY_CONFIG)) run_op("copy [Q,512] fp32 dram->dram", lambda: ttnn.clone(f512, memory_config=ttnn.DRAM_MEMORY_CONFIG)) def sweep(): # ---- explicit matmul program configs (the same math: K blocks accumulate in fp32 DEST / L1) g = dev.compute_with_storage_grid_size() gx, gy = int(g.x), int(g.y) M = -(-Q // 32)
def pc1d(K, N, ibw, obh, sbh, sbw, act=None): pcm = -(-M // (gx * gy)) return ttnn.MatmulMultiCoreReuseMultiCast1DProgramConfig( compute_with_storage_grid_size=ttnn.CoreCoord(gx, gy), in0_block_w=ibw, out_subblock_h=sbh, out_subblock_w=sbw, out_block_h=obh, out_block_w=N, per_core_M=pcm, per_core_N=N, fuse_batch=True, fused_activation=act, mcast_in0=False)
def pc2d(K, N, ibw, nx, obh, sbh, sbw, act=None): pcn = N // nx pcm = -(-M // gy) return ttnn.MatmulMultiCoreReuseMultiCastProgramConfig( compute_with_storage_grid_size=ttnn.CoreCoord(nx, gy), in0_block_w=ibw, out_subblock_h=sbh, out_subblock_w=sbw, out_block_h=obh, out_block_w=pcn, per_core_M=pcm, per_core_N=pcn, transpose_mcast=False, fused_activation=act)
relu = ttnn.UnaryWithParam(ttnn.UnaryOpType.RELU) cases = [("sca.off", L.sca_off, q, 8, 16, ttnn.float32, None), ("sca.att", L.sca_att, q, 8, 8, ttnn.float32, None), ("sca.out", L.sca_out, q, 8, 8, ttnn.bfloat16, None), ("ffn1", L.ffn1, q, 8, 16, ttnn.bfloat16, relu), ("ffn2", L.ffn2, h512, 16, 8, ttnn.bfloat16, None), ("tsa.out", L.tsa_out, h512, 16, 8, ttnn.bfloat16, None), ("tsa.off", L.tsa_off, q, 8, 4, ttnn.float32, None)] for name, lin, x, K, N, odt, act in cases: w, b, grid, cfg = lin._device or lin._upload(dev) cands = [] for ibw in (2, 4, 8): if K % ibw: continue for obh in (2, 4, 8, 16): sbw = min(N, 4) while N % sbw: sbw -= 1 sbh = max(1, 4 // sbw) while obh % sbh: sbh -= 1 cands.append((f"1d ibw{ibw} obh{obh} sb{sbh}x{sbw}", pc1d(K, N, ibw, obh, sbh, sbw, act))) for nx in (2, 4, 8): if N % nx: continue pcn = N // nx pcm = -(-M // gy) for ibw in (2, 4, 8): if K % ibw: continue for obh in (2, 4, 8): if pcm % obh: continue sbw = min(pcn, 4) while pcn % sbw: sbw -= 1 sbh = max(1, 4 // sbw) while obh % sbh: sbh -= 1 cands.append((f"2d nx{nx} ibw{ibw} obh{obh} sb{sbh}x{sbw}", pc2d(K, N, ibw, nx, obh, sbh, sbw, act))) for cname, pc in cands: try: timed(f"{name} {cname}", lambda: ttnn.linear(x, w, bias=b, program_config=pc, compute_kernel_config=cfg, dtype=odt, memory_config=ttnn.DRAM_MEMORY_CONFIG)) except Exception as e: # noqa: BLE001 - invalid configs are part of the sweep res[f"{name} {cname}"] = f"error: {str(e).splitlines()[0][:120]}" print(name, cname, "error", flush=True) ref = lin(x) best = min((k for k in res if k.startswith(name + " ") and isinstance(res[k], float)), key=res.get, default=None) if best is not None: cname = best[len(name) + 1:] pc = dict(cands)[cname] o = ttnn.linear(x, w, bias=b, program_config=pc, compute_kernel_config=cfg, dtype=odt, memory_config=ttnn.DRAM_MEMORY_CONFIG) a, r = ttnn.to_torch(o).float().numpy(), ttnn.to_torch(ref).float().numpy() res[f"{name} best"] = {"config": cname, "ms": res[best], "identical_to_default": bool(np.array_equal(a, r)), "max_abs": float(np.abs(a - r).max())} print(name, "best", res[f"{name} best"], flush=True) ttnn.deallocate(o) ttnn.deallocate(ref)
if args.sweep: sweep() finally: close_device(dev) with open(args.out, "w") as f: json.dump(res, f, indent=1) return 0
if __name__ == "__main__": raise SystemExit(main())44 unmodified lines4546474849505152535 unmodified lines59606162636444 unmodified linesttnn.deallocate(pm)res["pair_maps_build"] = round((time.perf_counter() - t) / 5 * 1e3, 3)for name, dbg, v in (("full", (), value), ("noread", ("noread",), value), ("nosteps", ("nosteps",), value),("pairs", (), pairs), ("pairs_noread", ("noread",), pairs)):fn = lambda: msda(v, loc_t, att_t, points=P, nq=rows, segments=[0] * 6, seg_table=seg_t, loc_hs=64,loc_off=0, att_col0=0, debug=dbg)o = fn()ttnn.synchronize_device(dev)ttnn.deallocate(o)5 unmodified linests.append(time.perf_counter() - t)ttnn.deallocate(o)res[name] = round(float(np.median(ts)) * 1e3, 3)print(name, res[name], "ms", flush=True)finally:close_device(dev)44 unmodified lines45464748495051525354555657585 unmodified lines64656667686970717273747576777844 unmodified linesttnn.deallocate(pm)res["pair_maps_build"] = round((time.perf_counter() - t) / 5 * 1e3, 3)for name, dbg, v in (("full", (), value), ("noread", ("noread",), value), ("nosteps", ("nosteps",), value),("pairs", (), pairs), ("pairs_noread", ("noread",), pairs),("pairs_nosteps", ("nosteps",), pairs), ("pairs_noread_nosteps", ("noread", "nosteps"), pairs),("pairs_hifi2", ("fid:HiFi2",), pairs), ("pairs_lofi", ("fid:LoFi",), pairs),("pairs_noread_hifi2", ("noread", "fid:HiFi2"), pairs)):fid = next((d[4:] for d in dbg if d.startswith("fid:")), None)dbg = tuple(d for d in dbg if not d.startswith("fid:"))fn = lambda: msda(v, loc_t, att_t, points=P, nq=rows, segments=[0] * 6, seg_table=seg_t, loc_hs=64,loc_off=0, att_col0=0, debug=dbg, fidelity=fid)o = fn()ttnn.synchronize_device(dev)ttnn.deallocate(o)5 unmodified linests.append(time.perf_counter() - t)ttnn.deallocate(o)res[name] = round(float(np.median(ts)) * 1e3, 3)if v is pairs and not dbg:o = fn()out = ttnn.to_torch(o).float().numpy()ttnn.deallocate(o)if fid is None:ref_out = outelse:res[name + "_vs_hifi4_max_abs"] = float(np.abs(out - ref_out).max())res[name + "_vs_hifi4_identical"] = bool(np.array_equal(out, ref_out))print(name, res[name], "ms", flush=True)finally:close_device(dev)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102# SPDX-License-Identifier: Apache-2.0"""Per-RISC kernel time of one SCA level call (bin/devrun with TT_METAL_DEVICE_PROFILER=1): the device profiler'skernel zones of the reader (NCRISC), writer (BRISC) and the three compute TRISCs, max / mean over cores.
TT_METAL_DEVICE_PROFILER=1 bin/devrun python -m tt_autoe2e.tests.dev_msda_riscs [--out-frac 0.6] [--hw 8]"""from __future__ import annotations
import argparseimport csvimport globimport jsonimport osimport shutilfrom collections import defaultdict
import numpy as np
def main(argv=None) -> int: ap = argparse.ArgumentParser() ap.add_argument("--hw", type=int, default=64) ap.add_argument("--out-frac", type=float, default=0.0, help="fraction of points placed fully outside the map") ap.add_argument("--tag", default="riscs") args = ap.parse_args(argv) import torch import ttnn
from ..tt.msda_k import msda from ..tt.pairmap import pair_maps from ..ttaw.device import DeviceConfig, close_device
rng = np.random.default_rng(0) dev = DeviceConfig(trace_region_size=32 << 20).open() res = {"hw": args.hw, "out_frac": args.out_frac} try: rows, heads, P, hw = 98304, 8, 8, args.hw segs = [29568 + 1152, 14944, 15648, 9696, 9472, 9696 + 8128] segs = [s - s % 32 for s in segs] segs[-1] += rows - sum(segs) loc = rng.uniform(-0.5, hw - 0.5, size=(1, 1, rows, heads * 64)) out = rng.uniform(size=loc.shape) < args.out_frac loc[out] = -50.0 loc = np.round(loc * 65536).astype(np.int32) att = rng.uniform(0, 1, size=(1, heads, rows, 32)).astype(np.float32) loc_t = ttnn.from_torch(torch.from_numpy(loc), dtype=ttnn.int32, layout=ttnn.TILE_LAYOUT, device=dev) att_t = ttnn.from_torch(torch.from_numpy(att), dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT, device=dev) ends = np.zeros((1, 1, 1, 16), np.int32) ends[0, 0, 0, :6] = np.cumsum(segs) // 32 seg_t = ttnn.from_torch(torch.from_numpy(ends), dtype=ttnn.uint32, layout=ttnn.ROW_MAJOR_LAYOUT, device=dev) proj = ttnn.from_torch(torch.randn(1, 1, 6 * hw * hw, 256), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev, memory_config=ttnn.L1_MEMORY_CONFIG) pairs = pair_maps(proj, heads=8, sub=6, hw=(hw, hw)) for _ in range(3): o = msda(pairs, loc_t, att_t, points=P, nq=rows, segments=[0] * 6, seg_table=seg_t, loc_hs=64, loc_off=0, att_col0=0, debug=("timing",)) ttnn.synchronize_device(dev) ttnn.deallocate(o) ttnn.ReadDeviceProfiler(dev) finally: close_device(dev) logs = glob.glob("/opt/tt-metal/generated/profiler/.logs/profile_log_device.csv") if not logs: print("no profiler log") return 1 shutil.copy(logs[0], f"/logs/{args.tag}_profile_log_device.csv") # rows: PCIe slot, core_x, core_y, RISC processor type, timer_id, time[cycles since reset], data, run host ID, # zone name, type (ZONE_START / ZONE_END), source line, source file, meta starts, spans, data = {}, defaultdict(list), defaultdict(list) with open(logs[0]) as f: f.readline() # ARCH / chip freq line rd = csv.reader(f) hdr = [h.strip() for h in next(rd)] ix = {h: i for i, h in enumerate(hdr)} for row in rd: row = [c.strip() for c in row] zone = row[ix.get("zone name", 8)] if zone in ("res", "hdr", "loop", "bar", "out", "geo", "in", "w", "tl", "st", "fin"): data[(row[ix["RISC processor type"]], zone, row[ix.get("run host ID", 7)])].append(int(row[ix["data"]])) continue if not zone.endswith("-KERNEL"): continue key = (row[ix["core_x"]], row[ix["core_y"]], row[ix["RISC processor type"]], zone, row[ix.get("run host ID", 7)]) t = int(row[ix["time[cycles since reset]"]]) if row[ix.get("type", 9)] == "ZONE_START": starts[key] = t elif key in starts: spans[(key[2], key[4])].append(t - starts.pop(key)) runs = sorted({k[1] for k in spans}, key=lambda s: int(s) if s.isdigit() else s) last = runs[-1] if runs else None res["per_risc_cycles_last_run"] = {k[0]: {"max": int(max(v)), "mean": int(np.mean(v)), "cores": len(v)} for k, v in spans.items() if k[1] == last} res["timing_cycles_mean_last_run"] = {f"{k[0]}.{k[1]}": int(np.mean(v)) for k, v in data.items() if k[2] == last} res["data_types_seen"] = sorted({k[2] for k in data})[:3] print(json.dumps(res, indent=1)) with open(f"/logs/{args.tag}.json", "w") as f: json.dump(res, f, indent=1) return 0
if __name__ == "__main__": raise SystemExit(main())93 unmodified lines94959697989910010110210310410510610710810922 unmodified lines13213313413513613730 unmodified lines16816917017117217317493 unmodified linespdev = ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(proj)), dtype=ttnn.bfloat16,layout=ttnn.TILE_LAYOUT, device=dev, memory_config=ttnn.L1_MEMORY_CONFIG)pairs = pair_maps(pdev, heads=heads, sub=6, hw=(h, w))ttnn.deallocate(pdev)for lvl in (0, 3):exp = emulate(value, locq[:, :, lvl], att[:, :, 8 * lvl:8 * lvl + 8], heads=heads, points=P,seg_rows=seg_rows, hdiv=1, map_of_head=lambda j: j)for tag, v in (("", vdev), ("_pairs", pairs)):out = msda(v, loc_dev, att_dev, points=P, nq=cap, segments=[0] * 6, seg_table=seg_dev,loc_hs=64, loc_off=16 * lvl, att_col0=8 * lvl)got = ttnn.to_torch(out).float().numpy().reshape(cap, heads * 32)res[f"{case}_level{lvl}{tag}"] = rel(got, exp)ttnn.deallocate(out)# joint softmax over a head's 32 logits + fp32 offsets with the anchor table added in the kernellogits = rng.standard_normal((cap, heads, 32)).astype(np.float32)e = np.exp(logits - logits.max(-1, keepdims=True))22 unmodified linesfor t in (lg_dev, off_dev, base_dev):ttnn.deallocate(t)ttnn.deallocate(pairs)for t in (loc_dev, att_dev, seg_dev):ttnn.deallocate(t)ttnn.deallocate(vdev)30 unmodified linesres["tsa_pairs_softmax"] = rel(got, exp)finally:close_device(dev)ok = all(v < 4e-3 for v in res.values())print(json.dumps(res, indent=1))print("PASS" if ok else "FAIL")return 0 if ok else 193 unmodified lines94959697989910010110210310410510610710810911011111211311422 unmodified lines13713813914014114214330 unmodified lines17417517617717817918093 unmodified linespdev = ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(proj)), dtype=ttnn.bfloat16,layout=ttnn.TILE_LAYOUT, device=dev, memory_config=ttnn.L1_MEMORY_CONFIG)pairs = pair_maps(pdev, heads=heads, sub=6, hw=(h, w))quads = pair_maps(pdev, heads=heads, sub=6, hw=(h, w), quad=True)ttnn.deallocate(pdev)for lvl in (0, 3):exp = emulate(value, locq[:, :, lvl], att[:, :, 8 * lvl:8 * lvl + 8], heads=heads, points=P,seg_rows=seg_rows, hdiv=1, map_of_head=lambda j: j)outs = {}for tag, v in (("", vdev), ("_pairs", pairs), ("_quads", quads)):out = msda(v, loc_dev, att_dev, points=P, nq=cap, segments=[0] * 6, seg_table=seg_dev,loc_hs=64, loc_off=16 * lvl, att_col0=8 * lvl)got = ttnn.to_torch(out).float().numpy().reshape(cap, heads * 32)res[f"{case}_level{lvl}{tag}"] = rel(got, exp)outs[tag] = gotttnn.deallocate(out)# quads read the same sticks as pairs: identical outputs (a nonzero entry here fails the test)res[f"{case}_level{lvl}_quads_vs_pairs_max_abs"] = float(np.abs(outs["_quads"] - outs["_pairs"]).max())# joint softmax over a head's 32 logits + fp32 offsets with the anchor table added in the kernellogits = rng.standard_normal((cap, heads, 32)).astype(np.float32)e = np.exp(logits - logits.max(-1, keepdims=True))22 unmodified linesfor t in (lg_dev, off_dev, base_dev):ttnn.deallocate(t)ttnn.deallocate(pairs)ttnn.deallocate(quads)for t in (loc_dev, att_dev, seg_dev):ttnn.deallocate(t)ttnn.deallocate(vdev)30 unmodified linesres["tsa_pairs_softmax"] = rel(got, exp)finally:close_device(dev)ok = all((v == 0.0 if k.endswith("_quads_vs_pairs_max_abs") else v < 4e-3) for k, v in res.items())print(json.dumps(res, indent=1))print("PASS" if ok else "FAIL")return 0 if ok else 1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172# SPDX-License-Identifier: Apache-2.0"""Where a step's time goes (bin/devrun): eager blocks before capture, then the traced call split into hostconversion, host -> device copies, replay and readback, per input group.
bin/devrun python -m tt_autoe2e.tests.dev_prof [--out /logs/prof/dev_prof.json] [--no-eager]
Eager part (each block synchronized): the image branch on the 6 views and on the 1024 px front, one BEV frame(with the encoder's block profile), the front fusion, T8 on 8 BEVs, the map fusion. Traced part (golden sample,ring primed with its 7 history frames): the step's inputs as ``AutoE2EDevice.step`` builds them."""from __future__ import annotations
import argparseimport globimport jsonimport osimport timefrom collections import defaultdict
import numpy as np
CKPT = "/ae2e/881e6a8367746da1eaae044a68077d0e7ce6fc1b/models/kitscenes-epoch-5/checkpoint.pt"
def group_of(name: str) -> str: if "." in name: tag, field = name.split(".", 1) return "geo." + "".join(c for c in field if not c.isdigit()) return name
def main(argv=None) -> int: ap = argparse.ArgumentParser() ap.add_argument("--out", default="/logs/prof/dev_prof.json") ap.add_argument("--no-eager", action="store_true") args = ap.parse_args(argv) import torch import ttnn
from ..host import head as H from ..host.geometry import bev_geometry, frame_geometry from ..reference.port_form import E, Q from ..reference.tree import load_tree from ..tt.fusion import FRONT_CAP from ..tt.image import backbone_input, state_dict_of from ..tt.runner import DEVICE_DEFAULTS, AutoE2EDevice, geometry_inputs from ..ttaw.device import DeviceConfig, close_device from ..ttaw.ops.conv import FeatureMap from ..ttaw.trace import to_host_tensor
torch.set_num_threads(8) g = np.load(glob.glob("/ae2e/ref/autoe2e_kitscenes_epoch5_*f000045.npz")[0]) tree = load_tree(CKPT) state = state_dict_of(tree) Ps = [g["camera_history_projection_matrix"][0, k] for k in range(7)] + [g["camera_projection_matrix"][0]] t = time.perf_counter() geos = [bev_geometry(P, 512) for P in Ps] gf = frame_geometry(g["front_camera_projection_matrix"][0], 1024, r_cap=FRONT_CAP, k_cams=1) res = {"host_geometry_9_s": time.perf_counter() - t} t = time.perf_counter() nav, _ = H.navigation(state, g["map_context"][0], g["route_mask"][0], bool(g["map_valid"][0]), bool(g["route_valid"][0])) res["host_navigation_s"] = time.perf_counter() - t cams = backbone_input(g["camera_tiles"][0]) front = backbone_input(g["front_camera_tile"]) nav_rows = np.ascontiguousarray(nav.reshape(256, -1).T) dev = DeviceConfig(**DEVICE_DEFAULTS).open() sync = lambda: ttnn.synchronize_device(dev) try: m = AutoE2EDevice(dev, tree) if not args.no_eager: eg = {}
def timed(name, fn, reps=2): out = fn() # warm (program cache) sync() best = 1e9 for _ in range(reps): if isinstance(out, list): for o in out: ttnn.deallocate(o) else: ttnn.deallocate(out) t0 = time.perf_counter() out = fn() sync() best = min(best, time.perf_counter() - t0) eg[name] = round(best * 1e3, 2) return out
up_rm = lambda a: ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(a, np.float32)), dtype=ttnn.bfloat16, layout=ttnn.ROW_MAJOR_LAYOUT, device=dev) xc = up_rm(cams.reshape(1, 1, 6 * 512, 512 * 3)) xf = up_rm(front.reshape(1, 1, 1024, 1024 * 3)) fpn = timed("image_6x512", lambda: m._pyramid(xc, 6, 512)) ffr = timed("image_front_1024", lambda: m._pyramid(xf, 1, 1024)) gd = m.enc.upload_geometry(geos[7]) gdf = m.enc.upload_geometry(gf) bev = timed("bev_frame", lambda: m.enc.frame(fpn, gd)) m.enc.prof = {} o = m.enc.frame(fpn, gd) sync() ttnn.deallocate(o) eg["bev_frame_blocks"] = {k: round(v * 1e3, 2) for k, v in sorted(m.enc.prof.items(), key=lambda kv: -kv[1])} m.enc.prof = None curf = timed("front_fusion", lambda: m.front(bev, ffr, gdf)) t8 = timed("t8", lambda: m.t8([bev] * 7 + [curf])) navd = ttnn.from_torch(torch.from_numpy(nav_rows.reshape(1, 1, Q, E)), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev) fused = timed("map_fusion", lambda: m.mfuse(t8, navd)) for x in fpn + ffr + [bev, curf, t8, navd, fused, xc, xf]: ttnn.deallocate(x) res["eager_ms"] = eg print(json.dumps(eg, indent=1), flush=True) t = time.perf_counter() m.capture() res["capture_s"] = time.perf_counter() - t for k in range(7): m.push(backbone_input(g["camera_history_tiles"][0, k])) sync() R = m.runner inputs = {"cams": cams.reshape(1, 1, 6 * 512, 512 * 3), "front": front.reshape(1, 1, 1024, 1024 * 3), "nav": nav_rows.reshape(1, 1, Q, E)} for k, gg in enumerate(geos): inputs.update(geometry_inputs(f"f{k}", gg)) inputs.update(geometry_inputs("front", gf)) m.step(cams, front, geos, gf, nav_rows) # warm conv, h2d, nbytes = defaultdict(float), defaultdict(float), defaultdict(int) for name, value in inputs.items(): slot = R._slot(name, "input") t0 = time.perf_counter() host = to_host_tensor(value, slot.dtype, slot.layout, shape=slot.shape) t1 = time.perf_counter() ttnn.copy_host_to_device_tensor(host, slot.buffers[0], cq_id=0) sync() t2 = time.perf_counter() grp = group_of(name) conv[grp] += (t1 - t0) * 1e3 h2d[grp] += (t2 - t1) * 1e3 nbytes[grp] += int(np.asarray(value).nbytes) res["inputs_ms"] = {k: {"convert": round(conv[k], 2), "h2d": round(h2d[k], 2), "MB": round(nbytes[k] / 1e6, 2)} for k in sorted(conv, key=lambda k: -(conv[k] + h2d[k]))} res["inputs_total_ms"] = round(sum(conv.values()) + sum(h2d.values()), 1) tm = defaultdict(list) for _ in range(3): t0 = time.perf_counter() ups = R._collect_uploads(inputs, None) t1 = time.perf_counter() R._enqueue_uploads(ups) sync() t2 = time.perf_counter() R.run("step_a") R.run("step_b") sync() t3 = time.perf_counter() R.read("step_b") t4 = time.perf_counter() for k, v in (("convert", t1 - t0), ("h2d", t2 - t1), ("replay", t3 - t2), ("read", t4 - t3)): tm[k].append(v * 1e3) res["traced_ms"] = {k: round(float(np.median(v)), 1) for k, v in tm.items()} m.release() finally: close_device(dev) print(json.dumps(res, indent=1)) os.makedirs(os.path.dirname(args.out), exist_ok=True) with open(args.out, "w") as f: json.dump(res, f, indent=1) return 0
if __name__ == "__main__": raise SystemExit(main())28 unmodified lines2930313233343516 unmodified lines5253545556575823 unmodified lines8283848586878828 unmodified linesimport ttnnfrom ..host import head as Hfrom ..host.geometry import frame_geometryfrom ..reference.tree import load_treefrom ..tt.fusion import FRONT_CAPfrom ..tt.image import backbone_input, state_dict_of16 unmodified linesdef call():t0 = time.perf_counter()Ps = [g["camera_history_projection_matrix"][0, k] for k in range(7)] + [g["camera_projection_matrix"][0]]geos = [frame_geometry(P, 512) for P in Ps]gf = frame_geometry(g["front_camera_projection_matrix"][0], 1024, r_cap=FRONT_CAP, k_cams=1)nav, _ = H.navigation(state, g["map_context"][0], g["route_mask"][0], bool(g["map_valid"][0]),bool(g["route_valid"][0]))23 unmodified linesreps = []for _ in range(3):t = time.perf_counter()m.runner.run("step")ttnn.synchronize_device(dev)reps.append(time.perf_counter() - t)res["step_replay_s"] = float(np.median(reps))28 unmodified lines2930313233343516 unmodified lines5253545556575823 unmodified lines828384858687888928 unmodified linesimport ttnnfrom ..host import head as Hfrom ..host.geometry import bev_geometry, frame_geometryfrom ..reference.tree import load_treefrom ..tt.fusion import FRONT_CAPfrom ..tt.image import backbone_input, state_dict_of16 unmodified linesdef call():t0 = time.perf_counter()Ps = [g["camera_history_projection_matrix"][0, k] for k in range(7)] + [g["camera_projection_matrix"][0]]geos = [bev_geometry(P, 512) for P in Ps]gf = frame_geometry(g["front_camera_projection_matrix"][0], 1024, r_cap=FRONT_CAP, k_cams=1)nav, _ = H.navigation(state, g["map_context"][0], g["route_mask"][0], bool(g["map_valid"][0]),bool(g["route_valid"][0]))23 unmodified linesreps = []for _ in range(3):t = time.perf_counter()m.runner.run("step_a")m.runner.run("step_b")ttnn.synchronize_device(dev)reps.append(time.perf_counter() - t)res["step_replay_s"] = float(np.median(reps))
35 unmodified lines3637383940414213 unmodified lines5657585960616235 unmodified linesimport ttnnfrom ..host import head as Hfrom ..host.geometry import frame_geometryfrom ..reference.port_form import Qfrom ..reference.tree import load_treefrom ..tt.encoder import TtBevEncoder13 unmodified linesT = res["time_s"]t = time.perf_counter()Ps = [g["camera_history_projection_matrix"][0, k] for k in range(7)] + [g["camera_projection_matrix"][0]]geos = [frame_geometry(P, 512) for P in Ps]gfront = frame_geometry(g["front_camera_projection_matrix"][0], 1024, r_cap=FRONT_CAP, k_cams=1)T["host_geometry"] = time.perf_counter() - tt = time.perf_counter()35 unmodified lines3637383940414213 unmodified lines5657585960616235 unmodified linesimport ttnnfrom ..host import head as Hfrom ..host.geometry import bev_geometry, frame_geometryfrom ..reference.port_form import Qfrom ..reference.tree import load_treefrom ..tt.encoder import TtBevEncoder13 unmodified linesT = res["time_s"]t = time.perf_counter()Ps = [g["camera_history_projection_matrix"][0, k] for k in range(7)] + [g["camera_projection_matrix"][0]]geos = [bev_geometry(P, 512) for P in Ps]gfront = frame_geometry(g["front_camera_projection_matrix"][0], 1024, r_cap=FRONT_CAP, k_cams=1)T["host_geometry"] = time.perf_counter() - tt = time.perf_counter()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104# SPDX-License-Identifier: Apache-2.0"""Where T8's time goes (bin/devrun): the concat, each conv of the 3 BasicBlocks, the residual adds, the linear and theLayerNorm on random BEVs, each synchronized (eager).
bin/devrun python -m tt_autoe2e.tests.dev_t8_prof"""from __future__ import annotations
import jsonimport time
import numpy as np
CKPT = "/ae2e/881e6a8367746da1eaae044a68077d0e7ce6fc1b/models/kitscenes-epoch-5/checkpoint.pt"
def main() -> int: import torch import ttnn
from ..reference.port_form import BEV_H, BEV_W, Q from ..reference.tree import load_tree from ..tt.image import state_dict_of from ..tt.t8 import TtT8 from ..ttaw.device import DeviceConfig, close_device from ..ttaw.ops.conv import FeatureMap, residual_add
tree = load_tree(CKPT) state = state_dict_of(tree) dev = DeviceConfig(trace_region_size=32 << 20).open() res = {} try: t8 = TtT8(state) rng = np.random.default_rng(0) bevs = [ttnn.from_torch(torch.from_numpy(rng.standard_normal((1, 1, Q, 256)).astype(np.float32)), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev) for _ in range(8)] sync = lambda: ttnn.synchronize_device(dev) for rep in range(2): tm = {} t = time.perf_counter() x = FeatureMap(ttnn.concat(list(bevs), dim=3, memory_config=ttnn.DRAM_MEMORY_CONFIG), 1, BEV_H, BEV_W, 2048) sync() tm["concat"] = time.perf_counter() - t for i, (c1, c2, ds) in enumerate(t8.blocks): t = time.perf_counter() h = c1(x) sync() tm[f"b{i}.conv1"] = time.perf_counter() - t t = time.perf_counter() o = c2(h) sync() tm[f"b{i}.conv2"] = time.perf_counter() - t h.deallocate() t = time.perf_counter() idt = ds(x) if ds is not None else x sync() tm[f"b{i}.downsample"] = time.perf_counter() - t t = time.perf_counter() y = residual_add(o, idt, "relu") sync() tm[f"b{i}.add"] = time.perf_counter() - t o.deallocate() if ds is not None: idt.deallocate() x.deallocate() x = y if t8.fused0 is not None: x0 = FeatureMap(ttnn.concat(list(bevs), dim=3, memory_config=ttnn.DRAM_MEMORY_CONFIG), 1, BEV_H, BEV_W, 2048) sync() t = time.perf_counter() f = t8.fused0(x0) sync() tm["b0.fused_conv1_downsample"] = time.perf_counter() - t t = time.perf_counter() rows = int(f.tensor.shape[-2]) h = ttnn.relu(ttnn.slice(f.tensor, [0, 0, 0, 0], [1, 1, rows, 512])) i2 = ttnn.slice(f.tensor, [0, 0, 0, 512], [1, 1, rows, 1024]) sync() tm["b0.fused_split"] = time.perf_counter() - t tm["fused_shape"] = 0.0 res_shape = tuple(int(d) for d in f.tensor.shape) for z_ in (h, i2): ttnn.deallocate(z_) f.deallocate() x0.deallocate() t = time.perf_counter() tt = ttnn.reshape(x.tensor, (1, 1, Q, 512)) if tuple(x.tensor.shape) != (1, 1, Q, 512) else x.tensor z = t8.linear(tt) sync() tm["linear"] = time.perf_counter() - t x.deallocate() ttnn.deallocate(z) res = {k: round(v * 1e3, 2) for k, v in tm.items()} res.pop("fused_shape", None) res["total_unfused_ms"] = round(sum(v for k, v in res.items() if "fused" not in k), 1) finally: close_device(dev) print(json.dumps(res, indent=1)) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120# SPDX-License-Identifier: Apache-2.0"""T8's convs under different ttnn conv configs (bin/devrun): block 1's 3 x 3 512 -> 512 conv and block 0's fused2048 -> 1024 conv on random 300 x 200 BEV maps, timed (median, eager, synchronized) and compared with the defaultconfig's output (max abs, identical).
bin/devrun python -m tt_autoe2e.tests.dev_t8_sweep [--out /logs/x.json]"""from __future__ import annotations
import argparseimport jsonimport time
import numpy as np
CKPT = "/ae2e/881e6a8367746da1eaae044a68077d0e7ce6fc1b/models/kitscenes-epoch-5/checkpoint.pt"
def main(argv=None) -> int: ap = argparse.ArgumentParser() ap.add_argument("--out", default="/logs/t8_sweep.json") ap.add_argument("--reps", type=int, default=3) args = ap.parse_args(argv) import torch import ttnn
from ..reference.port_form import BEV_H, BEV_W, Q from ..reference.tree import load_tree from ..tt.image import state_dict_of from ..tt.t8 import TtT8 from ..ttaw.device import DeviceConfig, close_device from ..ttaw.ops.conv import Conv2d, FeatureMap
tree = load_tree(CKPT) state = state_dict_of(tree) dev = DeviceConfig(trace_region_size=32 << 20).open() res = {} try: t8 = TtT8(state) rng = np.random.default_rng(0) up = lambda c: ttnn.from_torch(torch.from_numpy(rng.standard_normal((1, 1, Q, c)).astype(np.float32)), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev) x512 = FeatureMap(up(512), 1, BEV_H, BEV_W, 512) x2048 = FeatureMap(up(2048), 1, BEV_H, BEV_W, 2048) c1 = t8.blocks[1][0] f0 = t8.fused0 HS, BS, WS = (ttnn.TensorMemoryLayout.HEIGHT_SHARDED, ttnn.TensorMemoryLayout.BLOCK_SHARDED, ttnn.TensorMemoryLayout.WIDTH_SHARDED)
def variant(base, slicing="auto", **cc): return Conv2d(base.weight, base.bias, padding=1, activation=base.activation, precision=base.precision, slicing=slicing, conv_config=cc, name=base.name + "_v")
cases = { "c512": (c1, x512, [ ("default", {}), ("dram_bs", dict(shard_layout=BS)), ("dram_hs", dict(shard_layout=HS)), ("dram_bs_dbuf", dict(shard_layout=BS, enable_act_double_buffer=True, enable_weights_double_buffer=True)), ("dram_hs_dbuf", dict(shard_layout=HS, enable_act_double_buffer=True, enable_weights_double_buffer=True)), ("dram_bs_abh64", dict(shard_layout=BS, act_block_h_override=64)), ("dram_bs_abh128", dict(shard_layout=BS, act_block_h_override=128)), ("dram_hs_abh64", dict(shard_layout=HS, act_block_h_override=64)), ("dram_h8", dict(slicing=("height", 8))), ("dram_h4_bs", dict(slicing=("height", 4), shard_layout=BS)), ("l1_bs", dict(slicing="l1", shard_layout=BS)), ("l1_hs", dict(slicing="l1", shard_layout=HS)), ("l1_bs_dbuf", dict(slicing="l1", shard_layout=BS, enable_act_double_buffer=True, enable_weights_double_buffer=True)), ]), "f2048": (f0, x2048, [ ("default", {}), ("dram_bs", dict(shard_layout=BS)), ("dram_bs_dbuf", dict(shard_layout=BS, enable_act_double_buffer=True, enable_weights_double_buffer=True)), ("dram_hs", dict(shard_layout=HS)), ("dram_ws", dict(shard_layout=WS)), ("dram_bs_abh64", dict(shard_layout=BS, act_block_h_override=64)), ("dram_h8_bs", dict(slicing=("height", 8), shard_layout=BS)), ("dram_w4_bs", dict(slicing=("width", 4), shard_layout=BS)), ]), } for cname, (base, x, vs) in cases.items(): ref = None for vname, kw in vs: kw = dict(kw) slicing = kw.pop("slicing", "auto") conv = base if vname == "default" else variant(base, slicing, **kw) key = f"{cname}.{vname}" try: o = conv(x) ttnn.synchronize_device(dev) a = ttnn.to_torch(o.tensor).float().numpy().reshape(-1) o.deallocate() ts = [] for _ in range(args.reps): t = time.perf_counter() o = conv(x) ttnn.synchronize_device(dev) ts.append(time.perf_counter() - t) o.deallocate() ms = round(float(np.median(ts)) * 1e3, 2) if ref is None: ref = a res[key] = {"ms": ms, "identical": bool(np.array_equal(a, ref)), "max_abs": float(np.abs(a - ref).max())} except Exception as e: # noqa: BLE001 - invalid configs are part of the sweep res[key] = {"error": str(e).splitlines()[0][:160]} print(key, res[key], flush=True) finally: close_device(dev) with open(args.out, "w") as f: json.dump(res, f, indent=1) return 0
if __name__ == "__main__": raise SystemExit(main())12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091# SPDX-License-Identifier: Apache-2.0"""``host.geometry.frame_geometry`` (vectorized float32) against the original per-camera float64 loop, bit for bit,on the golden sample's 8 frames and its 1024 px front, plus timing (host only, no device).
bin/devrun --no-device python -m tt_autoe2e.tests.host_geometry"""from __future__ import annotations
import globimport jsonimport time
import numpy as np
from ..host import geometry as Gfrom ..reference.port_form import LEVELS, PILLARS, POINTS, Q, reference_points
def frame_geometry_loop(P: np.ndarray, image: int = 512, *, r_cap: int = G.R_CAP, k_cams: int = G.K_CAMS) -> G.FrameGeometry: """``P`` ``[V, 3, 4]`` (ego -> pixels of the ``image`` x ``image`` model input) -> :class:`FrameGeometry`.""" import torch
uv, mask = reference_points(torch.as_tensor(np.asarray(P, np.float32)), image) uv = uv.numpy().astype(np.float64) # [V, Q, 4, 2] vis = mask.numpy().any(-1) # [V, Q] V = vis.shape[0] rows = [np.nonzero(vis[v])[0] for v in range(V)] seg_rows = [int(-(-len(r) // 32) * 32) for r in rows] total = sum(seg_rows) if total > r_cap: raise ValueError(f"frame_geometry: {total} rebatched rows exceed the capacity {r_cap}") if V > 8: raise ValueError("frame_geometry: at most 8 cameras") sca_index = np.full((1, r_cap), Q, np.uint32) base = np.full((r_cap, LEVELS * 16), G.FAR, np.float32) cams_of = np.zeros(Q, np.int64) gather = np.full((k_cams, Q), r_cap, np.uint32) anchors = np.arange(POINTS) % PILLARS sizes = G.level_sizes(image) start = 0 ends = np.zeros((1, 1, 1, 16), np.uint32) for v, r in enumerate(rows): n = len(r) sca_index[0, start:start + n] = r a = uv[v, r][:, anchors] # [n, 8, 2] for lvl, (h, w) in enumerate(sizes): px = (a[..., 0] * w - 0.5) * 65536.0 py = (a[..., 1] * h - 0.5) * 65536.0 blk = np.stack([px, py], -1).reshape(n, 16) base[start:start + n, lvl * 16:(lvl + 1) * 16] = blk.astype(np.float32) slot = cams_of[r] if n and slot.max() >= k_cams: raise ValueError(f"frame_geometry: a cell is seen by more than {k_cams} cameras") gather[slot, r] = np.arange(start, start + n, dtype=np.uint32) cams_of[r] += 1 start += seg_rows[v] ends[0, 0, 0, v] = start // 32 ends[0, 0, 0, V:8] = r_cap // 32 # the last segment owns the padding blocks after it (its rows there are padding: cell Q, FAR positions) ends[0, 0, 0, V - 1] = r_cap // 32 cnt = cams_of.astype(np.float32) scale = (1.0 / np.maximum(cnt, 1.0)).reshape(Q, 1).astype(np.float32) observed = (cnt > 0).astype(np.float32).reshape(Q, 1) return G.FrameGeometry(sca_index, base, ends, seg_rows, gather, scale, observed, [int(len(r)) for r in rows])
def main() -> int: g = np.load(glob.glob("/ae2e/ref/autoe2e_kitscenes_epoch5_*f000045.npz")[0]) cases = [(g["camera_history_projection_matrix"][0, k], 512, {}) for k in range(7)] cases += [(g["camera_projection_matrix"][0], 512, {}), (g["front_camera_projection_matrix"][0], 1024, {"r_cap": 40_960, "k_cams": 1})] res = {"cases": len(cases), "mismatch": []} t_new = t_old = 0.0 for i, (P, size, kw) in enumerate(cases): t = time.perf_counter(); a = G.frame_geometry(P, size, **kw); t_new += time.perf_counter() - t t = time.perf_counter(); b = frame_geometry_loop(P, size, **kw); t_old += time.perf_counter() - t for f in ("sca_index", "base", "seg", "gather", "scale", "observed"): x, y = getattr(a, f), getattr(b, f) if x.shape != y.shape or x.dtype != y.dtype or x.tobytes() != y.tobytes(): res["mismatch"].append([i, f]) if a.seg_rows != b.seg_rows or a.visible_rows != b.visible_rows: res["mismatch"].append([i, "rows"]) res["ms_per_frame"] = {"vectorized": round(t_new / len(cases) * 1e3, 1), "loop": round(t_old / len(cases) * 1e3, 1)} res["verdict"] = "PASS" if not res["mismatch"] else "FAIL" print(json.dumps(res, indent=1)) return 0 if not res["mismatch"] else 1
if __name__ == "__main__": raise SystemExit(main())6 unmodified lines78910111213141510 unmodified lines26272829303132333435363738394055 unmodified lines969798991001011 unmodified line10310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813911 unmodified lines1511521531541551561571581591601611621632 unmodified lines1661671681691701711721731743 unmodified lines17817918018118218332 unmodified lines2162172182192202212224 unmodified lines2272282292302312322338 unmodified lines24224324424524624724824925025125225325425525625725825926026126226334 unmodified lines29829930030130230330430530630730830931032 unmodified lines3433443453463473483493503513523533547 unmodified lines3623633643653663673682 unmodified lines3713723733743753763778 unmodified lines3863873883896 unmodified linessegments), ``gather`` (K scatter gathers), ``scale``, ``observed``. The FPN levels arrive as rows ``[1, 1, 6 h w, 256]``(camera-major) bf16 TILE.TSA (layers 1-5): ``pin = [q | q + pos]``; one fp32 sampling projection in the merged layout of 16 head blocks(block ``2 head + queue``: 4 points x (x, y), scaled by 2^16) + the constant cell-centre base -> int32 positions;one fp32 attention projection into 16 blocks of 32 columns (4 logits, the rest -1e4) -> softmax per block; the valueprojection as 8 maps 300 x 200 in L1 shared by the two blocks of a head (``hdiv`` 2); the queue mean (x 0.5) foldedinto the output projection over the 16 merged blocks.10 unmodified linesimport numpy as npfrom ..host.geometry import K_CAMS, R_CAP, level_sizes, tsa_basefrom ..reference.port_form import BEV_H, BEV_W, E, HEADS, LEVELS, LN_EPS, Qfrom ..ttaw.models.second import RowLinearfrom .msda_k import PAD_LOGIT, msdaPREC = "HiFi4+fp32+l1acc:w=fp32"SCALE = 65536.0def _np(t) -> np.ndarray:return t.detach().float().cpu().numpy()55 unmodified lines"""``lin(x)`` (a RowLinear) with its output in L1 interleaved (the same ttnn.linear call otherwise)."""import ttnnfrom ..ttaw.tensors import ttnn_dtypeweight, bias, grid, cfg = lin._device or lin._upload(x.device())1 unmodified linememory_config=ttnn.L1_MEMORY_CONFIG, dtype=ttnn_dtype(lin.output_dtype))def _lin(w_out_in: np.ndarray, b: Optional[np.ndarray], *, out="bfloat16", act=None, name="linear") -> RowLinear:"""nn.Linear weight ``[out, in]`` -> RowLinear (``[in, out]``)."""return RowLinear(np.ascontiguousarray(w_out_in.T), b, activation=act, precision=PREC, output_dtype=out, name=name)class _Layer:def __init__(self, layer, i: int):sa, ca, ffn = layer.self_attention, layer.cross_attention, layer.ffnself.i = iif i > 0:self.tsa_v = _lin(_np(sa.value_proj.weight), _np(sa.value_proj.bias), name=f"l{i}.tsa.value")self.tsa_off = _lin(_np(sa.sampling_offsets.weight) * SCALE, _np(sa.sampling_offsets.bias) * SCALE,out="float32", name=f"l{i}.tsa.off")# [64, 512]: column h * 8 + q * 4 + p = head block 2 h + q, point p: the compact logits of the in-kernel# softmax (4 per block) as they comeself.tsa_att = _lin(_np(sa.attention_weights.weight), _np(sa.attention_weights.bias), out="float32",name=f"l{i}.tsa.att")wo = _np(sa.output_proj.weight) # [256, 256] (out, in = head * 32 + d)wo2 = np.zeros((E, 16 * 32), np.float32)for h in range(HEADS):for q in range(2):wo2[:, (2 * h + q) * 32:(2 * h + q + 1) * 32] = 0.5 * wo[:, h * 32:(h + 1) * 32]self.tsa_out = _lin(wo2, _np(sa.output_proj.bias), name=f"l{i}.tsa.out")self.sca_v = _lin(_np(ca.value_proj.weight), _np(ca.value_proj.bias), name=f"l{i}.sca.value")self.sca_off = _lin(_np(ca.sampling_offsets.weight) * SCALE, _np(ca.sampling_offsets.bias) * SCALE,out="float32", name=f"l{i}.sca.off")self.sca_att = _lin(_np(ca.attention_weights.weight), _np(ca.attention_weights.bias), out="float32",name=f"l{i}.sca.att")self.sca_out = _lin(_np(ca.output_proj.weight), _np(ca.output_proj.bias), name=f"l{i}.sca.out")self.ffn1 = _lin(_np(ffn[0].weight), _np(ffn[0].bias), act="relu", name=f"l{i}.ffn1")self.ffn2 = _lin(_np(ffn[3].weight), _np(ffn[3].bias), name=f"l{i}.ffn2")self.norms = [_LN(n) for n in layer.norms]11 unmodified linesself.sizes = level_sizes(image)pf = PortForm(model)vf = pf.vfself.layers = [_Layer(l, i) for i, l in enumerate(vf.layers)]up = lambda a, dt=ttnn.bfloat16: ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(a, np.float32)),dtype=dt, layout=ttnn.TILE_LAYOUT, device=device,memory_config=ttnn.DRAM_MEMORY_CONFIG)self.pos = up(pf.position.numpy().reshape(1, 1, Q, E))self.layer0 = up(pf.layer0.numpy().reshape(1, 1, Q, E))self.tsa_base = up(tsa_base().reshape(1, 1, Q, 128), ttnn.float32)# level + camera embeddings of the value input, per level [1, 1, 6 h w, 256] (camera-major rows)lvl, cam = pf.level_emb.numpy(), pf.camera_emb.numpy()self.emb = []2 unmodified linesself.emb.append(up(e))self.prof: Optional[Dict[str, float]] = None # set to {} to time the blocks (synchronizes the device)self.pairs = True # pixel-pair value maps (2x faster SCA kernel, same values)self.cfg = ttnn.init_device_compute_kernel_config(device.arch(), math_fidelity=ttnn.MathFidelity.HiFi4,math_approx_mode=False, fp32_dest_acc_en=True,packer_l1_acc=True)# ------------------------------------------------------------------ inputsdef upload_geometry(self, geo) -> Dict[str, Any]:3 unmodified linesd = self.devicet = {}t["sca_index"] = ttnn.from_torch(torch.from_numpy(geo.sca_index.astype(np.int64)).to(torch.int32),dtype=ttnn.uint32, layout=ttnn.ROW_MAJOR_LAYOUT, device=d)t["base"] = ttnn.from_torch(torch.from_numpy(geo.base.reshape(1, 1, geo.base.shape[0], -1)), dtype=ttnn.float32,32 unmodified linesmemory_config=mc or ttnn.DRAM_MEMORY_CONFIG)return outdef _maps(self, proj, n_maps, h, w):"""value projection ``[1, 1, S h w, 256]`` -> the ``msda`` value of the 8 S maps (map head * S + s): pixel-pairmaps ``(8 S, h, w + 1, 64)`` in L1 (``tt/pairmap.py``; one 128-byte read per two corners) when ``self.pairs``,else stick maps ``(8 S, h, w, 32)`` in L1."""4 unmodified linesp1 = proj if proj.memory_config().buffer_type == ttnn.BufferType.L1 else \ttnn.to_memory_config(proj, ttnn.L1_MEMORY_CONFIG)out = pair_maps(p1, heads=HEADS, sub=int(n_maps) // HEADS, hw=(h, w))if p1 is not proj:_free(p1)return out8 unmodified linesimport ttnnt0 = self._t('-', time.perf_counter())qpos = ttnn.add(query, self.pos, memory_config=ttnn.DRAM_MEMORY_CONFIG)pin = ttnn.concat([query, qpos], dim=3, memory_config=ttnn.DRAM_MEMORY_CONFIG)_free(qpos)off = L.tsa_off(pin) # [1, 1, Q, 128] fp32loc_f = ttnn.add(off, self.tsa_base, memory_config=ttnn.DRAM_MEMORY_CONFIG)_free(off)loc = ttnn.typecast(loc_f, ttnn.int32)_free(loc_f)logits = L.tsa_att(pin) # [1, 1, Q, 64] fp32_free(pin)t0 = self._t('tsa.proj_loc_att', t0)vproj = linear_l1(L.tsa_v, query) if self.pairs else L.tsa_v(query)maps = self._maps(vproj, HEADS, BEV_H, BEV_W)_free(vproj)t0 = self._t('tsa.value_maps', t0)out = msda(maps, loc, logits, points=4, nq=Q, sub=1, hdiv=2, loc_hs=8, softmax=True) # [1, 1, Q, 512]_free(maps, loc, logits)t0 = self._t('tsa.msda', t0)y = L.tsa_out(out)34 unmodified linesacc = Nonefor l, (h, w) in enumerate(self.sizes):vproj = linear_l1(L.sca_v, xs[l]) if self.pairs else L.sca_v(xs[l])maps = self._maps(vproj, HEADS * 6, h, w)_free(vproj)t0 = self._t('sca.value_maps', t0)o = msda(maps, loc, att, points=8, nq=R_CAP, segments=[0] * g["nseg"], seg_table=g["seg"],loc_hs=64, loc_off=16 * l, att_col0=8 * l)_free(maps)t0 = self._t('sca.msda', t0)if acc is None:acc = o # bf16; the sums are fp32else:32 unmodified linesself._t('sca.out', t0)return ydef frame(self, levels: Sequence[Any], g: Dict[str, Any], *, trace: Optional[List] = None):"""``levels``: 4 x ``[1, 1, 6 h w, 256]`` bf16 TILE FPN rows; ``g`` from :meth:`upload_geometry` -> the BEV``[1, 1, Q, 256]`` bf16 (zero where no camera sees the cell)."""import ttnnown_base = "base512" not in gif own_base:g["base512"] = ttnn.repeat(g["base"], ttnn.Shape([1, 1, 1, HEADS]), memory_config=ttnn.DRAM_MEMORY_CONFIG)xs = [ttnn.add(levels[l], self.emb[l], memory_config=ttnn.DRAM_MEMORY_CONFIG) for l in range(LEVELS)]7 unmodified linesif own:_free(query)query, own = q2, Truey = self._sca(L, query, xs, g)q2 = L.norms[1](y, residual=query, cfg=self.cfg)_free(y)if own:2 unmodified linesimport timet0 = self._t('-', time.perf_counter())h1 = L.ffn1(query)y = L.ffn2(h1)_free(h1)q2 = L.norms[2](y, residual=query, cfg=self.cfg)8 unmodified lines_free(g.pop("base512"))out = ttnn.multiply(query, g["observed"], memory_config=ttnn.DRAM_MEMORY_CONFIG)_free(query)return out6 unmodified lines789101112131415161710 unmodified lines28293031323334353637383940414243444546474849505155 unmodified lines1071081091101111121131141 unmodified line11611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129211 unmodified lines3043053063073083093103113123133143153163173183192 unmodified lines3223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633 unmodified lines36736836937037137237337437537637737832 unmodified lines4114124134144154164174 unmodified lines4224234244254264274288 unmodified lines43743843944044144244344444544644744844945045145245345445545645734 unmodified lines49249349449549649749849950050150250350432 unmodified lines5375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915927 unmodified lines6006016026036046056062 unmodified lines6096106116126136146158 unmodified lines6246256266276286296 unmodified linessegments), ``gather`` (K scatter gathers), ``scale``, ``observed``. The FPN levels arrive as rows ``[1, 1, 6 h w, 256]``(camera-major) bf16 TILE.TSA (layers 1-5): upstream projects ``pin = [q | q + pos]``; with ``W = [Wa | Wb]`` that is ``(Wa + Wb) q`` plusthe per-layer constant ``Wb pos + b`` (``pos`` is fixed), so the device projects ``q`` alone (K = 256) and adds theconstant (fp32, the cell-centre base folded in for the positions): one fp32 sampling projection in the merged layoutof 16 head blocks (block ``2 head + queue``: 4 points x (x, y), scaled by 2^16) -> int32 positions; one fp32attention projection to the compact logits (4 per block) for the kernel's own softmax; the valueprojection as 8 maps 300 x 200 in L1 shared by the two blocks of a head (``hdiv`` 2); the queue mean (x 0.5) foldedinto the output projection over the 16 merged blocks.10 unmodified linesimport numpy as npfrom ..host.geometry import K_CAMS, R_CAP, CmGeometry, level_sizes, tsa_base, use_cmfrom ..reference.port_form import BEV_H, BEV_W, E, HEADS, LEVELS, LN_EPS, Qfrom ..ttaw.models.second import RowLinearfrom .msda_cm import msda_cmfrom .msda_k import PAD_LOGIT, msdaPREC = "HiFi4+fp32+l1acc:w=fp32"SCALE = 65536.0def prec(group: str, default: str = PREC) -> str:"""Precision of a linear group (``AE_PREC_<GROUP>`` overrides, for experiments): OFF / ATT (sampling offsets andattention logits), VAL (value projections), OUT (output projections), FFN."""import osreturn os.environ.get(f"AE_PREC_{group}", default)def _np(t) -> np.ndarray:return t.detach().float().cpu().numpy()55 unmodified lines"""``lin(x)`` (a RowLinear) with its output in L1 interleaved (the same ttnn.linear call otherwise)."""import ttnnif isinstance(lin, PcLinear):return lin(x, memory_config=ttnn.L1_MEMORY_CONFIG)from ..ttaw.tensors import ttnn_dtypeweight, bias, grid, cfg = lin._device or lin._upload(x.device())1 unmodified linememory_config=ttnn.L1_MEMORY_CONFIG, dtype=ttnn_dtype(lin.output_dtype))# Explicit matmul program configs per (K tiles, N tiles, fp32 out, relu), from the sweep of tests/dev_layer_ops.py on# 60,000 BEV rows (1.2-1.8x faster than ttnn's choice for core_grid; the same fp32 accumulation, results within one# rounding step), kept under an L1 budget for their circular buffers (L1 tensors such as the value maps live beside# them): ("1d", in0_block_w, out_block_h, subblock h, subblock w) = in1 multicast, rows split over the grid;# ("2d", grid x, in0_block_w, out_block_h, subblock h, subblock w)_MM_SPECS = {(8, 16, True, False): ("2d", 8, 4, 4, 2, 2), # sampling offsets 256 -> 512 (fp32)(8, 8, True, False): ("1d", 4, 4, 1, 4), # attention logits 256 -> 256 (fp32)(8, 8, False, False): ("1d", 4, 4, 1, 4), # output / value projections(8, 16, False, True): ("2d", 8, 4, 4, 2, 2), # FFN 1 (relu)(8, 16, False, False): ("2d", 8, 4, 4, 2, 2),(16, 8, False, False): ("1d", 4, 2, 1, 4), # FFN 2, TSA output (512 -> 256)(16, 8, True, False): ("1d", 4, 2, 1, 4),(8, 4, True, False): ("1d", 8, 4, 1, 4), # TSA offsets 256 -> 128 (fp32)(8, 24, True, False): ("2d", 8, 4, 4, 1, 3), # SCA offsets + logits 256 -> 768 (fp32)}_MM_BUDGET = {"dram": 600 << 10, "l1": 260 << 10}def _mm_footprint(spec, k: int, n: int, fp32_out: bool) -> int:"""Circular-buffer bytes of a spec (bf16 activations, fp32 weights): in0 / in1 double-buffered, out, fp32 partials."""if spec[0] == "1d":_, ibw, obh, _, _ = specpcn = nelse:_, nx, ibw, obh, _, _ = specpcn = n // nxreturn (2 * obh * ibw * 2048 + 2 * ibw * pcn * 4096 + obh * pcn * (4096 if fp32_out else 2048)+ (obh * pcn * 4096 if k // ibw > 1 else 0))def mm_program_config(device, rows: int, k: int, n: int, fp32_out: bool, relu: bool, budget: str = "dram"):"""The matmul program config of a ``[rows, 32 k] x [32 k, 32 n]`` linear (``None``: ttnn's own choice, as``AE_MM_PC=0`` forces)."""import osimport ttnnif os.environ.get("AE_MM_PC", "1") == "0":return Nonesbw0 = next(w for w in (4, 2, 1) if n % w == 0)spec = _MM_SPECS.get((k, n, fp32_out, relu)) or ("1d", next(b for b in (4, 2, 1) if k % b == 0), 4, 1, sbw0)if budget == "l1":spec = ("1d", next(b for b in (2, 1) if k % b == 0), 2, 1, sbw0)while _mm_footprint(spec, k, n, fp32_out) > _MM_BUDGET[budget]:if spec[0] == "2d":spec = ("1d", min(spec[2], 4), spec[3], 1, sbw0)elif spec[2] > 1:spec = (spec[0], spec[1], spec[2] // 2, 1, spec[4])elif spec[1] > 1:spec = (spec[0], spec[1] // 2, spec[2], spec[3], spec[4])else:return Noneg = device.compute_with_storage_grid_size()gx, gy = int(g.x), int(g.y)mt = -(-int(rows) // 32)act = ttnn.UnaryWithParam(ttnn.UnaryOpType.RELU) if relu else Noneif spec[0] == "2d":_, nx, ibw, obh, sbh, sbw = specpcm = -(-mt // gy)if pcm % obh or n % nx:return Nonereturn ttnn.MatmulMultiCoreReuseMultiCastProgramConfig(compute_with_storage_grid_size=ttnn.CoreCoord(nx, gy), in0_block_w=ibw, out_subblock_h=sbh,out_subblock_w=sbw, out_block_h=obh, out_block_w=n // nx, per_core_M=pcm, per_core_N=n // nx,transpose_mcast=False, fused_activation=act)_, ibw, obh, sbh, sbw = specpcm = -(-mt // (gx * gy))obh = min(obh, pcm)while pcm % obh:obh -= 1while obh % sbh:sbh -= 1return ttnn.MatmulMultiCoreReuseMultiCast1DProgramConfig(compute_with_storage_grid_size=ttnn.CoreCoord(gx, gy), in0_block_w=ibw, out_subblock_h=sbh,out_subblock_w=sbw, out_block_h=obh, out_block_w=n, per_core_M=pcm, per_core_N=n, fuse_batch=True,fused_activation=act, mcast_in0=False)class PcLinear(RowLinear):"""A RowLinear run with an explicit program config (:func:`mm_program_config`, cached per row count)."""def __call__(self, x: Any, memory_config: Any = None) -> Any:import ttnnfrom ..ttaw.tensors import ttnn_dtypeif int(x.shape[-1]) != self.in_channels:raise ValueError(f"{self.name}: input has {int(x.shape[-1])} channels, expected {self.in_channels}")weight, bias, grid, cfg = self._device or self._upload(x.device())rows = 1for i in range(len(x.shape) - 1):rows *= int(x.shape[i])mc = memory_config or ttnn.DRAM_MEMORY_CONFIGbudget = "l1" if mc.buffer_type == ttnn.BufferType.L1 else "dram"cache = self.__dict__.setdefault("_pcs", {})if (rows, budget) not in cache:cache[(rows, budget)] = mm_program_config(x.device(), rows, self.in_channels // 32,self.out_channels // 32, self.output_dtype == "float32",self.activation == "relu", budget)pc = cache[(rows, budget)]if pc is None or self.in_channels % 32 or self.out_channels % 32:return ttnn.linear(x, weight, bias=bias, activation=self.activation, compute_kernel_config=cfg,core_grid=grid, memory_config=mc, dtype=ttnn_dtype(self.output_dtype))return ttnn.linear(x, weight, bias=bias, program_config=pc, compute_kernel_config=cfg, memory_config=mc,dtype=ttnn_dtype(self.output_dtype))def _lin(w_out_in: np.ndarray, b: Optional[np.ndarray], *, out="bfloat16", act=None, name="linear",group: str = "OFF") -> RowLinear:"""nn.Linear weight ``[out, in]`` -> PcLinear (``[in, out]``)."""return PcLinear(np.ascontiguousarray(w_out_in.T), b, activation=act, precision=prec(group), output_dtype=out,name=name)def cm_column_orders():"""Column orders of the sampling offsets / attention logits for ``msda_cm`` (its reader RISC h reads only its ownpoints 4 h .. 4 h + 3): offsets ``j * 64 + h * 32 + l * 8 + 2 q + xy`` (upstream ``j * 64 + l * 16 + 2 p + xy``,``p = 4 h + q``), logits ``j * 32 + h * 16 + l * 4 + q`` (upstream ``j * 32 + l * 8 + p``; the softmax over ahead's 32 columns does not depend on their order). Returns the two index arrays ``new -> upstream``."""po = np.zeros(HEADS * 64, np.int64)pa = np.zeros(HEADS * 32, np.int64)for j in range(HEADS):for h in range(2):for l in range(LEVELS):for q in range(4):p = 4 * h + qfor xy in range(2):po[j * 64 + h * 32 + l * 8 + 2 * q + xy] = j * 64 + l * 16 + 2 * p + xypa[j * 32 + h * 16 + l * 4 + q] = j * 32 + l * 8 + preturn po, padef _permuted(lin: RowLinear, perm: np.ndarray) -> "PcLinear":"""``lin`` with its output columns reordered (``out[:, n] = lin_out[:, perm[n]]``)."""return PcLinear(lin.weight_host[:, perm], lin.bias_host[perm], activation=lin.activation, precision=lin.precision,output_dtype=lin.output_dtype, name=lin.name)class _Layer:def __init__(self, layer, i: int, pos: np.ndarray):sa, ca, ffn = layer.self_attention, layer.cross_attention, layer.ffnself.i = iif i > 0:self.tsa_v = _lin(_np(sa.value_proj.weight), _np(sa.value_proj.bias), name=f"l{i}.tsa.value", group="VAL")# pin = [q | q + pos] -> (Wa + Wb) q + (Wb pos + b): the second term is a per-layer constantp64 = pos.astype(np.float64)w, b = _np(sa.sampling_offsets.weight).astype(np.float64), _np(sa.sampling_offsets.bias).astype(np.float64)self.tsa_off = _lin(((w[:, :E] + w[:, E:]) * SCALE).astype(np.float32), None, out="float32",name=f"l{i}.tsa.off")self.tsa_off_c = ((p64 @ w[:, E:].T + b) * SCALE + tsa_base().astype(np.float64)).astype(np.float32)# [64, 512]: column h * 8 + q * 4 + p = head block 2 h + q, point p: the compact logits of the in-kernel# softmax (4 per block) as they comew, b = _np(sa.attention_weights.weight).astype(np.float64), _np(sa.attention_weights.bias).astype(np.float64)self.tsa_att = _lin((w[:, :E] + w[:, E:]).astype(np.float32), None, out="float32", name=f"l{i}.tsa.att",group="ATT")self.tsa_att_c = (p64 @ w[:, E:].T + b).astype(np.float32)wo = _np(sa.output_proj.weight) # [256, 256] (out, in = head * 32 + d)wo2 = np.zeros((E, 16 * 32), np.float32)for h in range(HEADS):for q in range(2):wo2[:, (2 * h + q) * 32:(2 * h + q + 1) * 32] = 0.5 * wo[:, h * 32:(h + 1) * 32]self.tsa_out = _lin(wo2, _np(sa.output_proj.bias), name=f"l{i}.tsa.out", group="OUT")self.sca_v = _lin(_np(ca.value_proj.weight), _np(ca.value_proj.bias), name=f"l{i}.sca.value", group="VAL")self.sca_off = _lin(_np(ca.sampling_offsets.weight) * SCALE, _np(ca.sampling_offsets.bias) * SCALE,out="float32", name=f"l{i}.sca.off")self.sca_att = _lin(_np(ca.attention_weights.weight), _np(ca.attention_weights.bias), out="float32",name=f"l{i}.sca.att", group="ATT")self.sca_out = _lin(_np(ca.output_proj.weight), _np(ca.output_proj.bias), name=f"l{i}.sca.out", group="OUT")self.ffn1 = _lin(_np(ffn[0].weight), _np(ffn[0].bias), act="relu", name=f"l{i}.ffn1", group="FFN")self.ffn2 = _lin(_np(ffn[3].weight), _np(ffn[3].bias), name=f"l{i}.ffn2", group="FFN")self.norms = [_LN(n) for n in layer.norms]11 unmodified linesself.sizes = level_sizes(image)pf = PortForm(model)vf = pf.vfpos = pf.position.numpy()self.layers = [_Layer(l, i, pos) for i, l in enumerate(vf.layers)]up = lambda a, dt=ttnn.bfloat16: ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(a, np.float32)),dtype=dt, layout=ttnn.TILE_LAYOUT, device=device,memory_config=ttnn.DRAM_MEMORY_CONFIG)self.layer0 = up(pf.layer0.numpy().reshape(1, 1, Q, E))for L in self.layers[1:]:L.tsa_off_dev = up(L.tsa_off_c.reshape(1, 1, Q, 128), ttnn.float32)L.tsa_att_dev = up(L.tsa_att_c.reshape(1, 1, Q, 64), ttnn.float32)del L.tsa_off_c, L.tsa_att_c# level + camera embeddings of the value input, per level [1, 1, 6 h w, 256] (camera-major rows)lvl, cam = pf.level_emb.numpy(), pf.camera_emb.numpy()self.emb = []2 unmodified linesself.emb.append(up(e))self.prof: Optional[Dict[str, float]] = None # set to {} to time the blocks (synchronizes the device)self.pairs = True # pixel-pair value maps (2x faster SCA kernel, same values)import os# cross-attention value maps as quads (the 4 corners of a point in one 256-byte read; the same values)self.quads = self.pairs and os.environ.get("AE_QUADS", "1") != "0"# cell-major cross-attention (one kernel per layer, no gather / scatter / level sum); layer 0's query is the# constant LN0(TSA0(bev_queries)), so its sampling offsets and weights are constants tooself.cfg = ttnn.init_device_compute_kernel_config(device.arch(), math_fidelity=ttnn.MathFidelity.HiFi4,math_approx_mode=False, fp32_dest_acc_en=True,packer_l1_acc=True)self.cm = self.quads and use_cm()# intermediates read once by the next linear kept in L1 interleaved (no DRAM round trip) where they fit beside# the value maps and the kernel buffers: the FFN hidden (AE_L1_FFN), the TSA / SCA kernel outputs (AE_L1_TSA /# AE_L1_SCA; the SCA output does not fit beside its maps)l1 = lambda k, d: ttnn.L1_MEMORY_CONFIG if os.environ.get(k, d) != "0" else ttnn.DRAM_MEMORY_CONFIGself._mid_ffn = l1("AE_L1_FFN", "1")self._mid_tsa = l1("AE_L1_TSA", "0")self._mid_sca = l1("AE_L1_SCA", "0")self._cm0 = Noneif self.cm:po, pa = cm_column_orders()# the offsets and logits as ONE 256 -> 768 projection (the query read once; AE_SCA_MERGE=0: two)self.sca_merge = os.environ.get("AE_SCA_MERGE", "1") != "0"for L in self.layers:L.sca_off = _permuted(L.sca_off, po)L.sca_att = _permuted(L.sca_att, pa)if self.sca_merge:L.sca_proj = PcLinear(np.concatenate([L.sca_off.weight_host, L.sca_att.weight_host], axis=1),np.concatenate([L.sca_off.bias_host, L.sca_att.bias_host]),precision=L.sca_off.precision, output_dtype="float32",name=f"l{L.i}.sca.proj")L0 = self.layers[0]# the raw projections (msda_cm converts them in the kernel)if self.sca_merge:self._cm0 = (L0.sca_proj(self.layer0), None)else:self._cm0 = (L0.sca_off(self.layer0), L0.sca_att(self.layer0))# ------------------------------------------------------------------ inputsdef upload_geometry(self, geo) -> Dict[str, Any]:3 unmodified linesd = self.devicet = {}if isinstance(geo, CmGeometry):t["table"] = ttnn.from_torch(torch.from_numpy(geo.table.reshape(1, 1, Q, 32)), dtype=ttnn.int32,layout=ttnn.TILE_LAYOUT, device=d)t["observed"] = ttnn.from_torch(torch.from_numpy(geo.observed.reshape(1, 1, Q, 1)), dtype=ttnn.bfloat16,layout=ttnn.TILE_LAYOUT, device=d)return tt["sca_index"] = ttnn.from_torch(torch.from_numpy(geo.sca_index.astype(np.int64)).to(torch.int32),dtype=ttnn.uint32, layout=ttnn.ROW_MAJOR_LAYOUT, device=d)t["base"] = ttnn.from_torch(torch.from_numpy(geo.base.reshape(1, 1, geo.base.shape[0], -1)), dtype=ttnn.float32,32 unmodified linesmemory_config=mc or ttnn.DRAM_MEMORY_CONFIG)return outdef _maps(self, proj, n_maps, h, w, quad=False):"""value projection ``[1, 1, S h w, 256]`` -> the ``msda`` value of the 8 S maps (map head * S + s): pixel-pairmaps ``(8 S, h, w + 1, 64)`` in L1 (``tt/pairmap.py``; one 128-byte read per two corners) when ``self.pairs``,else stick maps ``(8 S, h, w, 32)`` in L1."""4 unmodified linesp1 = proj if proj.memory_config().buffer_type == ttnn.BufferType.L1 else \ttnn.to_memory_config(proj, ttnn.L1_MEMORY_CONFIG)out = pair_maps(p1, heads=HEADS, sub=int(n_maps) // HEADS, hw=(h, w), quad=quad)if p1 is not proj:_free(p1)return out8 unmodified linesimport ttnnt0 = self._t('-', time.perf_counter())off = L.tsa_off(query) # [1, 1, Q, 128] fp32loc_f = ttnn.add(off, L.tsa_off_dev, memory_config=ttnn.DRAM_MEMORY_CONFIG) # + Wb pos + b + base_free(off)loc = ttnn.typecast(loc_f, ttnn.int32)_free(loc_f)lg = L.tsa_att(query) # [1, 1, Q, 64] fp32logits = ttnn.add(lg, L.tsa_att_dev, memory_config=ttnn.DRAM_MEMORY_CONFIG)_free(lg)t0 = self._t('tsa.proj_loc_att', t0)vproj = linear_l1(L.tsa_v, query) if self.pairs else L.tsa_v(query)maps = self._maps(vproj, HEADS, BEV_H, BEV_W)_free(vproj)t0 = self._t('tsa.value_maps', t0)out = msda(maps, loc, logits, points=4, nq=Q, sub=1, hdiv=2, loc_hs=8, softmax=True,memory_config=self._mid_tsa) # [1, 1, Q, 512]_free(maps, loc, logits)t0 = self._t('tsa.msda', t0)y = L.tsa_out(out)34 unmodified linesacc = Nonefor l, (h, w) in enumerate(self.sizes):vproj = linear_l1(L.sca_v, xs[l]) if self.pairs else L.sca_v(xs[l])maps = self._maps(vproj, HEADS * 6, h, w, quad=self.quads)_free(vproj)t0 = self._t('sca.value_maps', t0)o = msda(maps, loc, att, points=8, nq=R_CAP, segments=[0] * g["nseg"], seg_table=g["seg"],loc_hs=64, loc_off=16 * l, att_col0=8 * l)_free(maps)t0 = self._t(f'sca.msda.l{l}', t0)if acc is None:acc = o # bf16; the sums are fp32else:32 unmodified linesself._t('sca.out', t0)return ydef _sca_cm(self, L: _Layer, query, xs, g):"""The cell-major cross-attention (``msda_cm``): offsets / weights on the Q cells, the 4 levels' quad maps, onekernel; ``g["table"]`` the frame's cell table."""import timeimport ttnnt0 = self._t('-', time.perf_counter())const = L.i == 0 and self._cm0 is not Noneif const:loc, att = self._cm0else:# raw fp32 projections: msda_cm makes the offsets int32 and runs the softmax per head in the kernelif self.sca_merge:loc, att = L.sca_proj(query), None # [1, 1, Q, 768] fp32else:loc = L.sca_off(query) # [1, 1, Q, 512] fp32att = L.sca_att(query) # [1, 1, Q, 256] fp32t0 = self._t('sca.proj_loc_att', t0)maps = []for l, (h, w) in enumerate(self.sizes):vproj = linear_l1(L.sca_v, xs[l])maps.append(self._maps(vproj, HEADS * 6, h, w, quad=True))_free(vproj)t0 = self._t('sca.value_maps', t0)o = msda_cm(maps, loc, att, g["table"], memory_config=self._mid_sca)_free(*maps)if not const:_free(loc, att)t0 = self._t('sca.msda', t0)y = L.sca_out(o)_free(o)self._t('sca.out', t0)return ydef frame(self, levels: Sequence[Any], g: Dict[str, Any], *, trace: Optional[List] = None):"""``levels``: 4 x ``[1, 1, 6 h w, 256]`` bf16 TILE FPN rows; ``g`` from :meth:`upload_geometry` -> the BEV``[1, 1, Q, 256]`` bf16 (zero where no camera sees the cell)."""import ttnncm = "table" in gif cm and "observed" not in g:# 1 where a camera sees the cell: the count column of the cell table (per frame, on the device)cnt = ttnn.typecast(ttnn.slice(g["table"], [0, 0, 0, 18], [1, 1, Q, 19]), ttnn.bfloat16)g = dict(g, observed=ttnn.gtz(cnt))_free(cnt)own_obs = Trueelse:own_obs = Falseown_base = not cm and "base512" not in gif own_base:g["base512"] = ttnn.repeat(g["base"], ttnn.Shape([1, 1, 1, HEADS]), memory_config=ttnn.DRAM_MEMORY_CONFIG)xs = [ttnn.add(levels[l], self.emb[l], memory_config=ttnn.DRAM_MEMORY_CONFIG) for l in range(LEVELS)]7 unmodified linesif own:_free(query)query, own = q2, Truey = self._sca_cm(L, query, xs, g) if cm else self._sca(L, query, xs, g)q2 = L.norms[1](y, residual=query, cfg=self.cfg)_free(y)if own:2 unmodified linesimport timet0 = self._t('-', time.perf_counter())h1 = L.ffn1(query, memory_config=self._mid_ffn)y = L.ffn2(h1)_free(h1)q2 = L.norms[2](y, residual=query, cfg=self.cfg)8 unmodified lines_free(g.pop("base512"))out = ttnn.multiply(query, g["observed"], memory_config=ttnn.DRAM_MEMORY_CONFIG)_free(query)if own_obs:_free(g["observed"])return out
101 unmodified lines102103104105106107108109101 unmodified lines"""ResNet-50 + FPN for ``batch`` square images of ``size`` px: ``__call__(fm) -> [P3, P4, P5, P6]``."""def __init__(self, state: Dict[str, Any], *, precision: str = PREC):prov = resnet_provider(state)fac = conv_factory(precision)self.stem = ResNetStem(prov, PREFIX + ".conv1", factory=fac)self.stages = ResNetStages(prov, mmdet_names(PREFIX), [3, 4, 6, 3], block="bottleneck", factory=fac)lat = lambda i: (_arr(state[f"{FPN}.lateral_convs.{i}.weight"]), _arr(state[f"{FPN}.lateral_convs.{i}.bias"]))101 unmodified lines102103104105106107108109110111112113114115101 unmodified lines"""ResNet-50 + FPN for ``batch`` square images of ``size`` px: ``__call__(fm) -> [P3, P4, P5, P6]``."""def __init__(self, state: Dict[str, Any], *, precision: str = PREC):import osprov = resnet_provider(state)# double-buffered activations / weights in every conv (AE_IMG_DBUF=1: no gain measured, outputs not bitwise# equal; off)cc = dict(enable_act_double_buffer=True, enable_weights_double_buffer=True) \if os.environ.get("AE_IMG_DBUF", "0") != "0" else Nonefac = conv_factory(precision, conv_config=cc)self.stem = ResNetStem(prov, PREFIX + ".conv1", factory=fac)self.stages = ResNetStages(prov, mmdet_names(PREFIX), [3, 4, 6, 3], block="bottleneck", factory=fac)lat = lambda i: (_arr(state[f"{FPN}.lateral_convs.{i}.weight"]), _arr(state[f"{FPN}.lateral_convs.{i}.bias"]))
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360// SPDX-License-Identifier: Apache-2.0// msda_cm (tt/msda_cm.py), compute: per work item (32 cells x one head; see msda_cm_reader.cpp) the chunk count from// cb_ctl (read_tile_value: the same value on the three TRISCs), then per chunk (slot, level):// 1. for each half h (the points of RISC h): DEST0..2 <- cb_geo_h (fx, fy, attn; fp32); SFPU: W_c = a * wx * wy for// the 4 corners (fx / fy decoded from 2^23 + q) -> cb_w pages 4h .. 4h + 3 (fp32; own point q in column 4 q);// 2. the [32 x 128] quad staging blocks tilized into the 4 corner tiles per point;// 3. for each (point q, corner c): DEST = V * (column 4 q of W_{h,c} broadcast over the 32 channels: an FPU// multiply with the weight tile read 16 q bytes on), packer L1 accumulation into cb_acc (fp32) over ALL chunks// of the item (slots and levels);// then cb_acc -> bf16 -> cb_out.#include <cstdint>
#include "api/compute/common.h"#include "api/compute/compute_kernel_api.h"#include "api/compute/compute_kernel_hw_startup.h"#include "api/compute/eltwise_binary.h"#include "api/compute/pack.h"#include "api/compute/reconfig_data_format.h"#include "api/compute/tile_move_copy.h"#include "api/compute/tilize.h"#include "api/compute/cb_api.h"#include "api/compute/bcast.h"#include "api/compute/eltwise_unary/typecast.h"#include "api/compute/reduce.h"#include "api/compute/softmax.h"#include "ttnn/cpp/ttnn/kernel_lib/reduce_helpers_compute.hpp"#include "ttnn/cpp/ttnn/kernel_lib/eltwise/api/chain.hpp"#include "ttnn/cpp/ttnn/kernel_lib/eltwise/api/convenience.hpp"#include "ttnn/cpp/ttnn/kernel_lib/eltwise/unary/math.hpp"#ifdef MSDA_K_TIMING#include "tools/profiler/kernel_profiler.hpp"#define TNOW() reg_read(RISCV_DEBUG_REG_WALL_CLOCK_L)#endif
#if defined(TRISC_MATH)#include "llk_math_eltwise_unary_sfpu_macros.h"#include "sfpi.h"
namespace ckernel::sfpu {// DEST tiles 0, 1, 2 = fx, fy (as 2^23 + q), attn -> tiles 0..3 = the NW, NE, SW, SE weights (one face per call)inline void msda_cm_w_face() {#pragma GCC unroll 2 for (int d = 0; d < 8; d++) { sfpi::vFloat fx = (sfpi::dst_reg[0] - 8388608.0f) * 0.0000152587890625f; sfpi::vFloat fy = (sfpi::dst_reg[32] - 8388608.0f) * 0.0000152587890625f; sfpi::vFloat a = sfpi::dst_reg[64]; sfpi::vFloat gx = 1.0f - fx; sfpi::vFloat ay0 = a * (1.0f - fy); sfpi::vFloat ay1 = a * fy; sfpi::dst_reg[0] = gx * ay0; sfpi::dst_reg[32] = fx * ay0; sfpi::dst_reg[64] = gx * ay1; sfpi::dst_reg[96] = fx * ay1; sfpi::dst_reg++; }}} // namespace ckernel::sfpu#endif
#if defined(TRISC_UNPACK)// llk_unpack_AB<COL> with srcB read ofs16 x 16 bytes past the tile: the 4 fp32 weight columns 0, 4, 8, 12 of a// corner tile each become column 0 of the unpacked faces (the column the FPU broadcasts)inline void unpack_ab_col_ofs(uint32_t cba, uint32_t cbb, uint32_t ta, uint32_t tb, uint32_t ofs16) { const uint32_t ida = get_operand_id(cba); const uint32_t idb = get_operand_id(cbb); const uint32_t aa = get_local_cb_interface(ida).fifo_rd_ptr - 1 + get_local_cb_interface(ida).fifo_page_size * ta; const uint32_t ab = get_local_cb_interface(idb).fifo_rd_ptr - 1 + get_local_cb_interface(idb).fifo_page_size * tb + ofs16; llk_unpack_AB_impl<BroadcastType::COL>(aa, ab, 0, unpack_src_format[idb]);}#endif
constexpr uint32_t NWORK = get_compile_time_arg_val(0);constexpr uint32_t NC = get_compile_time_arg_val(1);constexpr uint32_t GX = get_compile_time_arg_val(2);constexpr uint32_t P = 8;constexpr uint32_t PH = P / 2;constexpr uint32_t NS = PH * 4;constexpr uint32_t BW = 4; // tiles per quad staging blockconstexpr uint32_t cb_in0 = 0, cb_in1 = 1, cb_geo0 = 2, cb_geo1 = 3, cb_w = 5, cb_acc = 6, cb_ctl = 9, cb_out = 16, cb_tl0 = 19, cb_tl1 = 20;
namespace ckl = compute_kernel_lib;// the per-item conversions (msda_cm_reader.cpp): the raw sampling projection tiles -> int32 (Q16.16; the same SFPU// typecast as ttnn.typecast), the logit tile -> softmax over the head's 32 columns (the LLK sequence of// ttnn.softmax(numeric_stable) on one fp32 tile, as msda_k_compute.cpp: row max -> exp(x - max) -> row sum -> 1 / sum// -> x * (1 / sum)), packed once per reader RISCconstexpr uint32_t cb_scmax = 10, cb_scsum = 11, cb_lg = 12, cb_max = 13, cb_exps = 14, cb_rsum = 15, cb_raw0 = 17, cb_raw1 = 18, cb_off0 = 21, cb_off1 = 22, cb_sm0 = 23, cb_sm1 = 24;
static inline void convert_item() { for (uint32_t h = 0; h < 2; ++h) { const uint32_t cr = h ? cb_raw1 : cb_raw0; const uint32_t co = h ? cb_off1 : cb_off0; cb_wait_front(cr, 1); cb_reserve_back(co, 1); tile_regs_acquire(); reconfig_data_format_srca(cr); copy_init(cr); copy_tile(cr, 0, 0); typecast_tile_init<static_cast<uint32_t>(DataFormat::Float32), static_cast<uint32_t>(DataFormat::Int32)>(); typecast_tile<static_cast<uint32_t>(DataFormat::Float32), static_cast<uint32_t>(DataFormat::Int32)>(0); tile_regs_commit(); tile_regs_wait(); pack_reconfig_data_format(co); pack_tile(0, co); tile_regs_release(); cb_push_back(co, 1); cb_pop_front(cr, 1); } reconfig_data_format(cb_lg, cb_lg); pack_reconfig_data_format(cb_exps); copy_init(cb_lg); compute_kernel_lib::reduce<PoolType::MAX, ReduceDim::REDUCE_ROW, cb_lg, cb_scmax, cb_max, compute_kernel_lib::ReduceInputPolicy::WaitUpfrontNoPop, compute_kernel_lib::ReduceDataFormatReconfigMode::INPUT>( compute_kernel_lib::ReduceInputBlockShape::row(1)); ckl::eltwise_chain( ckl::IterationShape::tiles(1).block_size(1), ckl::BinaryFpu<ckl::BinaryFpuOp::Sub, ckl::input(cb_lg, ckl::WaitPolicy::Upfront, ckl::PopPolicy::AtEnd, ckl::InputTileMapping::Block, ckl::DataFormatReconfig::Disabled), ckl::input(cb_max, ckl::BroadcastDim::Col, ckl::WaitPolicy::Upfront, ckl::PopPolicy::AtEnd)>{}, ckl::Exp<static_cast<ckl::Approx>(0), ckl::Dst::D0>{}, ckl::PackTile<ckl::output(cb_exps, ckl::ReservePolicy::PerBlockSize, ckl::PushPolicy::PerBlockSize, ckl::DataFormatReconfig::Disabled)>{}); cb_wait_front(cb_exps, 1); compute_kernel_lib::reduce<PoolType::SUM, ReduceDim::REDUCE_ROW, cb_exps, cb_scsum, cb_rsum, compute_kernel_lib::ReduceInputPolicy::WaitUpfrontNoPop>( compute_kernel_lib::ReduceInputBlockShape::row(1), compute_kernel_lib::ReduceInputMemoryLayout::contiguous(), compute_kernel_lib::NoAccumulation{}, [](uint32_t) { recip_tile_init<ReciprocalDestAcc::FP32, ReciprocalApproxMode::Precise>(); recip_tile<ReciprocalDestAcc::FP32, ReciprocalApproxMode::Precise>(0); }); cb_wait_front(cb_rsum, 1); cb_reserve_back(cb_sm0, 1); cb_reserve_back(cb_sm1, 1); tile_regs_acquire(); reconfig_data_format(cb_exps, cb_rsum); mul_bcast_cols_init(cb_exps, cb_rsum); mul_tiles_bcast_cols(cb_exps, cb_rsum, 0, 0, 0); tile_regs_commit(); tile_regs_wait(); pack_reconfig_data_format(cb_sm0); pack_tile(0, cb_sm0); pack_tile(0, cb_sm1); tile_regs_release(); cb_push_back(cb_sm0, 1); cb_push_back(cb_sm1, 1); cb_pop_front(cb_exps, 1); cb_pop_front(cb_rsum, 1);}
void kernel_main() { const uint32_t ci = get_absolute_logical_y() * GX + get_absolute_logical_x(); if (ci >= NC || ci >= NWORK) { return; } compute_kernel_hw_startup(cb_lg, cb_scmax, cb_exps); cb_wait_front(cb_scmax, 1); cb_wait_front(cb_scsum, 1); convert_item(); // the first item; then one item ahead#ifdef MSDA_K_TIMING uint32_t t_geo = 0, t_w = 0, t_tl = 0, t_st = 0, t_fin = 0, t_acq = 0, t_pw = 0, t0, t1;#endif for (uint32_t w = ci; w < NWORK; w += NC) { if (w + NC < NWORK) { convert_item(); } cb_wait_front(cb_ctl, 1); const uint32_t nch = read_tile_value(cb_ctl, 0, 0); cb_pop_front(cb_ctl, 1); cb_reserve_back(cb_acc, 1); for (uint32_t ch = 0; ch < nch; ++ch) {#ifdef MSDA_K_TIMING t1 = TNOW();#endif // ---- 1. corner weights per half (exact fp32 copies into DEST: an FPU add would round the 2^23 + q // fractions to tf32), the SFPU on the left faces only (the point columns 0..7)#ifdef MSDA_K_CPNONE // probe: consume the chunk's inputs without any work for (uint32_t h = 0; h < 2; ++h) { cb_wait_front(h ? cb_geo1 : cb_geo0, 3); cb_pop_front(h ? cb_geo1 : cb_geo0, 3); cb_wait_front(h ? cb_in1 : cb_in0, NS); cb_pop_front(h ? cb_in1 : cb_in0, NS); } continue;#endif cb_reserve_back(cb_w, 8);#ifdef MSDA_K_NOW for (uint32_t h = 0; h < 2; ++h) { cb_wait_front(h ? cb_geo1 : cb_geo0, 3); cb_pop_front(h ? cb_geo1 : cb_geo0, 3); }#else for (uint32_t h = 0; h < 2; ++h) { const uint32_t cg = h ? cb_geo1 : cb_geo0;#ifdef MSDA_K_TIMING t0 = TNOW();#endif cb_wait_front(cg, 3);#ifdef MSDA_K_TIMING t_geo += TNOW() - t0;#endif tile_regs_acquire(); reconfig_data_format_srca(cg); copy_init(cg); copy_tile(cg, 0, 0); copy_tile(cg, 1, 1); copy_tile(cg, 2, 2); MATH((SFPU_UNARY_INIT(unused))); MATH((SFPU_UNARY_CALL_NO_TEMPLATE_ARGS(DST_SYNC_MODE, DST_ACCUM_MODE, msda_cm_w_face, 0, VectorMode::C))); tile_regs_commit(); tile_regs_wait(); pack_reconfig_data_format(cb_w); for (uint32_t c = 0; c < 4; ++c) { pack_tile<true>(c, cb_w, h * 4 + c); } tile_regs_release(); cb_pop_front(cg, 3); }#endif cb_push_back(cb_w, 8); cb_wait_front(cb_w, 8);#ifdef MSDA_K_TIMING t0 = TNOW(); t_w += t0 - t1;#endif // ---- 2. quad staging blocks -> corner tiles for (uint32_t h = 0; h < 2; ++h) { const uint32_t cin = h ? cb_in1 : cb_in0; const uint32_t ct = h ? cb_tl1 : cb_tl0; cb_wait_front(cin, NS); cb_reserve_back(ct, NS);#ifdef MSDA_K_NOTL cb_push_back(ct, NS); cb_pop_front(cin, NS); continue;#endif reconfig_data_format_srca(cin); pack_reconfig_data_format(ct); fast_tilize_init(cin, BW, ct); for (uint32_t bk = 0; bk < NS / BW; ++bk) { fast_tilize_block(cin, BW, ct, BW * bk, BW * bk); } fast_tilize_uninit(cin, ct, BW); cb_push_back(ct, NS); cb_pop_front(cin, NS); }#ifdef MSDA_K_TIMING t1 = TNOW(); t_tl += t1 - t0;#endif // ---- 3. the 4 PH (point, corner) steps of each half, accumulated over the item's chunks reconfig_data_format(cb_tl0, cb_w); pack_reconfig_data_format(cb_acc); for (uint32_t h = 0; h < 2; ++h) { const uint32_t ci_ = h ? cb_tl1 : cb_tl0; cb_wait_front(ci_, NS);#ifdef MSDA_K_NOSTEPS for (uint32_t k = 0; k < 4; k += 4) {#else for (uint32_t k = 0; k < NS; k += 4) {#endif#ifdef MSDA_K_TIMING uint32_t ta = TNOW();#endif tile_regs_acquire();#ifdef MSDA_K_TIMING t_acq += TNOW() - ta;#endif // DEST[c] = V_{q, c} * (W_{h, c} column 4 q broadcast over the 32 channels): one FPU product per // (point, corner); the weight tf32 in srcB, as the earlier broadcast matmul gave it (bit for bit)#ifndef MSDA_K_NOMUL if (k == 0) { mul_bcast_cols_init(ci_, cb_w); } for (uint32_t c = 0; c < 4; ++c) { MATH((llk_math_eltwise_binary<EltwiseBinaryType::ELWMUL, BroadcastType::COL, DST_ACCUM_MODE, MATH_FIDELITY, EltwiseBinaryReuseDestType::NONE>(ci_, cb_w, c, true))); UNPACK((unpack_ab_col_ofs(ci_, cb_w, k + c, h * 4 + c, k >> 2))); }#endif tile_regs_commit();#ifdef MSDA_K_TIMING ta = TNOW();#endif tile_regs_wait();#ifdef MSDA_K_TIMING t_pw += TNOW() - ta;#endif#if defined(MSDA_K_ACCOLD) for (uint32_t c = 0; c < 4; ++c) { pack_reconfig_l1_acc((ch == 0 && h == 0 && k == 0 && c == 0) ? 0 : 1); pack_tile<true>(c, cb_acc, 0); }#else // L1 accumulation switched only where its state changes (each switch stalls the packer until // it is idle): off for the item's very first pack, on for the chunk's steps, off again after // them (the weight / tilize packs of the next chunk overwrite) uint32_t c0 = 0; if (h == 0 && k == 0) { if (ch == 0) { pack_tile<true>(0, cb_acc, 0); c0 = 1; } pack_reconfig_l1_acc(1); }#ifdef MSDA_K_PACK1 for (uint32_t c = c0; c < 1; ++c) {#else for (uint32_t c = c0; c < 4; ++c) {#endif pack_tile<true>(c, cb_acc, 0); }#endif tile_regs_release(); } cb_pop_front(ci_, NS); } pack_reconfig_l1_acc(0); cb_pop_front(cb_w, 8);#ifdef MSDA_K_TIMING t0 = TNOW(); t_st += t0 - t1;#endif }#ifdef MSDA_K_CPNONE cb_reserve_back(cb_out, 1); cb_push_back(cb_out, 1); continue;#endif cb_push_back(cb_acc, 1); // ---- fp32 sum -> bf16 output tile cb_wait_front(cb_acc, 1); cb_reserve_back(cb_out, 1); tile_regs_acquire(); reconfig_data_format_srca(cb_acc); copy_init(cb_acc); copy_tile(cb_acc, 0, 0); tile_regs_commit(); tile_regs_wait(); pack_reconfig_data_format(cb_out); pack_tile(0, cb_out); tile_regs_release(); cb_push_back(cb_out, 1); cb_pop_front(cb_acc, 1); }#ifdef MSDA_K_TIMING DeviceTimestampedData("geo", t_geo); DeviceTimestampedData("w", t_w); DeviceTimestampedData("tl", t_tl); DeviceTimestampedData("st", t_st); DeviceTimestampedData("acq", t_acq); DeviceTimestampedData("pw", t_pw);#endif}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338// SPDX-License-Identifier: Apache-2.0// msda_cm (tt/msda_cm.py): the AutoE2E spatial cross-attention as ONE kernel per layer, cell-major. Derived from// msda_k_reader.cpp (quad maps, lean reads, head-minor strided items, fractions as 2^23 + q); this file is the data// movement half and runs on both data-movement RISC-Vs: PART 0 (NCRISC) owns the points [0, 4) of each level,// PART 1 (BRISC) the points [4, 8) and also writes the output tiles.//// Rows are the BEV cells (NQ, NB blocks of 32). Per cell up to K = 2 camera slots; the attention offsets / weights are// the cell's own (the same for every camera that sees it: upstream gathers the same query per camera), the anchors// per camera. Work item w (strided over the cores: w = core, core + NC, ..): b = w / H (block), j = w % H (head).// Per item each RISC reads its header (the next item's while this item's chunks run):// T int32 TILE [1, 1, NQ, 32], tile b: per row, columns 8 k + 2 a + (x, y) = the anchor a of slot k as// round(uv * 2^(16 + SMAX)) (level l: >> l, - 2^15 -> Q16.16 pixels of that level), column 16 + k = the// slot's camera (or -1), column 18 = the cell's camera count (0 .. K);// and hands the compute kernel its raw projection tiles two items ahead (the compute kernel converts them and hands// them back before the item's chunks):// off fp32 TILE [1, 1, NQ, H * 64] (the sampling projection, 2^16-scaled), own tile b * 2 H + 2 j + PART: column// l * 8 + 2 q + (x, y) = the offset of point 4 PART + q of level l (tt/encoder.py orders the columns so)// -> back as int32 (Q16.16) in cb_off;// lg fp32 TILE [1, 1, NQ, H * 32] (the attention projection), tile b * H + j (PART 0 only): column// 16 h + 4 l + q = the logit of point 4 h + q of level l -> back as the softmax over the head's 32 columns// in cb_sm (one copy per RISC), whose own two faces PART, 2 + PART this RISC halves once per item on// 2-camera rows (upstream's mean over the cameras; exact for normal numbers);// and then runs the chunks (slot k, level l) for k < nslot (the block's largest camera count; one empty chunk when// no camera sees the block): per chunk cb_geo <- fx, fy, attn (fp32) of own point q in column 4 q (the compute kernel// broadcasts columns 0, 4, 8, 12 of its weight tiles) and cb_in <- per own point one [32 x 128] row-major staging// block (one 256-byte quad page read per point and row: NW | NE | SW | SE). PART 0 pushes the chunk count to cb_ctl.// value: quad maps per level l, [H * NCAM, HV_l + 1, WV_l + 1, 128] bf16 ROW_MAJOR, L1 interleaved; map j * NCAM + cam.#include <stdint.h>
#include "api/dataflow/dataflow_api.h"#include "ttnn/cpp/ttnn/kernel_lib/reduce_helpers_dataflow.hpp"#ifdef MSDA_K_TIMING#include "tools/profiler/kernel_profiler.hpp"#define TNOW() reg_read(RISCV_DEBUG_REG_WALL_CLOCK_L)#endif
constexpr uint32_t PART = get_compile_time_arg_val(0);constexpr uint32_t cb_in = get_compile_time_arg_val(1);constexpr uint32_t cb_geo = get_compile_time_arg_val(2);constexpr uint32_t cb_t = get_compile_time_arg_val(3); // own scratch: 2 T pagesconstexpr uint32_t cb_out = get_compile_time_arg_val(5);constexpr uint32_t cb_ctl = get_compile_time_arg_val(6);constexpr uint32_t NB = get_compile_time_arg_val(7);constexpr uint32_t NQ = get_compile_time_arg_val(8);constexpr uint32_t H = get_compile_time_arg_val(9);constexpr uint32_t NC = get_compile_time_arg_val(10);constexpr uint32_t GX = get_compile_time_arg_val(11);constexpr uint32_t WRITES_OUT = get_compile_time_arg_val(12);constexpr uint32_t PUSHES_CTL = get_compile_time_arg_val(13);constexpr uint32_t NCAM = get_compile_time_arg_val(14);constexpr uint32_t K = get_compile_time_arg_val(15);constexpr int32_t HV[4] = {get_compile_time_arg_val(16), get_compile_time_arg_val(17), get_compile_time_arg_val(18), get_compile_time_arg_val(19)};constexpr int32_t WV[4] = {get_compile_time_arg_val(20), get_compile_time_arg_val(21), get_compile_time_arg_val(22), get_compile_time_arg_val(23)};// the projection tensors' tile geometry: row stride (tiles) and first column tile of the offsets / logits (separate// tensors: 2 H / 0 and H / 0; one merged [Q, 96 H] projection: 3 H / 0 and 3 H / 2 H)constexpr uint32_t OFF_TW = get_compile_time_arg_val(24);constexpr uint32_t OFF_C0 = get_compile_time_arg_val(25);constexpr uint32_t LG_TW = get_compile_time_arg_val(26);constexpr uint32_t LG_C0 = get_compile_time_arg_val(27);constexpr auto t_args = TensorAccessorArgs<28>();constexpr auto l_args = TensorAccessorArgs<t_args.next_compile_time_args_offset()>();constexpr auto a_args = TensorAccessorArgs<l_args.next_compile_time_args_offset()>();constexpr auto o_args = TensorAccessorArgs<a_args.next_compile_time_args_offset()>();
// the conversion CBs (the compute kernel's softmax scalers / logits; own raw off tiles, converted off, softmax)constexpr uint32_t cb_scmax = 10, cb_scsum = 11, cb_lg = 12;constexpr uint32_t cb_raw = PART ? 18 : 17, cb_off = PART ? 22 : 21, cb_sm = PART ? 24 : 23;
constexpr uint32_t P = 8; // points per levelconstexpr uint32_t PH = P / 2;constexpr uint32_t NS = PH * 4; // staging tiles per chunk and RISCconstexpr uint32_t TB16 = 2048, TB32 = 4096, QPAGE = 256, FACE32 = 1024;constexpr uint32_t NWORK = NB * H;static_assert(K >= 1 && K <= 2, "msda_cm: 1 or 2 camera slots");
constexpr uint32_t FRAC0 = 0x4B000000u; // fp32 2^23: the compute kernel takes (f - 2^23) * 2^-16static inline uint32_t q16_frac(uint32_t q) { return FRAC0 | q; }// x / 2 for an fp32 softmax weight (exact for normal numbers; the tiny denormal ones become 0)static inline uint32_t half_bits(uint32_t v) { return ((v >> 23) & 0xFF) > 1 ? v - 0x800000u : 0u; }
static inline void zero_l1(uint32_t addr, uint32_t bytes) { const uint64_t z = get_noc_addr(MEM_ZEROS_BASE); for (uint32_t o = 0; o < bytes; o += MEM_ZEROS_SIZE) { noc_async_read(z, addr + o, MEM_ZEROS_SIZE); }}static inline void quad_read(uint32_t xy, uint32_t src, uint32_t dst) { while (!noc_cmd_buf_ready(noc_index, read_cmd_buf)); NOC_CMD_BUF_WRITE_REG(noc_index, read_cmd_buf, NOC_RET_ADDR_LO, dst); NOC_CMD_BUF_WRITE_REG(noc_index, read_cmd_buf, NOC_TARG_ADDR_LO, src); NOC_CMD_BUF_WRITE_REG(noc_index, read_cmd_buf, NOC_TARG_ADDR_COORDINATE, xy); NOC_CMD_BUF_WRITE_REG(noc_index, read_cmd_buf, NOC_CMD_CTRL, NOC_CTRL_SEND_REQ);}
// one chunk (slot k, level L) of own points: geo + reads; returns the number of reads issuedtemplate <uint32_t L>static inline uint32_t chunk(const int32_t* T, const int32_t* OFF, const uint32_t* SM, uint32_t* fx, uint32_t* fy, uint32_t* at, uint32_t k, uint32_t nslot, uint32_t rows, uint32_t jcam, uint32_t mbase, uint32_t in_base) { constexpr int32_t hv = HV[L], wv = WV[L]; constexpr uint32_t wv1 = static_cast<uint32_t>(wv + 1); constexpr uint32_t plane = static_cast<uint32_t>((hv + 1) * (wv + 1)); constexpr uint32_t OFFL = (L >> 1) * 256 + (L & 1) * 8; // element of (row 0, level L) in the off tile constexpr uint32_t ATTL = L * 4; // column of level L in the own faces of cb_sm uint32_t nrd = 0; for (uint32_t r = 0; r < 32; ++r) { const uint32_t rb = ((r >> 4) << 9) + ((r & 15) << 4); // element of (r, 0) in a full tile const int32_t cam = nslot ? T[rb + 256 + k] : -1; if (!(r < rows && cam >= 0)) {#pragma GCC unroll 4 for (uint32_t q = 0; q < PH; ++q) { at[rb + 4 * q] = 0; // fx / fy keep earlier finite values: the weights are 0 } continue; } const uint32_t pbase = (jcam + static_cast<uint32_t>(cam)) * plane + wv1 + 1; // + (y0 * (wv + 1) + x0) const int32_t* tk = T + rb + 8 * k; const int32_t* orow = OFF + rb + OFFL; const uint32_t* arow = SM + ((((r >> 4) << 1) + PART) << 8) + ((r & 15) << 4) + ATTL; const uint32_t sbase = in_base + r * QPAGE;#pragma GCC unroll 4 for (uint32_t q = 0; q < PH; ++q) { const int32_t vx = ((tk[2 * q] >> L) - 32768) + orow[2 * q]; const int32_t vy = ((tk[2 * q + 1] >> L) - 32768) + orow[2 * q + 1]; const int32_t x0 = vx >> 16; const int32_t y0 = vy >> 16; // all four corners outside <=> x0 + 1 not in [0, wv] or y0 + 1 not in [0, hv] if (static_cast<uint32_t>(x0 + 1) > static_cast<uint32_t>(wv) || static_cast<uint32_t>(y0 + 1) > static_cast<uint32_t>(hv)) { at[rb + 4 * q] = 0; continue; } fx[rb + 4 * q] = q16_frac(static_cast<uint32_t>(vx) & 0xFFFF); fy[rb + 4 * q] = q16_frac(static_cast<uint32_t>(vy) & 0xFFFF); at[rb + 4 * q] = arow[q];#ifdef MSDA_K_NOREAD continue;#endif const uint32_t pg = pbase + static_cast<uint32_t>(y0) * wv1 + static_cast<uint32_t>(x0); const uint32_t row = udivsi3_const_divisor<NUM_L1_BANKS>(pg); const uint32_t bank = pg - row * NUM_L1_BANKS; quad_read(l1_bank_to_noc_xy[noc_index][bank], mbase + row * QPAGE + bank_to_l1_offset[bank], sbase + q * 4 * TB16); nrd += 1; } } return nrd;}
void kernel_main() { const uint32_t ci = get_absolute_logical_y() * GX + get_absolute_logical_x(); if (ci >= NC || ci >= NWORK) { return; } const auto t_acc = TensorAccessor(t_args, get_common_arg_val<uint32_t>(0), TB32); const auto l_acc = TensorAccessor(l_args, get_common_arg_val<uint32_t>(1), TB32); const auto a_acc = TensorAccessor(a_args, get_common_arg_val<uint32_t>(2), TB32); const auto o_acc = TensorAccessor(o_args, get_common_arg_val<uint32_t>(3), TB16); const uint32_t maddr[4] = {get_common_arg_val<uint32_t>(4), get_common_arg_val<uint32_t>(5), get_common_arg_val<uint32_t>(6), get_common_arg_val<uint32_t>(7)};
// the geo pages and the staging blocks: zero once (unwritten columns stay 0 / finite) cb_reserve_back(cb_geo, 6); zero_l1(get_write_ptr(cb_geo), 6 * TB32); cb_reserve_back(cb_in, 2 * NS); zero_l1(get_write_ptr(cb_in), 2 * NS * TB16); if constexpr (PUSHES_CTL) { // the softmax's reduce scalers, as ttnn's softmax reader makes them dataflow_kernel_lib::calculate_and_prepare_reduce_scaler<cb_scmax, ckernel::PoolType::MAX, ckernel::ReduceDim::REDUCE_ROW>(); dataflow_kernel_lib::calculate_and_prepare_reduce_scaler<cb_scsum, ckernel::PoolType::SUM, ckernel::ReduceDim::REDUCE_ROW>(); } // two T sets: the next item's T is read while this item's chunks run cb_reserve_back(cb_t, 2); const uint32_t sbuf = get_write_ptr(cb_t); noc_async_read_barrier(); // the raw projection tiles of item w into the next free page of cb_raw (and cb_lg) auto raw = [&](uint32_t w) { const uint32_t b = w / H; const uint32_t j = w - b * H; cb_reserve_back(cb_raw, 1); noc_async_read(l_acc.get_noc_addr(b * OFF_TW + OFF_C0 + 2 * j + PART), get_write_ptr(cb_raw), TB32); if constexpr (PUSHES_CTL) { cb_reserve_back(cb_lg, 1); noc_async_read(a_acc.get_noc_addr(b * LG_TW + LG_C0 + j), get_write_ptr(cb_lg), TB32); } }; auto raw_push = [&]() { cb_push_back(cb_raw, 1); if constexpr (PUSHES_CTL) { cb_push_back(cb_lg, 1); } };#ifdef MSDA_K_TIMING uint32_t t_res = 0, t_loop = 0, t_bar = 0, t_out = 0, t_hdr = 0, t0, t1;#endif
uint32_t prev = 0xFFFFFFFF; uint32_t set = 0; // item ci's raw tiles and T, then item ci + NC's raw tiles in flight (the compute kernel converts item w + NC // before it takes item w's chunks) noc_async_read(t_acc.get_noc_addr(ci / H), sbuf, TB32); raw(ci); noc_async_read_barrier(); raw_push(); if (ci + NC < NWORK) { raw(ci + NC); } for (uint32_t w = ci; w < NWORK; w += NC) { const uint32_t b = w / H; const uint32_t j = w - b * H;#ifdef MSDA_K_TIMING t0 = TNOW();#endif noc_async_read_barrier(); const uint32_t tbase = sbuf + set * TB32; if (w + NC < NWORK) { raw_push(); noc_async_read(t_acc.get_noc_addr((w + NC) / H), sbuf + (set ^ 1) * TB32, TB32); if (w + 2 * NC < NWORK) { raw(w + 2 * NC); } } set ^= 1; int32_t* T = reinterpret_cast<int32_t*>(tbase); cb_wait_front(cb_off, 1); cb_wait_front(cb_sm, 1); const int32_t* OFF = reinterpret_cast<const int32_t*>(get_read_ptr(cb_off)); uint32_t* const SM = reinterpret_cast<uint32_t*>(get_read_ptr(cb_sm)); const uint32_t rows = NQ - b * 32 < 32 ? NQ - b * 32 : 32; uint32_t nslot = 0; for (uint32_t r = 0; r < rows; ++r) { const uint32_t c = static_cast<uint32_t>(T[((r >> 4) << 9) + ((r & 15) << 4) + 256 + 2]); nslot = c > nslot ? c : nslot; if (c >= 2) { // upstream's mean over the 2 cameras: the row's 16 own weights halved once per item uint32_t* arow = SM + ((((r >> 4) << 1) + PART) << 8) + ((r & 15) << 4);#pragma GCC unroll 16 for (uint32_t i = 0; i < 16; ++i) { arow[i] = half_bits(arow[i]); } } } nslot = nslot > K ? K : nslot; const uint32_t nch = nslot ? nslot * 4 : 1; if constexpr (PUSHES_CTL) { cb_reserve_back(cb_ctl, 1); reinterpret_cast<volatile tt_l1_ptr uint32_t*>(get_write_ptr(cb_ctl))[0] = nch; cb_push_back(cb_ctl, 1); }#ifdef MSDA_K_TIMING t1 = TNOW(); t_hdr += t1 - t0;#endif const uint32_t jcam = j * NCAM; for (uint32_t ch = 0; ch < nch; ++ch) { const uint32_t k = ch >> 2; const uint32_t l = ch & 3;#ifdef MSDA_K_TIMING t0 = TNOW();#endif cb_reserve_back(cb_geo, 3); cb_reserve_back(cb_in, NS);#ifdef MSDA_K_TIMING t1 = TNOW(); t_res += t1 - t0;#endif#ifdef MSDA_K_RDNONE // probe: hand the compute kernel the chunk's pages without any reader work cb_push_back(cb_geo, 3); cb_push_back(cb_in, NS); continue;#endif const uint32_t g_addr = get_write_ptr(cb_geo); const uint32_t in_base = get_write_ptr(cb_in); uint32_t* fx = reinterpret_cast<uint32_t*>(g_addr); uint32_t* fy = reinterpret_cast<uint32_t*>(g_addr + TB32); uint32_t* at = reinterpret_cast<uint32_t*>(g_addr + 2 * TB32); noc_async_read_one_packet_set_state(get_noc_addr(MEM_ZEROS_BASE), QPAGE); uint32_t nrd; if (l == 0) { nrd = chunk<0>(T, OFF, SM, fx, fy, at, k, nslot, rows, jcam, maddr[0], in_base); } else if (l == 1) { nrd = chunk<1>(T, OFF, SM, fx, fy, at, k, nslot, rows, jcam, maddr[1], in_base); } else if (l == 2) { nrd = chunk<2>(T, OFF, SM, fx, fy, at, k, nslot, rows, jcam, maddr[2], in_base); } else { nrd = chunk<3>(T, OFF, SM, fx, fy, at, k, nslot, rows, jcam, maddr[3], in_base); } asm volatile("" ::: "memory"); noc_reads_num_issued[noc_index] += nrd;#ifdef MSDA_K_TIMING t0 = TNOW(); t_loop += t0 - t1;#endif noc_async_read_barrier();#ifdef MSDA_K_TIMING t1 = TNOW(); t_bar += t1 - t0;#endif cb_push_back(cb_geo, 3); cb_push_back(cb_in, NS); } cb_pop_front(cb_off, 1); cb_pop_front(cb_sm, 1); if constexpr (WRITES_OUT) { if (prev != 0xFFFFFFFF) {#ifdef MSDA_K_TIMING t0 = TNOW();#endif cb_wait_front(cb_out, 1);#ifdef MSDA_K_TIMING t_out += TNOW() - t0;#endif noc_async_write(get_read_ptr(cb_out), o_acc.get_noc_addr(prev), TB16); noc_async_writes_flushed(); cb_pop_front(cb_out, 1); } } prev = w; } if constexpr (WRITES_OUT) { cb_wait_front(cb_out, 1); noc_async_write(get_read_ptr(cb_out), o_acc.get_noc_addr(prev), TB16); noc_async_write_barrier(); cb_pop_front(cb_out, 1); }#ifdef MSDA_K_TIMING DeviceTimestampedData("res", t_res); DeviceTimestampedData("hdr", t_hdr); DeviceTimestampedData("loop", t_loop); DeviceTimestampedData("bar", t_bar); DeviceTimestampedData("out", t_out);#endif}24 unmodified lines2526272829301 unmodified line32333435363738394041429 unmodified lines52535455565758598 unmodified lines68697071727366 unmodified lines1401411421431441451462 unmodified lines1491501511521531541558 unmodified lines1641651661671681691701711721731741759 unmodified lines1851861871881891901911921931941951961971981992002012022032042052062072082091 unmodified line2112122132142152162172182192208 unmodified lines2292302312322332348 unmodified lines2432442452462472481 unmodified line2502512522532542558 unmodified lines26426526626726824 unmodified lines#include "ttnn/cpp/ttnn/kernel_lib/eltwise/api/chain.hpp"#include "ttnn/cpp/ttnn/kernel_lib/eltwise/api/convenience.hpp"#include "ttnn/cpp/ttnn/kernel_lib/eltwise/unary/math.hpp"#if defined(TRISC_MATH)#include "llk_math_eltwise_unary_sfpu_macros.h"1 unmodified linenamespace ckernel::sfpu {// DEST tiles 0, 1, 2 = fx, fy, attn -> tiles 0..3 = the NW, NE, SW, SE weights (one face per call)inline void msda_k_w_face() {#pragma GCC unroll 2for (int d = 0; d < 8; d++) {sfpi::vFloat fx = sfpi::dst_reg[0];sfpi::vFloat fy = sfpi::dst_reg[32];sfpi::vFloat a = sfpi::dst_reg[64];sfpi::vFloat gx = 1.0f - fx;sfpi::vFloat ay0 = a * (1.0f - fy);9 unmodified linesinline void msda_k_w_face_sm() {#pragma GCC unroll 2for (int d = 0; d < 8; d++) {sfpi::vFloat fx = sfpi::dst_reg[0];sfpi::vFloat fy = sfpi::dst_reg[32];sfpi::vFloat a = sfpi::dst_reg[64] * sfpi::dst_reg[96];sfpi::vFloat gx = 1.0f - fx;sfpi::vFloat ay0 = a * (1.0f - fy);8 unmodified lines} // namespace ckernel::sfpu#endifnamespace ckl = compute_kernel_lib;constexpr uint32_t P = get_compile_time_arg_val(1);66 unmodified linescompute_kernel_hw_startup(cb_geo0, cb_geo0, cb_w);}cb_wait_front(cb_e, P);for (uint32_t w = w0; w < w1; w += wstep) {if constexpr (SM) {softmax_tile();cb_wait_front(cb_sm, 1);2 unmodified linescb_reserve_back(cb_w, 8);for (uint32_t h = 0; h < 2; ++h) {const uint32_t cg = h ? cb_geo1 : cb_geo0;cb_wait_front(cg, 3);tile_regs_acquire();reconfig_data_format_srca(cg);copy_init(cg);8 unmodified linescopy_tile(cb_msk, h, 3);MATH((SFPU_UNARY_INIT(unused)));MATH((SFPU_UNARY_CALL_NO_TEMPLATE_ARGS(DST_SYNC_MODE, DST_ACCUM_MODE, msda_k_w_face_sm, 0,VectorMode::RC)));} else {copy_tile(cg, 2, 2);MATH((SFPU_UNARY_INIT(unused)));MATH((SFPU_UNARY_CALL_NO_TEMPLATE_ARGS(DST_SYNC_MODE, DST_ACCUM_MODE, msda_k_w_face, 0,VectorMode::RC)));}tile_regs_commit();tile_regs_wait();9 unmodified linescb_pop_front(cb_sm, 1);}cb_wait_front(cb_w, 8);if constexpr (PAIRS) {for (uint32_t h = 0; h < 2; ++h) {const uint32_t cin = h ? cb_in1 : cb_in0;const uint32_t ct = h ? cb_tl1 : cb_tl0;cb_wait_front(cin, NS);cb_reserve_back(ct, NS);reconfig_data_format_srca(cin);pack_reconfig_data_format(ct);#ifdef MSDA_K_FAST_TILIZE// BEVFORMER_MSDA_TILIZE=fast: the BH fast tilize (a lossless bf16 reorder)fast_tilize_init(cin, 2, ct);for (uint32_t bk = 0; bk < NS / 2; ++bk) {fast_tilize_block(cin, 2, ct, 2 * bk, 2 * bk);}fast_tilize_uninit(cin, ct, 2);#elsetilize_init(cin, 2, ct);for (uint32_t bk = 0; bk < NS / 2; ++bk) {tilize_block(cin, 2, ct, 2 * bk, 2 * bk);}tilize_uninit(cin, ct);#endif1 unmodified linecb_pop_front(cin, NS);}}// ---- 2. the 4P (point, corner) stepscb_reserve_back(cb_acc, 1);reconfig_data_format_srca(cb_e);reconfig_data_format_srcb(cb_w);pack_reconfig_data_format(cb_acc);for (uint32_t h = 0; h < 2; ++h) {const uint32_t ci_ = PAIRS ? (h ? cb_tl1 : cb_tl0) : (h ? cb_in1 : cb_in0);8 unmodified lines// the same fp32 sum order as one step per acquire; 2 inits and 1 sync per 4 steps instead of 8 / 4)const uint32_t p = h * PH + (k >> 2);tile_regs_acquire();matmul_init(cb_w, cb_e);for (uint32_t c = 0; c < 4; ++c) {matmul_tiles(cb_w, cb_e, h * 4 + c, p, c);8 unmodified linespack_reconfig_l1_acc((h == 0 && k == 0 && c == 0) ? 0 : 1);pack_tile<true>(c, cb_acc, 0);}tile_regs_release();}cb_pop_front(ci_, NS);1 unmodified linepack_reconfig_l1_acc(0);cb_push_back(cb_acc, 1);cb_pop_front(cb_w, 8);// ---- 3. fp32 sum -> bf16 output tilecb_wait_front(cb_acc, 1);cb_reserve_back(cb_out, 1);8 unmodified linestile_regs_release();cb_push_back(cb_out, 1);cb_pop_front(cb_acc, 1);}}24 unmodified lines252627282930313233341 unmodified line3637383940414243444546479 unmodified lines57585960616263648 unmodified lines73747576777879808182838485868788899066 unmodified lines1571581591601611621631641651661671681692 unmodified lines1721731741751761771781791801811821831848 unmodified lines1931941951961971981992002012022032049 unmodified lines2142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482491 unmodified line2512522532542552562572582592602612622632642652662672688 unmodified lines2772782792802812822832842852862872882892902912922932942952962972982993003013023033043058 unmodified lines3143153163173183193201 unmodified line3223233243253263273283293303318 unmodified lines34034134234334434534634734834935035135235335435524 unmodified lines#include "ttnn/cpp/ttnn/kernel_lib/eltwise/api/chain.hpp"#include "ttnn/cpp/ttnn/kernel_lib/eltwise/api/convenience.hpp"#include "ttnn/cpp/ttnn/kernel_lib/eltwise/unary/math.hpp"#ifdef MSDA_K_TIMING#include "tools/profiler/kernel_profiler.hpp"#define TNOW() reg_read(RISCV_DEBUG_REG_WALL_CLOCK_L)#endif#if defined(TRISC_MATH)#include "llk_math_eltwise_unary_sfpu_macros.h"1 unmodified linenamespace ckernel::sfpu {// DEST tiles 0, 1, 2 = fx, fy, attn -> tiles 0..3 = the NW, NE, SW, SE weights (one face per call)// fx / fy arrive as the fp32 2^23 + q (q the 16-bit fraction, msda_k_reader.cpp): (f - 2^23) * 2^-16 is exactinline void msda_k_w_face() {#pragma GCC unroll 2for (int d = 0; d < 8; d++) {sfpi::vFloat fx = (sfpi::dst_reg[0] - 8388608.0f) * 0.0000152587890625f;sfpi::vFloat fy = (sfpi::dst_reg[32] - 8388608.0f) * 0.0000152587890625f;sfpi::vFloat a = sfpi::dst_reg[64];sfpi::vFloat gx = 1.0f - fx;sfpi::vFloat ay0 = a * (1.0f - fy);9 unmodified linesinline void msda_k_w_face_sm() {#pragma GCC unroll 2for (int d = 0; d < 8; d++) {sfpi::vFloat fx = (sfpi::dst_reg[0] - 8388608.0f) * 0.0000152587890625f;sfpi::vFloat fy = (sfpi::dst_reg[32] - 8388608.0f) * 0.0000152587890625f;sfpi::vFloat a = sfpi::dst_reg[64] * sfpi::dst_reg[96];sfpi::vFloat gx = 1.0f - fx;sfpi::vFloat ay0 = a * (1.0f - fy);8 unmodified lines} // namespace ckernel::sfpu#endif#if defined(TRISC_UNPACK)// llk_unpack_AB<COL> with srcB read ofs16 x 16 bytes past the tile (see msda_cm_compute.cpp)inline void unpack_ab_col_ofs(uint32_t cba, uint32_t cbb, uint32_t ta, uint32_t tb, uint32_t ofs16) {const uint32_t ida = get_operand_id(cba);const uint32_t idb = get_operand_id(cbb);const uint32_t aa = get_local_cb_interface(ida).fifo_rd_ptr - 1 + get_local_cb_interface(ida).fifo_page_size * ta;const uint32_t ab =get_local_cb_interface(idb).fifo_rd_ptr - 1 + get_local_cb_interface(idb).fifo_page_size * tb + ofs16;llk_unpack_AB_impl<BroadcastType::COL>(aa, ab, 0, unpack_src_format[idb]);}#endifnamespace ckl = compute_kernel_lib;constexpr uint32_t P = get_compile_time_arg_val(1);66 unmodified linescompute_kernel_hw_startup(cb_geo0, cb_geo0, cb_w);}cb_wait_front(cb_e, P);#ifdef MSDA_K_TIMINGuint32_t t_geo = 0, t_in = 0, t_w = 0, t_tl = 0, t_st = 0, t_fin = 0, t0, t1;#endiffor (uint32_t w = w0; w < w1; w += wstep) {#ifdef MSDA_K_TIMINGt1 = TNOW();#endifif constexpr (SM) {softmax_tile();cb_wait_front(cb_sm, 1);2 unmodified linescb_reserve_back(cb_w, 8);for (uint32_t h = 0; h < 2; ++h) {const uint32_t cg = h ? cb_geo1 : cb_geo0;#ifdef MSDA_K_TIMINGt0 = TNOW();#endifcb_wait_front(cg, 3);#ifdef MSDA_K_TIMINGt_geo += TNOW() - t0;#endiftile_regs_acquire();reconfig_data_format_srca(cg);copy_init(cg);8 unmodified linescopy_tile(cb_msk, h, 3);MATH((SFPU_UNARY_INIT(unused)));MATH((SFPU_UNARY_CALL_NO_TEMPLATE_ARGS(DST_SYNC_MODE, DST_ACCUM_MODE, msda_k_w_face_sm, 0,SM == 2 ? VectorMode::RC : VectorMode::C)));} else {copy_tile(cg, 2, 2);MATH((SFPU_UNARY_INIT(unused)));MATH((SFPU_UNARY_CALL_NO_TEMPLATE_ARGS(DST_SYNC_MODE, DST_ACCUM_MODE, msda_k_w_face, 0,VectorMode::C))); // point columns < 16 (no joint mode here)}tile_regs_commit();tile_regs_wait();9 unmodified linescb_pop_front(cb_sm, 1);}cb_wait_front(cb_w, 8);#ifdef MSDA_K_TIMINGt0 = TNOW();t_w += t0 - t1;#endifif constexpr (PAIRS) {for (uint32_t h = 0; h < 2; ++h) {const uint32_t cin = h ? cb_in1 : cb_in0;const uint32_t ct = h ? cb_tl1 : cb_tl0;#ifdef MSDA_K_TIMINGt1 = TNOW();#endifcb_wait_front(cin, NS);#ifdef MSDA_K_TIMINGt_in += TNOW() - t1;#endifcb_reserve_back(ct, NS);reconfig_data_format_srca(cin);pack_reconfig_data_format(ct);constexpr uint32_t BW = 2 * PAIRS; // tiles per staging block: 2 (pair rows), 4 (quad rows)#ifdef MSDA_K_FAST_TILIZE// BEVFORMER_MSDA_TILIZE=fast: the BH fast tilize (a lossless bf16 reorder)fast_tilize_init(cin, BW, ct);for (uint32_t bk = 0; bk < NS / BW; ++bk) {fast_tilize_block(cin, BW, ct, BW * bk, BW * bk);}fast_tilize_uninit(cin, ct, BW);#elsetilize_init(cin, BW, ct);for (uint32_t bk = 0; bk < NS / BW; ++bk) {tilize_block(cin, BW, ct, BW * bk, BW * bk);}tilize_uninit(cin, ct);#endif1 unmodified linecb_pop_front(cin, NS);}}#ifdef MSDA_K_TIMINGt1 = TNOW();t_tl += t1 - t0;#endif// ---- 2. the 4P (point, corner) stepscb_reserve_back(cb_acc, 1);#ifdef MSDA_K_COLBreconfig_data_format(cb_tl0, cb_w);#elsereconfig_data_format_srca(cb_e);reconfig_data_format_srcb(cb_w);#endifpack_reconfig_data_format(cb_acc);for (uint32_t h = 0; h < 2; ++h) {const uint32_t ci_ = PAIRS ? (h ? cb_tl1 : cb_tl0) : (h ? cb_in1 : cb_in0);8 unmodified lines// the same fp32 sum order as one step per acquire; 2 inits and 1 sync per 4 steps instead of 8 / 4)const uint32_t p = h * PH + (k >> 2);tile_regs_acquire();#ifdef MSDA_K_COLB// DEST[c] = V_{p, c} * (column 4 p of W_{h, c} broadcast over the 32 channels)if (k == 0) {mul_bcast_cols_init(ci_, cb_w);}for (uint32_t c = 0; c < 4; ++c) {MATH((llk_math_eltwise_binary<EltwiseBinaryType::ELWMUL, BroadcastType::COL, DST_ACCUM_MODE,MATH_FIDELITY, EltwiseBinaryReuseDestType::NONE>(ci_, cb_w, c, true)));UNPACK((unpack_ab_col_ofs(ci_, cb_w, k + c, h * 4 + c, p)));}tile_regs_commit();tile_regs_wait();// L1 accumulation switched only where its state changes (each switch stalls the packer)uint32_t c0 = 0;if (h == 0 && k == 0) {pack_tile<true>(0, cb_acc, 0);pack_reconfig_l1_acc(1);c0 = 1;}for (uint32_t c = c0; c < 4; ++c) {pack_tile<true>(c, cb_acc, 0);}#elsematmul_init(cb_w, cb_e);for (uint32_t c = 0; c < 4; ++c) {matmul_tiles(cb_w, cb_e, h * 4 + c, p, c);8 unmodified linespack_reconfig_l1_acc((h == 0 && k == 0 && c == 0) ? 0 : 1);pack_tile<true>(c, cb_acc, 0);}#endiftile_regs_release();}cb_pop_front(ci_, NS);1 unmodified linepack_reconfig_l1_acc(0);cb_push_back(cb_acc, 1);cb_pop_front(cb_w, 8);#ifdef MSDA_K_TIMINGt0 = TNOW();t_st += t0 - t1;#endif// ---- 3. fp32 sum -> bf16 output tilecb_wait_front(cb_acc, 1);cb_reserve_back(cb_out, 1);8 unmodified linestile_regs_release();cb_push_back(cb_out, 1);cb_pop_front(cb_acc, 1);#ifdef MSDA_K_TIMINGt_fin += TNOW() - t0;#endif}#ifdef MSDA_K_TIMINGDeviceTimestampedData("geo", t_geo);DeviceTimestampedData("in", t_in);DeviceTimestampedData("w", t_w);DeviceTimestampedData("tl", t_tl);DeviceTimestampedData("st", t_st);DeviceTimestampedData("fin", t_fin);#endif}
9 unmodified lines101112131415168 unmodified lines25262728293068 unmodified lines9910010110210310410510628 unmodified lines13513613713813914050 unmodified lines19119219319419519619719819940 unmodified lines2402412422432442452462477 unmodified lines2552562572582592602612622632642652667 unmodified lines27427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832910 unmodified lines3403413423433443453463473483493503513523533543553563573582 unmodified lines36136236336436536612 unmodified lines3793803813823833843853863 unmodified lines3903913923933943953963973983994004014024034044054064074084094103 unmodified lines4144154164174184194204214224234244254264274281 unmodified line4304314324334344354364374384394409 unmodified lines// so there is no cross-RISC handshake.//// Work item w (contiguous range per core, core index from the logical coordinates: common RT args only, probe P3):// j = w / NB (head block), b = w % NB (32-query block); value map m = j * SUB + b / (NB / SUB);// loc int32 TILE [1, H, NB * 32, 32], tile j * NB + b: row r, column 2p / 2p + 1 = x / y of point p as// round(pixel * 2^16) (pixel = (g + 1) size / 2 - 0.5, align_corners=False);// attn fp32 TILE [1, H, NB * 32, 32], tile j * NB + b: the softmax weight of point p in column p;8 unmodified lines#include <stdint.h>#include "api/dataflow/dataflow_api.h"#include "ttnn/cpp/ttnn/kernel_lib/reduce_helpers_dataflow.hpp"constexpr uint32_t PART = get_compile_time_arg_val(1);68 unmodified linesconstexpr uint32_t P0 = PART * PH;constexpr uint32_t NS = PH * 4; // steps (tiles) per item and RISCconstexpr uint32_t TB16 = 2048, TB32 = 4096;constexpr uint32_t VPAGE = VSRC == 0 ? 64 : (VSRC == 2 ? 128 : 2048); // RM stick; pixel pair; TILE: a bf16 tilestatic_assert(VSRC != 2 || !SKIP, "msda_k: pair maps and SKIP are exclusive");constexpr uint32_t BPS = NB / SUB;constexpr uint32_t MAP = static_cast<uint32_t>(HV * WV);constexpr int32_t LOC_LIM = 1 << 28; // |pixel| < 4096 after the clamp: no overflow below28 unmodified linesconst uint32_t n = 31 - __builtin_clz(q);return ((127 - 16 + n) << 23) | ((q << (23 - n)) & 0x7FFFFF);}// one corner stick (32 channels) -> the face rows at dst (channels 0..15) and dst + 512 (16..31). pos: RM page// (VSRC 0) or slice * TPH * 32 + row (VSRC 1).50 unmodified linesif (ci >= NC) {return;}const uint32_t w0 = SKIP ? ci : ci * NWORK / NC;const uint32_t w1 = SKIP ? NWORK : (ci + 1) * NWORK / NC;const uint32_t wstep = SKIP ? NC : 1;if (w0 >= w1) {return;}40 unmodified linesfor (uint32_t h = 0; h < 2; ++h) {for (uint32_t r = 0; r < 32; ++r) {for (uint32_t c = 0; c < 32; ++c) {m[h * 1024 + tile_elem(r, c)] =(c >= ECOL + h * PH && c < ECOL + (h + 1) * PH) ? 0x3F800000u : 0u;}}}7 unmodified lines// the geo pages: zero once (columns >= P and the right faces stay zero / finite forever)cb_reserve_back(cb_geo, 6);zero_l1(get_write_ptr(cb_geo), 6 * TB32);if constexpr (SKIP) {cb_reserve_back(cb_in, 2 * NS);zero_l1(get_write_ptr(cb_in), 2 * NS * TB16);}cb_reserve_back(cb_loc, 1);const uint32_t lbuf = get_write_ptr(cb_loc);uint32_t bbuf = 0;if constexpr (LOCF) {cb_reserve_back(cb_base, 1);7 unmodified linesvolatile tt_l1_ptr int32_t* loc = reinterpret_cast<volatile tt_l1_ptr int32_t*>(lbuf);uint32_t prev = 0xFFFFFFFF;for (uint32_t w = w0; w < w1; w += wstep) {const uint32_t j = w / NB;const uint32_t b = w - j * NB;// VSRC 0: page of the map's pixel 0; VSRC 1: the slice's first tile row + the map's first row in itconst uint32_t jm = j / HDIV;const uint32_t sg = segment(b);const uint32_t vbase = VSRC == 0 ? (jm * SUB + sg) * MAP: VSRC == 2 ? (jm * SUB + sg) * HV * (WV + 1): VSRC == 3 ? sg * MAP: jm * TPH * 32 + sg * MAP;g_hj = j;cb_reserve_back(cb_geo, 3);cb_reserve_back(cb_in, NS);const uint32_t g_addr = get_write_ptr(cb_geo);const uint32_t in_base = get_write_ptr(cb_in);const uint32_t ltile = LOC_HS == 0 ? j * NB + b : b * LOC_TW + (j * LOC_HS + LOC_OFF) / 32;const uint32_t lcol = LOC_HS == 0 ? 0 : (j * LOC_HS + LOC_OFF) % 32;noc_async_read(l_acc.get_noc_addr(ltile), lbuf, TB32);if constexpr (LOCF) {noc_async_read(bs_acc.get_noc_addr(b * 2 + (LOC_OFF % 64) / 32), bbuf, TB32);}if constexpr (SM) {if constexpr (MAKES_E) {noc_async_read(a_acc.get_noc_addr(b * AT_TW + (SM == 2 ? j : (j * P) / 32)), get_write_ptr(cb_scr),TB32);}} else {noc_async_read(a_acc.get_noc_addr(j * NB + b), g_addr + 2 * TB32, TB32);}noc_async_read_barrier();if constexpr (SM && MAKES_E) {// the head's logit tile: columns 0..P-1 <- compact columns (j P) % 32 + p; columns >= P keep PADcb_reserve_back(cb_lg, 1);volatile tt_l1_ptr uint32_t* lg = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(get_write_ptr(cb_lg));volatile tt_l1_ptr uint32_t* src = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(get_write_ptr(cb_scr));const uint32_t acol = (j * P) % 32;for (uint32_t r = 0; r < 32; ++r) {const bool ok = b * 32 + r < NQ;if constexpr (SM == 2) {for (uint32_t c = 0; c < 32; ++c) {lg[tile_elem(r, c)] = ok ? src[tile_elem(r, c)] : 0u;}} else {for (uint32_t p = 0; p < P; ++p) {lg[tile_elem(r, p)] = ok ? src[tile_elem(r, acol + p)] : 0u;}}}cb_push_back(cb_lg, 1);}volatile tt_l1_ptr uint32_t* fx = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(g_addr);volatile tt_l1_ptr uint32_t* fy = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(g_addr + TB32);volatile tt_l1_ptr uint32_t* at = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(g_addr + 2 * TB32);10 unmodified lines}}}for (uint32_t r = 0; r < 32; ++r) {const uint32_t roff = (((r >> 4) << 1) << 9) + ((r & 15) << 5); // face (r / 16, 0), row r % 16const bool row_ok = b * 32 + r < NQ;for (uint32_t p = P0; p < P0 + PH; ++p) {const uint32_t dst = in_base + (p - P0) * 4 * TB16 + roff;const uint32_t ew = tile_elem(r, ECOL + p);if (!row_ok) {fx[ew] = 0;fy[ew] = 0;if constexpr (!SM) {at[ew] = 0;}if constexpr (SKIP) {continue;}if constexpr (VSRC == 2) {2 unmodified linesnoc_async_read(zeros, blk + 2 * TB16, 128);continue;}for (uint32_t c = 0; c < 4; ++c) {noc_async_read(zeros, dst + c * TB16, 32);noc_async_read(zeros, dst + c * TB16 + 512, 32);12 unmodified linesvy = vy > LOC_LIM ? LOC_LIM : (vy < -LOC_LIM ? -LOC_LIM : vy);const int32_t x0 = vx >> 16;const int32_t y0 = vy >> 16;fx[ew] = q16_to_f32(static_cast<uint32_t>(vx) & 0xFFFF);fy[ew] = q16_to_f32(static_cast<uint32_t>(vy) & 0xFFFF);const bool xv0 = x0 >= 0 && x0 < WV, xv1 = x0 + 1 >= 0 && x0 + 1 < WV;const bool yv0 = y0 >= 0 && y0 < HV, yv1 = y0 + 1 >= 0 && y0 + 1 < HV;if constexpr (SKIP) {3 unmodified linescontinue;}}if constexpr (VSRC == 2) {// staging blocks of point p: top (NW | NE) at + 0, bottom (SW | SE) at + 2 tiles; row r: 128 Bconst uint32_t blk = in_base + (p - P0) * 4 * TB16 + r * 128;const bool xp = x0 >= -1 && x0 < WV; // page i = x0 + 1 in [0, WV]const uint32_t pg = vbase + static_cast<uint32_t>(y0 * (WV + 1) + x0 + 1);if (xp && yv0) {noc_async_read(v_acc.get_noc_addr(pg), blk, 128);} else {noc_async_read(zeros, blk, 128);}if (xp && yv1) {noc_async_read(v_acc.get_noc_addr(pg + WV + 1), blk + 2 * TB16, 128);} else {noc_async_read(zeros, blk + 2 * TB16, 128);}continue;}const uint32_t pos = vbase + static_cast<uint32_t>(y0 * WV + x0);3 unmodified linesgather(v_acc, pos + WV + 1, yv1 && xv1, zeros, dst + 3 * TB16);}}noc_async_read_barrier();cb_push_back(cb_geo, 3);cb_push_back(cb_in, NS);if constexpr (WRITES_OUT) {if (prev != 0xFFFFFFFF) {const uint32_t jp = prev / NB;const uint32_t bp = prev - jp * NB;cb_wait_front(cb_out, 1);noc_async_write(get_read_ptr(cb_out), o_acc.get_noc_addr(bp * H + jp), TB16);noc_async_writes_flushed();cb_pop_front(cb_out, 1);}1 unmodified lineprev = w;}if constexpr (WRITES_OUT) {const uint32_t jp = prev / NB;const uint32_t bp = prev - jp * NB;cb_wait_front(cb_out, 1);noc_async_write(get_read_ptr(cb_out), o_acc.get_noc_addr(bp * H + jp), TB16);noc_async_write_barrier();cb_pop_front(cb_out, 1);}}9 unmodified lines101112131415168 unmodified lines2526272829303132333468 unmodified lines10310410510610710810911011111211311411511611711811912012112212328 unmodified lines15215315415515615715815916016116216316416516616716816917017117217317417550 unmodified lines22622722822923023123223323423523623740 unmodified lines2782792802812822832842852862872882897 unmodified lines2972982993003013023033043053063073083093103113127 unmodified lines32032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743810 unmodified lines4494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435442 unmodified lines54754854955055155255355455555612 unmodified lines5695705715725735745755763 unmodified lines5805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386393 unmodified lines6436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726731 unmodified line6756766776786796806816826836846856866876886896909 unmodified lines// so there is no cross-RISC handshake.//// Work item w (contiguous range per core, core index from the logical coordinates: common RT args only, probe P3):// b = w / H (32-query block), j = w % H (head block; head-minor order); value map m = j * SUB + segment(b);// loc int32 TILE [1, H, NB * 32, 32], tile j * NB + b: row r, column 2p / 2p + 1 = x / y of point p as// round(pixel * 2^16) (pixel = (g + 1) size / 2 - 0.5, align_corners=False);// attn fp32 TILE [1, H, NB * 32, 32], tile j * NB + b: the softmax weight of point p in column p;8 unmodified lines#include <stdint.h>#include "api/dataflow/dataflow_api.h"#ifdef MSDA_K_TIMING#include "tools/profiler/kernel_profiler.hpp"#define TNOW() reg_read(RISCV_DEBUG_REG_WALL_CLOCK_L)#endif#include "ttnn/cpp/ttnn/kernel_lib/reduce_helpers_dataflow.hpp"constexpr uint32_t PART = get_compile_time_arg_val(1);68 unmodified linesconstexpr uint32_t P0 = PART * PH;constexpr uint32_t NS = PH * 4; // steps (tiles) per item and RISCconstexpr uint32_t TB16 = 2048, TB32 = 4096;// VSRC 4 (AutoE2E): quad maps [N, h + 1, w + 1, 128] (tt/pairmap.py quad=True): the 256-byte page (m, Y, i) holds the// NW | NE | SW | SE sticks of the point whose top-left corner is (Y - 1, i - 1): ONE read per point and row lands a row// of the point's [32 x 128] row-major staging block (tilized into the 4 corner tiles by the compute kernel)constexpr uint32_t VPAGE = VSRC == 0 ? 64 : (VSRC == 2 ? 128 : (VSRC == 4 ? 256 : 2048));constexpr uint32_t VPAGE_AL = VPAGE; // L1 page stride (128 B: already a multiple of the L1 alignment)static_assert((VSRC != 2 && VSRC != 4) || !SKIP, "msda_k: pair / quad maps and SKIP are exclusive");// MSDA_K_SKIPP (pair maps, no in-kernel softmax): a point with all four corners outside the map (or a row past NQ)// issues no reads; its weight in this RISC's attn copy is set to 0 and its staging rows keep earlier finite sticks// (zeroed once at start), so it adds 0 (the zeros-page reads it replaces cost as much as real ones)#ifdef MSDA_K_SKIPPconstexpr bool SKIPP = true;#elseconstexpr bool SKIPP = false;#endifstatic_assert(!SKIPP || ((VSRC == 2 || VSRC == 4) && SM == 0), "msda_k: SKIPP needs pair / quad maps and host-side weights");constexpr uint32_t BPS = NB / SUB;constexpr uint32_t MAP = static_cast<uint32_t>(HV * WV);constexpr int32_t LOC_LIM = 1 << 28; // |pixel| < 4096 after the clamp: no overflow below28 unmodified linesconst uint32_t n = 31 - __builtin_clz(q);return ((127 - 16 + n) << 23) | ((q << (23 - n)) & 0x7FFFFF);}// the fraction q (16 bits) as the fp32 2^23 + q: one OR instead of a normalisation (no clz on these RISC-Vs); the// compute kernel's weight function takes (f - 2^23) * 2^-16, exact. FRAC0 is the encoding of 0.constexpr uint32_t FRAC0 = 0x4B000000u;static inline uint32_t q16_frac(uint32_t q) { return FRAC0 | q; }// lean 128-byte reads of pixel-pair pages (interleaved L1): the bank and its NOC coordinate from the firmware// tables, and only the registers that change per read (the length and the chip-local address high bits are set// once per item by noc_async_read_one_packet_set_state)static inline void pair_read_state() {noc_async_read_one_packet_set_state(get_noc_addr(MEM_ZEROS_BASE), VPAGE);}static inline void pair_read(uint32_t xy, uint32_t src, uint32_t dst) {while (!noc_cmd_buf_ready(noc_index, read_cmd_buf));NOC_CMD_BUF_WRITE_REG(noc_index, read_cmd_buf, NOC_RET_ADDR_LO, dst);NOC_CMD_BUF_WRITE_REG(noc_index, read_cmd_buf, NOC_TARG_ADDR_LO, src);NOC_CMD_BUF_WRITE_REG(noc_index, read_cmd_buf, NOC_TARG_ADDR_COORDINATE, xy);NOC_CMD_BUF_WRITE_REG(noc_index, read_cmd_buf, NOC_CMD_CTRL, NOC_CTRL_SEND_REQ);}// one corner stick (32 channels) -> the face rows at dst (channels 0..15) and dst + 512 (16..31). pos: RM page// (VSRC 0) or slice * TPH * 32 + row (VSRC 1).50 unmodified linesif (ci >= NC) {return;}// strided items (w = core, core + NC, ..) whenever per-item work varies (skipped points, padding blocks): every// core gets a sample of all segments / heads instead of one contiguous rangeconstexpr bool STRIDE = SKIP || SKIPP;const uint32_t w0 = STRIDE ? ci : ci * NWORK / NC;const uint32_t w1 = STRIDE ? NWORK : (ci + 1) * NWORK / NC;const uint32_t wstep = STRIDE ? NC : 1;if (w0 >= w1) {return;}40 unmodified linesfor (uint32_t h = 0; h < 2; ++h) {for (uint32_t r = 0; r < 32; ++r) {for (uint32_t c = 0; c < 32; ++c) {#ifdef MSDA_K_COLBm[h * 1024 + tile_elem(r, c)] = (c % 4 == 0 && c / 4 >= h * PH && c / 4 < (h + 1) * PH) ? 0x3F800000u : 0u;#elsem[h * 1024 + tile_elem(r, c)] =(c >= ECOL + h * PH && c < ECOL + (h + 1) * PH) ? 0x3F800000u : 0u;#endif}}}7 unmodified lines// the geo pages: zero once (columns >= P and the right faces stay zero / finite forever)cb_reserve_back(cb_geo, 6);zero_l1(get_write_ptr(cb_geo), 6 * TB32);if constexpr (SKIP || SKIPP) {cb_reserve_back(cb_in, 2 * NS);zero_l1(get_write_ptr(cb_in), 2 * NS * TB16);}// PREF (the in-kernel softmax with pair maps: the t1 self-attention): the next item's loc and logit tiles are read// while the current item's points are processed (two buffers each), hiding their DRAM latencyconstexpr bool PREF = SM == 1 && VSRC == 2 && LOC_HS > 0 && !LOCF && ECOL == 0;cb_reserve_back(cb_loc, PREF ? 2 : 1);const uint32_t lbuf = get_write_ptr(cb_loc);const uint32_t sbuf0 = (SM && MAKES_E) ? get_write_ptr(cb_scr) : 0;uint32_t bbuf = 0;if constexpr (LOCF) {cb_reserve_back(cb_base, 1);7 unmodified linesvolatile tt_l1_ptr int32_t* loc = reinterpret_cast<volatile tt_l1_ptr int32_t*>(lbuf);uint32_t prev = 0xFFFFFFFF;auto head_reads = [&](uint32_t wq, uint32_t lb, uint32_t sb) {const uint32_t bq = wq / H;const uint32_t jq = wq - bq * H;noc_async_read(l_acc.get_noc_addr(bq * LOC_TW + (jq * LOC_HS + LOC_OFF) / 32), lb, TB32);if constexpr (SM && MAKES_E) {noc_async_read(a_acc.get_noc_addr(bq * AT_TW + (jq * P) / 32), sb, TB32);}};uint32_t cur = 0;if constexpr (PREF) {if (w0 < w1) {head_reads(w0, lbuf, sbuf0);noc_async_read_barrier();}}uint32_t nrd = 0;const uint32_t vaddr = get_common_arg_val<uint32_t>(0);const uint32_t my_xy = NOC_XY_ENCODING(my_x[noc_index], my_y[noc_index]);#ifdef MSDA_K_TIMINGuint32_t t_res = 0, t_bar = 0, t_loop = 0, t_out = 0, t_hdr = 0, t0, t1;#endiffor (uint32_t w = w0; w < w1; w += wstep) {// head-minor items (w = b * H + j): the cores running at the same time cover all the heads' maps of a camera,// not one map (a small level's map is ~100 pages: one map at a time made hot spots of its banks); the output// tile of item w is tile wconst uint32_t b = w / H;const uint32_t j = w - b * H;// VSRC 0: page of the map's pixel 0; VSRC 1: the slice's first tile row + the map's first row in itconst uint32_t jm = j / HDIV;const uint32_t sg = segment(b);const uint32_t vbase = VSRC == 0 ? (jm * SUB + sg) * MAP: VSRC == 2 ? (jm * SUB + sg) * HV * (WV + 1): VSRC == 4 ? (jm * SUB + sg) * (HV + 1) * (WV + 1): VSRC == 3 ? sg * MAP: jm * TPH * 32 + sg * MAP;g_hj = j;#ifdef MSDA_K_TIMINGt0 = TNOW();#endifcb_reserve_back(cb_geo, 3);cb_reserve_back(cb_in, NS);#ifdef MSDA_K_TIMINGt1 = TNOW();t_res += t1 - t0;#endifconst uint32_t g_addr = get_write_ptr(cb_geo);const uint32_t in_base = get_write_ptr(cb_in);const uint32_t ltile = LOC_HS == 0 ? j * NB + b : b * LOC_TW + (j * LOC_HS + LOC_OFF) / 32;const uint32_t lcol = LOC_HS == 0 ? 0 : (j * LOC_HS + LOC_OFF) % 32;const uint32_t lcur = PREF ? lbuf + cur * TB32 : lbuf;const uint32_t scur = PREF ? sbuf0 + cur * TB32 : sbuf0;if constexpr (PREF) {if (w + wstep < w1) {head_reads(w + wstep, lbuf + (cur ^ 1) * TB32, sbuf0 + (cur ^ 1) * TB32);}cur ^= 1;} else {noc_async_read(l_acc.get_noc_addr(ltile), lbuf, TB32);}if constexpr (LOCF) {noc_async_read(bs_acc.get_noc_addr(b * 2 + (LOC_OFF % 64) / 32), bbuf, TB32);}if constexpr (SM) {if constexpr (MAKES_E && !PREF) {noc_async_read(a_acc.get_noc_addr(b * AT_TW + (SM == 2 ? j : (j * P) / 32)), get_write_ptr(cb_scr),TB32);}} else {noc_async_read(a_acc.get_noc_addr(j * NB + b), g_addr + 2 * TB32, TB32);}if constexpr (!PREF) {noc_async_read_barrier();}if constexpr (SM && MAKES_E) {// the head's logit tile: columns 0..P-1 <- compact columns (j P) % 32 + p; columns >= P keep PADcb_reserve_back(cb_lg, 1);volatile tt_l1_ptr uint32_t* lg = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(get_write_ptr(cb_lg));volatile tt_l1_ptr uint32_t* src = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(scur);const uint32_t acol = (j * P) % 32;if constexpr (SM == 2) {for (uint32_t r = 0; r < 32; ++r) {const bool ok = b * 32 + r < NQ;for (uint32_t c = 0; c < 32; ++c) {lg[tile_elem(r, c)] = ok ? src[tile_elem(r, c)] : 0u;}}} else {// the P compact columns of a head sit in one face row ((j P) % 16 + P <= 16): row base + offsetsuint32_t* lgn = const_cast<uint32_t*>(lg);const uint32_t* srn = const_cast<const uint32_t*>(src) + ((acol >> 4) << 8) + (acol & 15);for (uint32_t r = 0; r < 32; ++r) {const uint32_t rb = ((r >> 4) << 9) + ((r & 15) << 4);const bool ok = b * 32 + r < NQ;#pragma GCC unroll 8for (uint32_t p = 0; p < P; ++p) {#ifdef MSDA_K_COLBlgn[rb + 4 * p] = ok ? srn[rb + p] : 0u; // point p in column 4 p (the rest PAD)#elselgn[rb + p] = ok ? srn[rb + p] : 0u;#endif}}asm volatile("" ::: "memory");}cb_push_back(cb_lg, 1);}#ifdef MSDA_K_TIMINGt0 = TNOW();t_hdr += t0 - t1;#endifif constexpr (VSRC == 2 || VSRC == 4) {pair_read_state();}volatile tt_l1_ptr uint32_t* fx = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(g_addr);volatile tt_l1_ptr uint32_t* fy = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(g_addr + TB32);volatile tt_l1_ptr uint32_t* at = reinterpret_cast<volatile tt_l1_ptr uint32_t*>(g_addr + 2 * TB32);10 unmodified lines}}}// fast path (pair maps, the merged loc layout, no fp32 offsets): row bases instead of per-element tile// indexing; a head's 2P loc columns lie in one face row ((j LOC_HS + LOC_OFF) % 16 + 2P <= 16 in every use)constexpr bool FAST = VSRC == 2 && LOC_HS > 0 && !LOCF && ECOL == 0;#ifdef MSDA_K_COLBconstexpr uint32_t GC = 4; // geo column of point p: 4 p (the compute kernel's column broadcast)static_assert(FAST && SM == 1 && P <= 4, "msda_k: COLB is the compact-softmax pair-map fast path");#elseconstexpr uint32_t GC = 1;#endifif constexpr (FAST) {const int32_t* Ln = reinterpret_cast<const int32_t*>(lcur) + ((lcol >> 4) << 8) + (lcol & 15);uint32_t* fxn = const_cast<uint32_t*>(fx);uint32_t* fyn = const_cast<uint32_t*>(fy);uint32_t* atn = const_cast<uint32_t*>(at);for (uint32_t r = 0; r < 32; ++r) {const uint32_t rb = ((r >> 4) << 9) + ((r & 15) << 4);const uint32_t sb = in_base + r * 128;if (b * 32 + r >= NQ) {#pragma GCC unroll 4for (uint32_t p = P0; p < P0 + PH; ++p) {fxn[rb + GC * p] = FRAC0;fyn[rb + GC * p] = FRAC0;if constexpr (!SM) {atn[rb + p] = 0;}if constexpr (!SKIPP) {pair_read(my_xy, MEM_ZEROS_BASE, sb + (p - P0) * 4 * TB16);pair_read(my_xy, MEM_ZEROS_BASE, sb + (p - P0) * 4 * TB16 + 2 * TB16);nrd += 2;}}continue;}const int32_t* lr = Ln + rb;#pragma GCC unroll 4for (uint32_t p = P0; p < P0 + PH; ++p) {const int32_t vx = lr[2 * p];const int32_t vy = lr[2 * p + 1];const int32_t x0 = vx >> 16;const int32_t y0 = vy >> 16;const uint32_t blk = sb + (p - P0) * 4 * TB16;const bool xp = static_cast<uint32_t>(x0 + 1) <= static_cast<uint32_t>(WV);const bool yv0 = static_cast<uint32_t>(y0) < static_cast<uint32_t>(HV);const bool yv1 = static_cast<uint32_t>(y0 + 1) < static_cast<uint32_t>(HV);if constexpr (SKIPP) {if (!(xp && (yv0 || yv1))) {atn[rb + p] = 0;continue;}}fxn[rb + GC * p] = q16_frac(static_cast<uint32_t>(vx) & 0xFFFF);fyn[rb + GC * p] = q16_frac(static_cast<uint32_t>(vy) & 0xFFFF);#ifdef MSDA_K_NOREADcontinue;#endifconst uint32_t pg = vbase + static_cast<uint32_t>(y0) * (WV + 1) + static_cast<uint32_t>(x0 + 1);if (xp && yv0) {const uint32_t row = udivsi3_const_divisor<NUM_L1_BANKS>(pg);const uint32_t bank = pg - row * NUM_L1_BANKS;pair_read(l1_bank_to_noc_xy[noc_index][bank], vaddr + row * VPAGE_AL + bank_to_l1_offset[bank], blk);} else {pair_read(my_xy, MEM_ZEROS_BASE, blk);}if (xp && yv1) {const uint32_t pb = pg + WV + 1;const uint32_t row = udivsi3_const_divisor<NUM_L1_BANKS>(pb);const uint32_t bank = pb - row * NUM_L1_BANKS;pair_read(l1_bank_to_noc_xy[noc_index][bank], vaddr + row * VPAGE_AL + bank_to_l1_offset[bank],blk + 2 * TB16);} else {pair_read(my_xy, MEM_ZEROS_BASE, blk + 2 * TB16);}nrd += 2;}}asm volatile("" ::: "memory");}for (uint32_t r = 0; r < (FAST ? 0u : 32u); ++r) {const uint32_t roff = (((r >> 4) << 1) << 9) + ((r & 15) << 5); // face (r / 16, 0), row r % 16const bool row_ok = b * 32 + r < NQ;for (uint32_t p = P0; p < P0 + PH; ++p) {const uint32_t dst = in_base + (p - P0) * 4 * TB16 + roff;const uint32_t ew = tile_elem(r, ECOL + p);if (!row_ok) {fx[ew] = FRAC0;fy[ew] = FRAC0;if constexpr (!SM) {at[ew] = 0;}if constexpr (SKIP || SKIPP) {continue;}if constexpr (VSRC == 2) {2 unmodified linesnoc_async_read(zeros, blk + 2 * TB16, 128);continue;}if constexpr (VSRC == 4) {noc_async_read(zeros, in_base + (p - P0) * 4 * TB16 + r * 256, 256);continue;}for (uint32_t c = 0; c < 4; ++c) {noc_async_read(zeros, dst + c * TB16, 32);noc_async_read(zeros, dst + c * TB16 + 512, 32);12 unmodified linesvy = vy > LOC_LIM ? LOC_LIM : (vy < -LOC_LIM ? -LOC_LIM : vy);const int32_t x0 = vx >> 16;const int32_t y0 = vy >> 16;fx[ew] = q16_frac(static_cast<uint32_t>(vx) & 0xFFFF);fy[ew] = q16_frac(static_cast<uint32_t>(vy) & 0xFFFF);const bool xv0 = x0 >= 0 && x0 < WV, xv1 = x0 + 1 >= 0 && x0 + 1 < WV;const bool yv0 = y0 >= 0 && y0 < HV, yv1 = y0 + 1 >= 0 && y0 + 1 < HV;if constexpr (SKIP) {3 unmodified linescontinue;}}if constexpr (VSRC == 4) {// staging block of point p: [32 x 128] row-major at + 0 (4 tiles); row r: 256 B = NW | NE | SW | SEconst uint32_t blk = in_base + (p - P0) * 4 * TB16 + r * 256;if (!(x0 >= -1 && x0 < WV && y0 >= -1 && y0 < HV)) {if constexpr (SKIPP) {at[ew] = 0;} else {pair_read(my_xy, MEM_ZEROS_BASE, blk);nrd += 1;}continue;}#ifdef MSDA_K_NOREADcontinue;#endifconst uint32_t pg = vbase + static_cast<uint32_t>((y0 + 1) * (WV + 1) + x0 + 1);const uint32_t row = udivsi3_const_divisor<NUM_L1_BANKS>(pg);const uint32_t bank = pg - row * NUM_L1_BANKS;pair_read(l1_bank_to_noc_xy[noc_index][bank], vaddr + row * VPAGE_AL + bank_to_l1_offset[bank], blk);nrd += 1;continue;}if constexpr (VSRC == 2) {// staging blocks of point p: top (NW | NE) at + 0, bottom (SW | SE) at + 2 tiles; row r: 128 Bconst uint32_t blk = in_base + (p - P0) * 4 * TB16 + r * 128;const bool xp = x0 >= -1 && x0 < WV; // page i = x0 + 1 in [0, WV]if constexpr (SKIPP) {if (!(xp && (yv0 || yv1))) {at[ew] = 0;continue;}}const uint32_t pg = vbase + static_cast<uint32_t>(y0 * (WV + 1) + x0 + 1);#ifdef MSDA_K_NOREADcontinue;#endif// top page pg, bottom page pg + WV + 1 (bank = page % NUM_L1_BANKS, row = page / NUM_L1_BANKS)if (xp && yv0) {const uint32_t row = udivsi3_const_divisor<NUM_L1_BANKS>(pg);const uint32_t bank = pg - row * NUM_L1_BANKS;pair_read(l1_bank_to_noc_xy[noc_index][bank], vaddr + row * VPAGE_AL + bank_to_l1_offset[bank], blk);} else {pair_read(my_xy, MEM_ZEROS_BASE, blk);}if (xp && yv1) {const uint32_t pb = pg + WV + 1;const uint32_t row = udivsi3_const_divisor<NUM_L1_BANKS>(pb);const uint32_t bank = pb - row * NUM_L1_BANKS;pair_read(l1_bank_to_noc_xy[noc_index][bank], vaddr + row * VPAGE_AL + bank_to_l1_offset[bank],blk + 2 * TB16);} else {pair_read(my_xy, MEM_ZEROS_BASE, blk + 2 * TB16);}nrd += 2;continue;}const uint32_t pos = vbase + static_cast<uint32_t>(y0 * WV + x0);3 unmodified linesgather(v_acc, pos + WV + 1, yv1 && xv1, zeros, dst + 3 * TB16);}}if constexpr (VSRC == 2 || VSRC == 4) {noc_reads_num_issued[noc_index] += nrd; // the lean reads do not count themselvesnrd = 0;}#ifdef MSDA_K_TIMINGt1 = TNOW();t_loop += t1 - t0;#endifnoc_async_read_barrier();#ifdef MSDA_K_TIMINGt0 = TNOW();t_bar += t0 - t1;#endifcb_push_back(cb_geo, 3);cb_push_back(cb_in, NS);if constexpr (WRITES_OUT) {if (prev != 0xFFFFFFFF) {#ifdef MSDA_K_TIMINGt0 = TNOW();#endifcb_wait_front(cb_out, 1);#ifdef MSDA_K_TIMINGt_out += TNOW() - t0;#endifnoc_async_write(get_read_ptr(cb_out), o_acc.get_noc_addr(prev), TB16);noc_async_writes_flushed();cb_pop_front(cb_out, 1);}1 unmodified lineprev = w;}if constexpr (WRITES_OUT) {cb_wait_front(cb_out, 1);noc_async_write(get_read_ptr(cb_out), o_acc.get_noc_addr(prev), TB16);noc_async_write_barrier();cb_pop_front(cb_out, 1);}#ifdef MSDA_K_TIMINGDeviceTimestampedData("res", t_res);DeviceTimestampedData("hdr", t_hdr);DeviceTimestampedData("loop", t_loop);DeviceTimestampedData("bar", t_bar);DeviceTimestampedData("out", t_out);#endif}
19 unmodified lines2021222324252627284 unmodified lines3334353637383927 unmodified lines6768697071727374757677787980818283848519 unmodified linesconstexpr uint32_t NITEMS = get_compile_time_arg_val(6);constexpr uint32_t NC = get_compile_time_arg_val(7);constexpr uint32_t GX = get_compile_time_arg_val(8);constexpr auto i_args = TensorAccessorArgs<9>();constexpr auto o_args = TensorAccessorArgs<i_args.next_compile_time_args_offset()>();constexpr uint32_t TB16 = 2048, PAGE = 128, STK = 64, W1 = WV + 1, MAP = HV * WV;constexpr uint32_t cb_in = 0, cb_prev = 1, cb_rm = 16;void kernel_main() {4 unmodified linesconst uint32_t w0 = ci * NITEMS / NC;const uint32_t w1 = (ci + 1) * NITEMS / NC;const auto ia = TensorAccessor(i_args, get_common_arg_val<uint32_t>(0), TB16);const auto oa = TensorAccessor(o_args, get_common_arg_val<uint32_t>(1), PAGE);for (uint32_t w = w0; w < w1; ++w) {const uint32_t j = w % HEADS;const uint32_t bt_t = w / HEADS; // bt * NTR + t27 unmodified linesconst uint32_t y = rem / WV;const uint32_t x = rem - y * WV;const uint32_t m = (bt * HEADS + j) * SUB + s;const uint32_t pg = (m * HV + y) * W1 + x;const uint32_t cur = rm + r * STK;if (x > 0 && r > 0) {noc_async_write(cur - STK, oa.get_noc_addr(pg), PAGE);} else {const uint64_t d = oa.get_noc_addr(pg);noc_async_write(x == 0 ? zeros : prev, d, STK);noc_async_write(cur, d + STK, STK);}if (x == WV - 1) { // the end-of-row page (y, WV) = [x = WV - 1 | zeros]const uint64_t d = oa.get_noc_addr(pg + 1);noc_async_write(cur, d, STK);noc_async_write(zeros, d + STK, STK);}}noc_async_writes_flushed();19 unmodified lines2021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566674 unmodified lines7273747576777827 unmodified lines10610710810911011111211311411519 unmodified linesconstexpr uint32_t NITEMS = get_compile_time_arg_val(6);constexpr uint32_t NC = get_compile_time_arg_val(7);constexpr uint32_t GX = get_compile_time_arg_val(8);// QUAD (AutoE2E): the output is the quad map [N, HV + 1, WV + 1, 128]: 256-byte page (m, Y, i) = [pair page (m, Y - 1,// i) | pair page (m, Y, i)] (rows -1 and HV are zeros), the four corners of a sample point in one read; each pair page// is written as the lower half of quad row y and the upper half of quad row y + 1constexpr uint32_t QUAD = get_compile_time_arg_val(9);constexpr auto i_args = TensorAccessorArgs<10>();constexpr auto o_args = TensorAccessorArgs<i_args.next_compile_time_args_offset()>();constexpr uint32_t TB16 = 2048, PAGE = 128, STK = 64, W1 = WV + 1, MAP = HV * WV;constexpr uint32_t OPAGE = QUAD ? 2 * PAGE : PAGE;// the 128-byte pair page (m, y, i) from two 64-byte parts (a, b): one write when contiguous; QUAD: into the lower half// of quad page (m, y, i) and the upper half of (m, y + 1, i), plus the zero halves of the edge rowstemplate <typename A>static inline void put_pair(const A& oa, uint32_t m, uint32_t y, uint32_t i, uint32_t a, uint32_t b, uint32_t zeros) {if constexpr (!QUAD) {const uint64_t d = oa.get_noc_addr((m * HV + y) * W1 + i);if (b == a + STK) {noc_async_write(a, d, PAGE);} else {noc_async_write(a, d, STK);noc_async_write(b, d + STK, STK);}} else {const uint32_t q = (m * (HV + 1) + y) * W1 + i;const uint64_t lo = oa.get_noc_addr(q, PAGE); // quad row y, lower halfconst uint64_t hi = oa.get_noc_addr(q + W1); // quad row y + 1, upper halfif (b == a + STK) {noc_async_write(a, lo, PAGE);noc_async_write(a, hi, PAGE);} else {noc_async_write(a, lo, STK);noc_async_write(b, lo + STK, STK);noc_async_write(a, hi, STK);noc_async_write(b, hi + STK, STK);}if (y == 0) {noc_async_write(zeros, oa.get_noc_addr(q), PAGE);}if (y == HV - 1) {noc_async_write(zeros, oa.get_noc_addr(q + W1, PAGE), PAGE);}}}constexpr uint32_t cb_in = 0, cb_prev = 1, cb_rm = 16;void kernel_main() {4 unmodified linesconst uint32_t w0 = ci * NITEMS / NC;const uint32_t w1 = (ci + 1) * NITEMS / NC;const auto ia = TensorAccessor(i_args, get_common_arg_val<uint32_t>(0), TB16);const auto oa = TensorAccessor(o_args, get_common_arg_val<uint32_t>(1), OPAGE);for (uint32_t w = w0; w < w1; ++w) {const uint32_t j = w % HEADS;const uint32_t bt_t = w / HEADS; // bt * NTR + t27 unmodified linesconst uint32_t y = rem / WV;const uint32_t x = rem - y * WV;const uint32_t m = (bt * HEADS + j) * SUB + s;const uint32_t cur = rm + r * STK;put_pair(oa, m, y, x, x == 0 ? zeros : (r > 0 ? cur - STK : prev), cur, zeros);if (x == WV - 1) { // the end-of-row page (y, WV) = [x = WV - 1 | zeros]put_pair(oa, m, y, WV, cur, zeros, zeros);}}noc_async_writes_flushed();
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125# SPDX-License-Identifier: Apache-2.0"""``msda_cm``: the AutoE2E spatial cross-attention of one layer as ONE kernel, cell-major (kernels``msda_cm_{reader,compute}.cpp``; derived from ``msda_k``):
out[q, j * 32 + d] = 1 / n_q * sum_{k < n_q} sum_l sum_p softmax_j(logits)[q, l, p] * bilinear(value_l[j * 6 + cam_k(q)], anchor_{k, l, p % 4}(q) + off[q, j, l, p])[d]
with ``n_q`` the number of cameras that see cell ``q`` (at most 2), zero padding outside the maps. Unlike the rebatchedform (``msda`` on per-camera row lists + the scatter over cameras + a sum over the levels) the rows are the cells:the offsets / weights are computed once per cell (upstream gathers the same query for every camera), there is nogather, no scatter and no level sum, and everything is summed in fp32 with one bf16 rounding at the end.
- ``maps``: 4 quad maps ``(8 * 6, h_l + 1, w_l + 1, 128)`` bf16 ROW_MAJOR in L1 (``tt/pairmap.py`` ``quad=True``);- ``off``: fp32 TILE ``[1, 1, Q, 512]`` (the 2^16-scaled sampling projection), column ``j * 64 + h * 32 + l * 8 + 2 q + (x, y)`` = the offset of point ``p = 4 h + q`` (``tt/encoder.py`` ``cm_column_orders``: reader RISC h hands one tile per item to the compute kernel, which makes it int32 Q16.16);- ``logits``: fp32 TILE ``[1, 1, Q, 256]`` (the attention projection), column ``j * 32 + 16 h + 4 l + q`` = the logit of point ``4 h + q``; the softmax over a head's 32 columns runs in the kernel. ``None``: ``off`` is ONE merged ``[1, 1, Q, 768]`` projection, the offsets in columns ``[0, 512)`` and the logits in ``[512, 768)``;- ``table``: int32 TILE ``[1, 1, Q, 32]`` (``host.geometry.cm_table``): per slot k the 4 anchors as ``round(uv * 2^(16 + smax))`` in columns ``8 k + 2 a + (x, y)``, the cameras in 16 + k (-1: none), the count in 18.
Output ``[1, 1, Q, 256]`` bf16 TILE."""from __future__ import annotations
import osfrom typing import Any, Optional, Sequence
__all__ = ["msda_cm"]
KDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kernels")TB16, TB32 = 2048, 4096
def msda_cm(maps: Sequence[Any], off: Any, logits: Optional[Any], table: Any, *, ncam: int = 6, slots: int = 2, memory_config: Any = None, debug: Sequence[str] = ()) -> Any: import ttnn
if len(maps) != 4: raise ValueError("msda_cm: 4 levels") merged = logits is None if merged: # one [1, 1, Q, 96 H] projection: the offsets in columns [0, 64 H), the logits in [64 H, 96 H) logits = off heads = int(off.shape[-1]) // 96 else: heads = int(logits.shape[-1]) // 32 nq = int(off.shape[-2]) hv, wv = [], [] for m in maps: n, h1, w1, d = (int(m.shape[i]) for i in range(4)) if d != 128 or n != heads * ncam or m.layout != ttnn.ROW_MAJOR_LAYOUT: raise ValueError(f"msda_cm: quad maps ({heads * ncam}, h + 1, w + 1, 128), got {tuple(m.shape)}") hv.append(h1 - 1) wv.append(w1 - 1) if off.dtype != ttnn.float32 or int(off.shape[-1]) != heads * (96 if merged else 64): raise ValueError(f"msda_cm: off fp32 [1, 1, Q, {heads * (96 if merged else 64)}], got {off.dtype} " f"{tuple(off.shape)}") if logits.dtype != ttnn.float32 or int(logits.shape[-2]) != nq: raise ValueError(f"msda_cm: logits fp32 [1, 1, Q, H * 32], got {logits.dtype} {tuple(logits.shape)}") if table.dtype != ttnn.int32 or int(table.shape[-1]) != 32 or int(table.shape[-2]) != nq: raise ValueError(f"msda_cm: table int32 [1, 1, Q, 32], got {table.dtype} {tuple(table.shape)}") dev = off.device() out = ttnn.allocate_tensor_on_device(ttnn.Shape([1, 1, nq, heads * 32]), ttnn.bfloat16, ttnn.TILE_LAYOUT, dev, memory_config or ttnn.DRAM_MEMORY_CONFIG) g = dev.compute_with_storage_grid_size() gx, gy = int(g.x), int(g.y) nb = -(-nq // 32) nwork = nb * heads nc = gx * gy crs = ttnn.CoreRangeSet({ttnn.CoreRange(ttnn.CoreCoord(0, 0), ttnn.CoreCoord(gx - 1, gy - 1))}) P, ns = 8, 16
def cb(idx, pages, dtype, size): return ttnn.CBDescriptor(total_size=pages * size, core_ranges=crs, format_descriptors=[ ttnn.CBFormatDescriptor(buffer_index=idx, data_format=dtype, page_size=size)])
cbs = [cb(0, 2 * ns, ttnn.bfloat16, TB16), cb(1, 2 * ns, ttnn.bfloat16, TB16), cb(2, 6, ttnn.float32, TB32), cb(3, 6, ttnn.float32, TB32), cb(5, 8, ttnn.float32, TB32), cb(6, 1, ttnn.float32, TB32), cb(7, 2, ttnn.int32, TB32), cb(8, 2, ttnn.int32, TB32), cb(9, 2, ttnn.float32, TB32), cb(10, 1, ttnn.float32, TB32), cb(11, 1, ttnn.float32, TB32), cb(12, 3, ttnn.float32, TB32), cb(13, 1, ttnn.float32, TB32), cb(14, 1, ttnn.float32, TB32), cb(15, 1, ttnn.float32, TB32), cb(17, 3, ttnn.float32, TB32), cb(18, 3, ttnn.float32, TB32), cb(21, 2, ttnn.int32, TB32), cb(22, 2, ttnn.int32, TB32), cb(23, 2, ttnn.float32, TB32), cb(24, 2, ttnn.float32, TB32), cb(16, 2, ttnn.bfloat16, TB16), cb(19, ns, ttnn.bfloat16, TB16), cb(20, ns, ttnn.bfloat16, TB16)]
def acc(t): return list(ttnn.TensorAccessorArgs(t).get_compile_time_args())
accs = acc(table) + acc(off) + acc(logits) + acc(out) tail = [nb, nq, heads, nc, gx] lv = [int(ncam), int(slots)] + hv + wv if merged: lv += [3 * heads, 0, 3 * heads, 2 * heads] else: lv += [2 * heads, 0, heads, 0] rd_ct = [0, 0, 2, 7, 4, 16, 9] + tail + [0, 1] + lv + accs wr_ct = [1, 1, 3, 8, 4, 16, 9] + tail + [1, 0] + lv + accs cp_ct = [nwork, nc, gx] common = [table.buffer_address(), off.buffer_address(), logits.buffer_address(), out.buffer_address()] + \ [m.buffer_address() for m in maps] um = [ttnn.UnpackToDestMode.Default] * 64 for i in (2, 3, 6, 17, 18): um[i] = ttnn.UnpackToDestMode.UnpackToDestFp32 # HiFi4 by default; AE_MSDA_FIDELITY=HiFi3 drops the last fidelity phase (exact for the weight broadcast against # the exact ones of E_p; ~2^-12 relative on the products) fid = getattr(ttnn.MathFidelity, os.environ.get("AE_MSDA_FIDELITY", "HiFi4")) ccfg = ttnn.ComputeConfigDescriptor(math_fidelity=fid, fp32_dest_acc_en=True, math_approx_mode=False) ccfg.unpack_to_dest_mode = um dbg = list(debug) + [d for d in os.environ.get("AE_MSDA_DEBUG", "").split(",") if d] defines = [(f"MSDA_K_{d.upper()}", "1") for d in dbg] SRC = ttnn.KernelDescriptor.SourceType.FILE_PATH
def kd(name, ct, common_args, config): return ttnn.KernelDescriptor(kernel_source=os.path.join(KDIR, name), source_type=SRC, core_ranges=crs, compile_time_args=ct, defines=list(defines), runtime_args=ttnn.RuntimeArgs(), common_runtime_args=common_args, config=config)
ks = [kd("msda_cm_reader.cpp", rd_ct, common, ttnn.ReaderConfigDescriptor()), kd("msda_cm_reader.cpp", wr_ct, common, ttnn.WriterConfigDescriptor()), kd("msda_cm_compute.cpp", cp_ct, [], ccfg)] ttnn.generic_op([table, off, logits] + list(maps) + [out], ttnn.ProgramDescriptor(kernels=ks, semaphores=[], cbs=cbs)) return out33 unmodified lines3435363738394019 unmodified lines6061626364656667686970717273747543 unmodified lines1191201211221231241251261271281291301311321336 unmodified lines14014114214314414514614714814915015115215315415515615733 unmodified linesdef msda(value: Any, loc: Any, attn: Any, *, points: int, nq: int, sub: int = 1,segments: Optional[Sequence[int]] = None, hdiv: int = 1, att_col0: int = 0, loc_hs: int = 0,loc_off: int = 0, seg_table: Any = None, memory_config: Any = None, fast_tilize: bool = False,debug: Sequence[str] = (), softmax: Any = False, base: Any = None) -> Any:"""See the module docstring. ``softmax``: False (``attn`` holds weights), True (compact logits, softmax overeach head block's ``points`` columns) or ``"joint"`` (``attn`` ``[1, 1, Q, H * 32]`` logits, the softmax over all32 columns of a head and this call's weights in columns ``att_col0 + p``: the 4-level cross-attention).19 unmodified linesif cols != 32:raise ValueError(f"msda: head-split loc {tuple(loc.shape)}")if value.layout != ttnn.ROW_MAJOR_LAYOUT:raise ValueError("msda: value must be ROW_MAJOR stick maps (N, h, w, 32) or pair maps (N, h, w + 1, 64)")pairs = int(value.shape[-1]) == 64n, hv, wv, d = (int(value.shape[i]) for i in range(4))if pairs:wv, d = wv - 1, 32elif value.memory_config().buffer_type != ttnn.BufferType.L1:raise ValueError("msda: stick maps must be in L1 (32-byte reads at 32-byte offsets)")if d != 32:raise ValueError(f"msda: head dim {d}")vsrc = 2 if pairs else 0nb = -(-qp // 32)if segments is not None:segs = [int(s) for s in segments]43 unmodified linescbs = [cb(0, 2 * ns, ttnn.bfloat16, TB16), cb(1, 2 * ns, ttnn.bfloat16, TB16),cb(2, 6, ttnn.float32, TB32), cb(3, 6, ttnn.float32, TB32),cb(4, p, ttnn.bfloat16, TB16), cb(5, 8, ttnn.float32, TB32), cb(6, 1, ttnn.float32, TB32),cb(7, 1, ttnn.int32, TB32), cb(8, 1, ttnn.int32, TB32), cb(16, 2, ttnn.bfloat16, TB16)]if pairs:cbs += [cb(19, ns, ttnn.bfloat16, TB16), cb(20, ns, ttnn.bfloat16, TB16)]if base is not None:cbs += [cb(21, 1, ttnn.float32, TB32), cb(22, 1, ttnn.float32, TB32)]if softmax:cbs += [cb(9, 2, ttnn.float32, TB32), cb(10, 1, ttnn.float32, TB32), cb(11, 1, ttnn.float32, TB32),cb(12, 2, ttnn.float32, TB32), cb(13, 2, ttnn.float32, TB32), cb(14, 1, ttnn.float32, TB32),cb(15, 1, ttnn.float32, TB32), cb(17, 1, ttnn.float32, TB32), cb(18, 1, ttnn.float32, TB32)]def acc(t):return list(ttnn.TensorAccessorArgs(t).get_compile_time_args())6 unmodified linesext = [int(hdiv), int(att_col0), int(loc_off), nseg] + ends + [int(seg_table is not None), int(base is not None)]rd_ct = [0, 0, 0, 2, 7, 4, 16] + geom + [0, 1, vsrc, 0, 0] + tail + ext + accswr_ct = [0, 1, 1, 3, 8, 4, 16] + geom + [1, 0, vsrc, 0, 0] + tail + ext + accscp_ct = [0, p, nwork, nc, gx, 0, int(bool(softmax)), int(pairs)]common = [value.buffer_address(), loc.buffer_address(), attn.buffer_address(), out.buffer_address(),(seg_table if seg_table is not None else out).buffer_address(),(base if base is not None else out).buffer_address()]um = [ttnn.UnpackToDestMode.Default] * 64for i in (2, 3, 6, 12, 13):um[i] = ttnn.UnpackToDestMode.UnpackToDestFp32ccfg = ttnn.ComputeConfigDescriptor(math_fidelity=ttnn.MathFidelity.HiFi4, fp32_dest_acc_en=True,math_approx_mode=False)ccfg.unpack_to_dest_mode = umdefines = [("MSDA_K_FAST_TILIZE", "1")] if (fast_tilize or pairs) else []defines += [(f"MSDA_K_{d.upper()}", "1") for d in debug] # NOREAD / NOSTEPS: bottleneck probes onlySRC = ttnn.KernelDescriptor.SourceType.FILE_PATHdef kd(name, ct, common_args, config):33 unmodified lines3435363738394019 unmodified lines606162636465666768697071727374757677787943 unmodified lines1231241251261271281291301311321331341351361376 unmodified lines14414514614714814915015115215315415515615715815916016116216316416516616716816917033 unmodified linesdef msda(value: Any, loc: Any, attn: Any, *, points: int, nq: int, sub: int = 1,segments: Optional[Sequence[int]] = None, hdiv: int = 1, att_col0: int = 0, loc_hs: int = 0,loc_off: int = 0, seg_table: Any = None, memory_config: Any = None, fast_tilize: bool = False,debug: Sequence[str] = (), softmax: Any = False, base: Any = None, fidelity: Optional[str] = None) -> Any:"""See the module docstring. ``softmax``: False (``attn`` holds weights), True (compact logits, softmax overeach head block's ``points`` columns) or ``"joint"`` (``attn`` ``[1, 1, Q, H * 32]`` logits, the softmax over all32 columns of a head and this call's weights in columns ``att_col0 + p``: the 4-level cross-attention).19 unmodified linesif cols != 32:raise ValueError(f"msda: head-split loc {tuple(loc.shape)}")if value.layout != ttnn.ROW_MAJOR_LAYOUT:raise ValueError("msda: value must be ROW_MAJOR stick maps (N, h, w, 32), pair maps (N, h, w + 1, 64) or ""quad maps (N, h + 1, w + 1, 128)")quads = int(value.shape[-1]) == 128pairs = int(value.shape[-1]) == 64n, hv, wv, d = (int(value.shape[i]) for i in range(4))if pairs:wv, d = wv - 1, 32if quads:hv, wv, d = hv - 1, wv - 1, 32elif not quads and value.memory_config().buffer_type != ttnn.BufferType.L1:raise ValueError("msda: stick maps must be in L1 (32-byte reads at 32-byte offsets)")if d != 32:raise ValueError(f"msda: head dim {d}")vsrc = 4 if quads else (2 if pairs else 0)nb = -(-qp // 32)if segments is not None:segs = [int(s) for s in segments]43 unmodified linescbs = [cb(0, 2 * ns, ttnn.bfloat16, TB16), cb(1, 2 * ns, ttnn.bfloat16, TB16),cb(2, 6, ttnn.float32, TB32), cb(3, 6, ttnn.float32, TB32),cb(4, p, ttnn.bfloat16, TB16), cb(5, 8, ttnn.float32, TB32), cb(6, 1, ttnn.float32, TB32),cb(7, 2, ttnn.int32, TB32), cb(8, 2, ttnn.int32, TB32), cb(16, 2, ttnn.bfloat16, TB16)]if pairs or quads:cbs += [cb(19, ns, ttnn.bfloat16, TB16), cb(20, ns, ttnn.bfloat16, TB16)]if base is not None:cbs += [cb(21, 1, ttnn.float32, TB32), cb(22, 1, ttnn.float32, TB32)]if softmax:cbs += [cb(9, 2, ttnn.float32, TB32), cb(10, 1, ttnn.float32, TB32), cb(11, 1, ttnn.float32, TB32),cb(12, 2, ttnn.float32, TB32), cb(13, 2, ttnn.float32, TB32), cb(14, 1, ttnn.float32, TB32),cb(15, 1, ttnn.float32, TB32), cb(17, 1, ttnn.float32, TB32), cb(18, 2, ttnn.float32, TB32)]def acc(t):return list(ttnn.TensorAccessorArgs(t).get_compile_time_args())6 unmodified linesext = [int(hdiv), int(att_col0), int(loc_off), nseg] + ends + [int(seg_table is not None), int(base is not None)]rd_ct = [0, 0, 0, 2, 7, 4, 16] + geom + [0, 1, vsrc, 0, 0] + tail + ext + accswr_ct = [0, 1, 1, 3, 8, 4, 16] + geom + [1, 0, vsrc, 0, 0] + tail + ext + accsskipp = (pairs or quads) and not softmax and os.environ.get("AE_MSDA_SKIPP", "1") != "0"# [5]: strided items (= reader); [7]: staging blocks per point to tilize: 0 none, 1 two-tile pairs, 2 four-tile quadscp_ct = [0, p, nwork, nc, gx, int(skipp), int(bool(softmax)), 2 if quads else int(pairs)]common = [value.buffer_address(), loc.buffer_address(), attn.buffer_address(), out.buffer_address(),(seg_table if seg_table is not None else out).buffer_address(),(base if base is not None else out).buffer_address()]um = [ttnn.UnpackToDestMode.Default] * 64for i in (2, 3, 6, 12, 13):um[i] = ttnn.UnpackToDestMode.UnpackToDestFp32fid = getattr(ttnn.MathFidelity, fidelity or os.environ.get("AE_MSDA_FIDELITY", "HiFi4"))ccfg = ttnn.ComputeConfigDescriptor(math_fidelity=fid, fp32_dest_acc_en=True, math_approx_mode=False)ccfg.unpack_to_dest_mode = umdefines = [("MSDA_K_FAST_TILIZE", "1")] if (fast_tilize or pairs or quads) else []# the products as one column-broadcast FPU multiply per (point, corner) (point p's columns at 4 p: the softmax# logits, masks, geo and weights; msda_cm's form, bit for bit) for the compact-softmax self-attentionif softmax and not joint and pairs and p <= 4 and os.environ.get("AE_MSDA_COLB", "1") != "0":defines.append(("MSDA_K_COLB", "1"))if skipp:defines.append(("MSDA_K_SKIPP", "1")) # no reads for points entirely outside the mapdbg = list(debug) + [d for d in os.environ.get("AE_MSDA_DEBUG", "").split(",") if d] # probes (wrong outputs)defines += [(f"MSDA_K_{d.upper()}", "1") for d in dbg] # NOREAD / NOSTEPS: bottleneck probes onlySRC = ttnn.KernelDescriptor.SourceType.FILE_PATHdef kd(name, ct, common_args, config):
16 unmodified lines171819202122233 unmodified lines2728293031323311 unmodified lines4546474849505116 unmodified linesKDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kernels")def pair_maps(x: Any, *, heads: int, sub: int, hw, memory_config: Any = None) -> Any:import ttnnhv, wv = int(hw[0]), int(hw[1])3 unmodified linesraise ValueError(f"pair_maps: input {tuple(x.shape)} for {heads} heads x {sub} maps {hv}x{wv}")dev = x.device()n = int(heads) * int(sub)out = ttnn.allocate_tensor_on_device(ttnn.Shape([n, hv, wv + 1, 64]), ttnn.bfloat16, ttnn.ROW_MAJOR_LAYOUT,dev, memory_config or ttnn.L1_MEMORY_CONFIG)g = dev.compute_with_storage_grid_size()gx, gy = int(g.x), int(g.y)11 unmodified lineslist(ttnn.TensorAccessorArgs(out).get_compile_time_args())common = [x.buffer_address(), out.buffer_address()]SRC = ttnn.KernelDescriptor.SourceType.FILE_PATHhead = [hv, wv, int(sub), int(heads), ntr, nitems, nc, gx]ks = [ttnn.KernelDescriptor(kernel_source=os.path.join(KDIR, "pairmap2_dm.cpp"), source_type=SRC, core_ranges=crs,compile_time_args=[role] + head + accs, defines=[], runtime_args=ttnn.RuntimeArgs(),common_runtime_args=common, config=cfg)16 unmodified lines1718192021222324253 unmodified lines293031323334353611 unmodified lines4849505152535416 unmodified linesKDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kernels")def pair_maps(x: Any, *, heads: int, sub: int, hw, memory_config: Any = None, quad: bool = False) -> Any:"""``quad``: the quad map ``[heads * sub, h + 1, w + 1, 128]`` instead (256-byte page ``(m, Y, i)`` = pair pages``(m, Y - 1, i)`` and ``(m, Y, i)``, zero rows outside): one read per sample point in ``msda``."""import ttnnhv, wv = int(hw[0]), int(hw[1])3 unmodified linesraise ValueError(f"pair_maps: input {tuple(x.shape)} for {heads} heads x {sub} maps {hv}x{wv}")dev = x.device()n = int(heads) * int(sub)shape = [n, hv + 1, wv + 1, 128] if quad else [n, hv, wv + 1, 64]out = ttnn.allocate_tensor_on_device(ttnn.Shape(shape), ttnn.bfloat16, ttnn.ROW_MAJOR_LAYOUT,dev, memory_config or ttnn.L1_MEMORY_CONFIG)g = dev.compute_with_storage_grid_size()gx, gy = int(g.x), int(g.y)11 unmodified lineslist(ttnn.TensorAccessorArgs(out).get_compile_time_args())common = [x.buffer_address(), out.buffer_address()]SRC = ttnn.KernelDescriptor.SourceType.FILE_PATHhead = [hv, wv, int(sub), int(heads), ntr, nitems, nc, gx, int(bool(quad))]ks = [ttnn.KernelDescriptor(kernel_source=os.path.join(KDIR, "pairmap2_dm.cpp"), source_type=SRC, core_ranges=crs,compile_time_args=[role] + head + accs, defines=[], runtime_args=ttnn.RuntimeArgs(),common_runtime_args=common, config=cfg)
20 unmodified lines2122232425262711 unmodified lines394041424344454619 unmodified lines66676869707172737475767778798081828317 unmodified lines1011021031041051061073 unmodified lines11111211311411511611714 unmodified lines1321331341351361371381391407 unmodified lines1481491501511521531541551561571581599 unmodified lines16917017117217317417517617717817918018118218318418520 unmodified linesimport numpy as npfrom ..host.geometry import FAR, K_CAMS, R_CAP, FrameGeometry, level_sizesfrom ..reference.port_form import E, Qfrom ..ttaw.ops.conv import FeatureMapfrom ..ttaw.trace import TraceRunner, pack_outputs11 unmodified lines[f"{tag}.gather{i}" for i in range(k_cams)]def geometry_inputs(tag: str, geo: FrameGeometry) -> Dict[str, np.ndarray]:"""Host arrays of one frame's geometry under the runner's input names."""r = geo.base.shape[0]out = {f"{tag}.sca_index": geo.sca_index.astype(np.uint32),f"{tag}.base": geo.base.reshape(1, 1, r, -1).astype(np.float32),19 unmodified linesself.banks = int(banks)R = self.runner = TraceRunner(device, num_command_queues=1, name="autoe2e")RM, TL = ttnn.ROW_MAJOR_LAYOUT, ttnn.TILE_LAYOUTR.add_input("cams", shape=(1, 1, 6 * 512 * 512, 3), dtype="bfloat16", layout=RM)R.add_input("front", shape=(1, 1, 1024 * 1024, 3), dtype="bfloat16", layout=RM)R.add_input("nav", shape=(1, 1, Q, E), dtype="bfloat16", layout=TL)for k in range(8):self._add_geometry(f"f{k}", R_CAP, K_CAMS, 6)self._add_geometry("front", FRONT_CAP, 1, 1)for s in range(7):for l, (h, w) in enumerate(SIZES):R.add_state(self._ring(s, l), shape=(1, 1, 6 * h * w, E), dtype="bfloat16", layout=TL,banks=self.banks)R.add_variant("push", self._push)R.add_variant("step", self._step)# ------------------------------------------------------------------ registration@staticmethod17 unmodified linesself._ncam = getattr(self, "_ncam", {})self._ncam[tag] = (ncam, k_cams)def _geo(self, ctx, tag: str) -> Dict[str, Any]:ncam, k = self._ncam[tag]return {"sca_index": ctx[f"{tag}.sca_index"], "base": ctx[f"{tag}.base"], "seg": ctx[f"{tag}.seg"],"scale": ctx[f"{tag}.scale"], "observed": ctx[f"{tag}.observed"],3 unmodified linesdef _pyramid(self, x, n, size) -> List[Any]:import ttnnouts = self.img(FeatureMap(x, n, size, size, 3))res = []for o in outs:shape = (1, 1, n * o.height * o.width, E)14 unmodified linesself._shift(ctx, fpn)for t in fpn:ttnn.deallocate(t)return pack_outputs({"ok": ctx["f0.scale"]}, dtype="float32")def _step(self, ctx):import ttnnfpn = self._pyramid(ctx["cams"], 6, 512)7 unmodified linesimage_bev = self.t8(bevs + [curf])for t in bevs + [curf]:ttnn.deallocate(t)fused = self.mfuse(image_bev, ctx["nav"])ttnn.deallocate(image_bev)self._shift(ctx, fpn)for t in fpn:ttnn.deallocate(t)return pack_outputs({"fused": fused}, dtype="float32")# ------------------------------------------------------------------ host APIdef capture(self) -> None:9 unmodified linesdef push(self, cams_input: np.ndarray) -> None:"""``cams_input`` [6, 512, 512, 3] float32 (``backbone_input``) into the ring (history prime)."""self.runner("push", inputs={"cams": cams_input.reshape(1, 1, -1, 3)})def step(self, cams_input: np.ndarray, front_input: np.ndarray, geos: Sequence[FrameGeometry],geo_front: FrameGeometry, nav_rows: np.ndarray) -> np.ndarray:"""One step -> the fused BEV ``[Q, 256]`` float32 (for the host planner)."""inputs = {"cams": cams_input.reshape(1, 1, -1, 3), "front": front_input.reshape(1, 1, -1, 3),"nav": nav_rows.reshape(1, 1, Q, E)}for k, g in enumerate(geos):inputs.update(geometry_inputs(f"f{k}", g))inputs.update(geometry_inputs("front", geo_front))out = self.runner("step", inputs=inputs)return np.asarray(out["fused"], np.float32).reshape(Q, E)def release(self) -> None:20 unmodified lines2122232425262711 unmodified lines3940414243444546474819 unmodified lines6869707172737475767778798081828384858687888990919293949517 unmodified lines1131141151161171181191201211221231241251261271281291303 unmodified lines13413513613713813914014114214314414 unmodified lines1591601611621631641651661677 unmodified lines1751761771781791801811821831841851861871881891901911921931949 unmodified lines20420520620720820921021121221321421521621721821922022122222322422522622722822923023120 unmodified linesimport numpy as npfrom ..host.geometry import FAR, K_CAMS, R_CAP, CmGeometry, FrameGeometry, level_sizes, use_cmfrom ..reference.port_form import E, Qfrom ..ttaw.ops.conv import FeatureMapfrom ..ttaw.trace import TraceRunner, pack_outputs11 unmodified lines[f"{tag}.gather{i}" for i in range(k_cams)]def geometry_inputs(tag: str, geo) -> Dict[str, np.ndarray]:"""Host arrays of one frame's geometry under the runner's input names."""if isinstance(geo, CmGeometry):return {f"{tag}.table": geo.table.reshape(1, 1, Q, 32)} # observed: from the table's count on the devicer = geo.base.shape[0]out = {f"{tag}.sca_index": geo.sca_index.astype(np.uint32),f"{tag}.base": geo.base.reshape(1, 1, r, -1).astype(np.float32),19 unmodified linesself.banks = int(banks)R = self.runner = TraceRunner(device, num_command_queues=1, name="autoe2e")RM, TL = ttnn.ROW_MAJOR_LAYOUT, ttnn.TILE_LAYOUT# images as one row per image row (a 3-byte row per pixel is a slow host -> device copy: 39 ms for the 6# views), reshaped to pixel rows on the device; nav row-major, tilized on the deviceR.add_input("cams", shape=(1, 1, 6 * 512, 512 * 3), dtype="bfloat16", layout=RM)R.add_input("front", shape=(1, 1, 1024, 1024 * 3), dtype="bfloat16", layout=RM)R.add_input("nav", shape=(1, 1, Q, E), dtype="bfloat16", layout=RM)self.cm = self.enc.cmfor k in range(8):if self.cm:self._add_cm_geometry(f"f{k}")else:self._add_geometry(f"f{k}", R_CAP, K_CAMS, 6)self._add_geometry("front", FRONT_CAP, 1, 1)for s in range(7):for l, (h, w) in enumerate(SIZES):R.add_state(self._ring(s, l), shape=(1, 1, 6 * h * w, E), dtype="bfloat16", layout=TL,banks=self.banks)# the step in two traces: step_a (images, the 8 BEV frames, the front fusion, T8 -> state image_bev) and# step_b (the map fusion with nav): the host computes the navigation BEV while step_a runsR.add_state("image_bev", shape=(1, 1, Q, E), dtype="bfloat16", layout=TL)R.add_variant("push", self._push)R.add_variant("step_a", self._step_a)R.add_variant("step_b", self._step_b)# ------------------------------------------------------------------ registration@staticmethod17 unmodified linesself._ncam = getattr(self, "_ncam", {})self._ncam[tag] = (ncam, k_cams)def _add_cm_geometry(self, tag: str) -> None:import ttnntable = np.zeros((1, 1, Q, 32), np.int32)table[..., 16:18] = -1self.runner.add_input(f"{tag}.table", table, dtype="int32", layout=ttnn.TILE_LAYOUT)self._ncam = getattr(self, "_ncam", {})self._ncam[tag] = Nonedef _geo(self, ctx, tag: str) -> Dict[str, Any]:if self._ncam[tag] is None:return {"table": ctx[f"{tag}.table"]}ncam, k = self._ncam[tag]return {"sca_index": ctx[f"{tag}.sca_index"], "base": ctx[f"{tag}.base"], "seg": ctx[f"{tag}.seg"],"scale": ctx[f"{tag}.scale"], "observed": ctx[f"{tag}.observed"],3 unmodified linesdef _pyramid(self, x, n, size) -> List[Any]:import ttnnshape = (1, 1, n * size * size, 3)px = x if tuple(x.shape) == shape else ttnn.reshape(x, shape) # image rows -> pixel rows (a copy)outs = self.img(FeatureMap(px, n, size, size, 3))if px is not x:ttnn.deallocate(px)res = []for o in outs:shape = (1, 1, n * o.height * o.width, E)14 unmodified linesself._shift(ctx, fpn)for t in fpn:ttnn.deallocate(t)return pack_outputs({"ok": ctx["front.scale"]}, dtype="float32") # a dummy output (the ring is the result)def _step_a(self, ctx):import ttnnfpn = self._pyramid(ctx["cams"], 6, 512)7 unmodified linesimage_bev = self.t8(bevs + [curf])for t in bevs + [curf]:ttnn.deallocate(t)ctx.write_state("image_bev", image_bev)ttnn.deallocate(image_bev)self._shift(ctx, fpn)for t in fpn:ttnn.deallocate(t)return pack_outputs({"ok": ctx["front.scale"]}, dtype="float32") # a dummy output (the state is the result)def _step_b(self, ctx):import ttnnnav = ttnn.to_layout(ctx["nav"], ttnn.TILE_LAYOUT, memory_config=ttnn.DRAM_MEMORY_CONFIG)fused = self.mfuse(ctx["image_bev"], nav)ttnn.deallocate(nav)return pack_outputs({"fused": fused}, dtype="bfloat16") # the fused BEV is bf16: the same values, half the read# ------------------------------------------------------------------ host APIdef capture(self) -> None:9 unmodified linesdef push(self, cams_input: np.ndarray) -> None:"""``cams_input`` [6, 512, 512, 3] float32 (``backbone_input``) into the ring (history prime)."""self.runner("push", inputs={"cams": cams_input.reshape(1, 1, 6 * 512, 512 * 3)})def step(self, cams_input: np.ndarray, front_input: np.ndarray, geos: Sequence[Any],geo_front: FrameGeometry, nav_rows: np.ndarray) -> np.ndarray:"""One step -> the fused BEV ``[Q, 256]`` float32 (for the host planner). ``nav_rows`` ``[Q, 256]``: numpy, or atorch bf16 tensor (no conversion on this thread: ``api`` converts it on its host pool)."""self.step_begin(cams_input, front_input, geos, geo_front)return self.step_end(nav_rows)def step_begin(self, cams_input: np.ndarray, front_input: np.ndarray, geos: Sequence[Any],geo_front: FrameGeometry) -> None:"""Upload the frame and start step_a (non-blocking): the host is free until :meth:`step_end`."""inputs = {"cams": cams_input.reshape(1, 1, 6 * 512, 512 * 3),"front": front_input.reshape(1, 1, 1024, 1024 * 3)}for k, g in enumerate(geos):inputs.update(geometry_inputs(f"f{k}", g))inputs.update(geometry_inputs("front", geo_front))self.runner.run("step_a", inputs=inputs)def step_end(self, nav_rows: Any) -> np.ndarray:"""The map fusion with the navigation BEV ``[Q, 256]`` (numpy or torch bf16) -> the fused BEV ``[Q, 256]``."""out = self.runner("step_b", inputs={"nav": nav_rows.reshape(1, 1, Q, E)})return np.asarray(out["fused"], np.float32).reshape(Q, E)def release(self) -> None:
19 unmodified lines2021222324252627282930313233343536377 unmodified lines454647484950515253545519 unmodified linesclass TtT8:def __init__(self, state: Dict[str, Any], *, precision: str = PREC):self.blocks = []for b in range(3):p = f"{T8}.layers.{b}"c1 = Conv2d(*fold_bn(state, p + ".conv1", p + ".bn1"), padding=1, activation="relu", precision=precision,name=f"t8.{b}.conv1")c2 = Conv2d(*fold_bn(state, p + ".conv2", p + ".bn2"), padding=1, precision=precision,name=f"t8.{b}.conv2")ds = Noneif p + ".downsample.0.weight" in state:ds = Conv2d(*fold_bn(state, p + ".downsample.0", p + ".downsample.1"), padding=1, precision=precision,name=f"t8.{b}.downsample")self.blocks.append((c1, c2, ds))self.linear = RowLinear(_arr(state[f"{T8}.layer_norm.0.weight"]).T, _arr(state[f"{T8}.layer_norm.0.bias"]),precision="HiFi4+fp32+l1acc:w=fp32", name="t8.linear")self.ln_g = _arr(state[f"{T8}.layer_norm.1.weight"]).reshape(1, -1)7 unmodified linesd = bevs[0].device()x = FeatureMap(ttnn.concat(list(bevs), dim=3, memory_config=ttnn.DRAM_MEMORY_CONFIG), 1, BEV_H, BEV_W, 2048)for c1, c2, ds in self.blocks:h = c1(x)o = c2(h)h.deallocate()idt = ds(x) if ds is not None else xy = residual_add(o, idt, "relu")o.deallocate()if ds is not None:19 unmodified lines2021222324252627282930313233343536373839404142434445464748495051525354555657587 unmodified lines66676869707172737475767778798081828384858619 unmodified linesclass TtT8:def __init__(self, state: Dict[str, Any], *, precision: str = PREC):import osimport ttnnprecision = os.environ.get("AE_PREC_T8", precision)# block-sharded DRAM slices with double-buffered activations and weights (tests/dev_t8_sweep.py: 3 x 3 512# 8.44 -> 7.36 ms, the fused 2048 -> 1024 34.6 -> 30.1 ms, the same outputs bit for bit); AE_T8_DBUF=0: ttnn's# default configcc = Noneif os.environ.get("AE_T8_DBUF", "1") != "0":cc = dict(shard_layout=ttnn.TensorMemoryLayout.BLOCK_SHARDED, enable_act_double_buffer=True,enable_weights_double_buffer=True)# block 0's conv1 (relu) and its 3 x 3 projection read the same 2048-channel input: one conv to 1024 channels# (the two weight sets stacked), then the halves (AE_T8_FUSE=0: two convs)self.fuse0 = os.environ.get("AE_T8_FUSE", "1") != "0"self.fused0 = Noneself.blocks = []for b in range(3):p = f"{T8}.layers.{b}"c1 = Conv2d(*fold_bn(state, p + ".conv1", p + ".bn1"), padding=1, activation="relu", precision=precision,conv_config=cc, name=f"t8.{b}.conv1")c2 = Conv2d(*fold_bn(state, p + ".conv2", p + ".bn2"), padding=1, precision=precision,conv_config=cc, name=f"t8.{b}.conv2")ds = Noneif p + ".downsample.0.weight" in state:ds = Conv2d(*fold_bn(state, p + ".downsample.0", p + ".downsample.1"), padding=1, precision=precision,conv_config=cc, name=f"t8.{b}.downsample")self.blocks.append((c1, c2, ds))if b == 0 and ds is not None and self.fuse0:w1, b1 = fold_bn(state, p + ".conv1", p + ".bn1")wd, bd = fold_bn(state, p + ".downsample.0", p + ".downsample.1")self.fused0 = Conv2d(np.concatenate([w1, wd]), np.concatenate([b1, bd]), padding=1,precision=precision, conv_config=cc, name="t8.0.conv1_downsample")self.linear = RowLinear(_arr(state[f"{T8}.layer_norm.0.weight"]).T, _arr(state[f"{T8}.layer_norm.0.bias"]),precision="HiFi4+fp32+l1acc:w=fp32", name="t8.linear")self.ln_g = _arr(state[f"{T8}.layer_norm.1.weight"]).reshape(1, -1)7 unmodified linesd = bevs[0].device()x = FeatureMap(ttnn.concat(list(bevs), dim=3, memory_config=ttnn.DRAM_MEMORY_CONFIG), 1, BEV_H, BEV_W, 2048)for bi, (c1, c2, ds) in enumerate(self.blocks):if bi == 0 and self.fused0 is not None:f = self.fused0(x)ft = f.tensorrows = int(ft.shape[-2])h = f.with_tensor(ttnn.relu(ttnn.slice(ft, [0, 0, 0, 0], [1, 1, rows, 512])), 512)idt = f.with_tensor(ttnn.slice(ft, [0, 0, 0, 512], [1, 1, rows, 1024]), 512)f.deallocate()o = c2(h)h.deallocate()else:h = c1(x)o = c2(h)h.deallocate()idt = ds(x) if ds is not None else xy = residual_add(o, idt, "relu")o.deallocate()if ds is not None:
1{"id":"43e8fb51e99bdba99976a897780b318a736f070326de2981b98f852d8196e469","parent":"dedfcea43c50e05c4e2e4fbb88e839d5fc9499c0054a4b00fc0e2004e8c0ff24","created":"1970-01-01T09:00:00+09:00","container_config":{"Hostname":"","Domainname":"","User":"","AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":null,"Cmd":null,"Image":"","Volumes":null,"WorkingDir":"","Entrypoint":null,"OnBuild":null,"Labels":null},"os":"linux"}1{"architecture":"amd64","config":{"User":"tt","Env":["PATH=/opt/tt-venv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin","VENV=/opt/tt-venv","VIRTUAL_ENV=/opt/tt-venv","TT_METAL_RUNTIME_ROOT=/opt/tt-metal","TT_METAL_HOME=/opt/tt-metal","PYTHONPATH=/opt/tt-metal","LD_LIBRARY_PATH=/opt/tt-metal/build/lib:/opt/openmpi-v5.0.7-ulfm/lib","EXTRA_MODELS_DIR=","TT_VLLM_BUILTIN_MODELS=","TT_MODEL_KIND=tt-dit-server","HF_HOME=/hf","TT_METAL_CACHE=/cache","HOME=/home/tt","USER=tt","LOGNAME=tt"],"Entrypoint":["/usr/local/bin/entrypoint.sh"],"Cmd":["/usr/local/bin/serve-default.sh"],"WorkingDir":"/home/tt/work","Labels":{"org.opencontainers.image.revision":"44d66500520fda9f2c7060c0f6b41ec48f7ab37e","org.opencontainers.image.version":"22.04","org.tenstorrent.tt-model":"auto_e2e-p150","org.tenstorrent.tt-model.arch":"blackhole","org.tenstorrent.tt-model.kind":"tt-dit-server","org.tenstorrent.tt-model.plugin":"","org.tenstorrent.tt-model.profiles":"default","org.tenstorrent.tt-model.repo":"changh95/auto_e2e-p150","org.tenstorrent.tt-model.tt-metal":"","org.tenstorrent.tt-model.weights":"AutowareFoundation/auto_e2e"},"ArgsEscaped":true},"created":"2026-12-05T22:59:45.850721395+09:00","history":[{"created":"2026-09-03T12:14:51.139348462Z","created_by":"/bin/sh -c #(nop) ARG RELEASE","empty_layer":true},{"created":"2026-09-03T12:14:51.170427469Z","created_by":"/bin/sh -c #(nop) ARG LAUNCHPAD_BUILD_ARCH","empty_layer":true},{"created":"2026-09-03T12:14:51.200307479Z","created_by":"/bin/sh -c #(nop) LABEL org.opencontainers.image.version=22.04","empty_layer":true},{"created":"2026-09-03T12:14:53.528689977Z","created_by":"/bin/sh -c #(nop) ADD file:81c01921c5f642ac2fcbfae682e489e8e64b347467d9fa1587707e310e64d790 in / "},{"created":"2026-09-03T12:14:54.045714841Z","created_by":"/bin/sh -c #(nop) CMD [\"/bin/bash\"]","empty_layer":true},{"created":"2026-12-05T09:07:31.631409893+09:00","created_by":"ARG OMPI_DIR=/opt/openmpi-v5.0.7-ulfm","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T09:07:31.631409893+09:00","created_by":"ARG EXTRA_MODELS_DIR=","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T09:07:31.631409893+09:00","created_by":"ARG TT_MODEL_KIND","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T09:07:31.631409893+09:00","created_by":"ARG MODEL_NAME","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T09:07:31.631409893+09:00","created_by":"ARG MODEL_REPO","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T09:07:31.631409893+09:00","created_by":"ARG MODEL_WEIGHTS","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T09:07:31.631409893+09:00","created_by":"ARG MODEL_ARCH","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T09:07:31.631409893+09:00","created_by":"ARG MODEL_PROFILES","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T09:07:31.631409893+09:00","created_by":"ARG MODEL_TT_METAL_SHA","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T09:07:31.631409893+09:00","created_by":"ARG MODEL_TT_METAL_DESCRIBE","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T09:07:31.631409893+09:00","created_by":"ARG MODEL_PLUGIN_SHA","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T09:07:31.631409893+09:00","created_by":"RUN |11 OMPI_DIR=/opt/openmpi-v5.0.7-ulfm EXTRA_MODELS_DIR= TT_MODEL_KIND=tt-dit-server MODEL_NAME=auto_e2e-p150 MODEL_REPO=changh95/auto_e2e-p150 MODEL_WEIGHTS=AutowareFoundation/auto_e2e MODEL_ARCH=blackhole MODEL_PROFILES=default MODEL_TT_METAL_SHA=44d66500520fda9f2c7060c0f6b41ec48f7ab37e MODEL_TT_METAL_DESCRIBE= MODEL_PLUGIN_SHA= /bin/sh -c apt-get update \u0026\u0026 apt-get install -y --no-install-recommends libhwloc15 libnuma1 libatomic1 libudev1 libcap2 zlib1g libmpc3 libmpfr6 libgmp10 libzstd1 libevent-core-2.1-7 libevent-pthreads-2.1-7 libgl1 libsndfile1 ca-certificates \u0026\u0026 apt-get clean \u0026\u0026 rm -rf /var/lib/apt/lists/* # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T09:07:31.95297359+09:00","created_by":"RUN |11 OMPI_DIR=/opt/openmpi-v5.0.7-ulfm EXTRA_MODELS_DIR= TT_MODEL_KIND=tt-dit-server MODEL_NAME=auto_e2e-p150 MODEL_REPO=changh95/auto_e2e-p150 MODEL_WEIGHTS=AutowareFoundation/auto_e2e MODEL_ARCH=blackhole MODEL_PROFILES=default MODEL_TT_METAL_SHA=44d66500520fda9f2c7060c0f6b41ec48f7ab37e MODEL_TT_METAL_DESCRIBE= MODEL_PLUGIN_SHA= /bin/sh -c existing=\"$(getent passwd 1000 | cut -d: -f1)\" \u0026\u0026 if [ -n \"$existing\" ]; then userdel -r \"$existing\" 2\u003e/dev/null || userdel \"$existing\"; fi \u0026\u0026 useradd --uid 1000 --create-home --home-dir /home/tt --shell /bin/bash tt \u0026\u0026 mkdir -p /home/tt/work/logs /cache /opt/tt-metal \u0026\u0026 chown -R tt:tt /home/tt /cache /opt/tt-metal \u0026\u0026 chmod 1777 /home/tt /home/tt/work /home/tt/work/logs /cache # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T09:12:10.929790863+09:00","created_by":"COPY /opt/openmpi-v5.0.7-ulfm /opt/openmpi-v5.0.7-ulfm # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T09:12:11.535817847+09:00","created_by":"COPY /opt/tenstorrent /opt/tenstorrent # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T10:27:44.58528759+09:00","created_by":"COPY /usr/local/share/uv /usr/local/share/uv # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T22:59:28.531798518+09:00","created_by":"COPY /opt/tt-venv /opt/tt-venv # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T22:59:28.63367437+09:00","created_by":"COPY /opt/vllm /opt/vllm # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T22:59:29.320163921+09:00","created_by":"COPY --chown=tt:tt /opt/tt-metal/runtime /opt/tt-metal/runtime # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T22:59:29.57498304+09:00","created_by":"COPY --chown=tt:tt /opt/tt-metal/build_Release /opt/tt-metal/build_Release # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T22:59:29.835279731+09:00","created_by":"COPY --chown=tt:tt /opt/tt-metal/build /opt/tt-metal/build # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T22:59:30.696212201+09:00","created_by":"COPY --chown=tt:tt /opt/tt-metal/tt_metal /opt/tt-metal/tt_metal # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T22:59:31.433051404+09:00","created_by":"COPY --chown=tt:tt /opt/tt-metal/ttnn /opt/tt-metal/ttnn # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T22:59:31.584189225+09:00","created_by":"COPY --chown=tt:tt /opt/tt-metal/tools /opt/tt-metal/tools # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T22:59:31.744133258+09:00","created_by":"COPY --chown=tt:tt /opt/tt-metal/setup.py /opt/tt-metal/pyproject.toml /opt/tt-metal/ # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T22:59:31.893727205+09:00","created_by":"COPY --chown=tt:tt code/ /opt/tt-metal/ # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T22:59:32.349067781+09:00","created_by":"RUN |11 OMPI_DIR=/opt/openmpi-v5.0.7-ulfm EXTRA_MODELS_DIR= TT_MODEL_KIND=tt-dit-server MODEL_NAME=auto_e2e-p150 MODEL_REPO=changh95/auto_e2e-p150 MODEL_WEIGHTS=AutowareFoundation/auto_e2e MODEL_ARCH=blackhole MODEL_PROFILES=default MODEL_TT_METAL_SHA=44d66500520fda9f2c7060c0f6b41ec48f7ab37e MODEL_TT_METAL_DESCRIBE= MODEL_PLUGIN_SHA= /bin/sh -c find /opt/tt-metal \\( -type f -o -type d \\) \\( ! -perm -o+r -o \\( -type d ! -perm -o+x \\) \\) -exec chmod a+rX {} + # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T22:59:32.461022759+09:00","created_by":"COPY --chmod=0755 entrypoint.sh /usr/local/bin/entrypoint.sh # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T22:59:32.568648474+09:00","created_by":"COPY --chmod=0755 serve-default.sh /usr/local/bin/serve-default.sh # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T22:59:32.568648474+09:00","created_by":"ENV VENV=/opt/tt-venv","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:32.568648474+09:00","created_by":"ENV VIRTUAL_ENV=/opt/tt-venv","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:32.568648474+09:00","created_by":"ENV PATH=/opt/tt-venv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:32.568648474+09:00","created_by":"ENV TT_METAL_RUNTIME_ROOT=/opt/tt-metal","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:32.568648474+09:00","created_by":"ENV TT_METAL_HOME=/opt/tt-metal","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:32.568648474+09:00","created_by":"ENV PYTHONPATH=/opt/tt-metal","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:32.568648474+09:00","created_by":"ENV LD_LIBRARY_PATH=/opt/tt-metal/build/lib:/opt/openmpi-v5.0.7-ulfm/lib","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:32.568648474+09:00","created_by":"ENV EXTRA_MODELS_DIR=","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:32.568648474+09:00","created_by":"ARG TT_VLLM_BUILTIN_MODELS=","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:32.568648474+09:00","created_by":"ENV TT_VLLM_BUILTIN_MODELS=","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:32.568648474+09:00","created_by":"ENV TT_MODEL_KIND=tt-dit-server","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:32.568648474+09:00","created_by":"ENV HF_HOME=/hf","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:32.568648474+09:00","created_by":"ENV TT_METAL_CACHE=/cache","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:32.568648474+09:00","created_by":"ENV HOME=/home/tt","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:32.568648474+09:00","created_by":"ENV USER=tt","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:32.568648474+09:00","created_by":"ENV LOGNAME=tt","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:32.568648474+09:00","created_by":"USER tt","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:32.68118188+09:00","created_by":"WORKDIR /home/tt/work","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T22:59:32.786788549+09:00","created_by":"COPY --chmod=0755 verify.sh /ctx/verify.sh # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T22:59:45.549522716+09:00","created_by":"RUN |12 OMPI_DIR=/opt/openmpi-v5.0.7-ulfm EXTRA_MODELS_DIR= TT_MODEL_KIND=tt-dit-server MODEL_NAME=auto_e2e-p150 MODEL_REPO=changh95/auto_e2e-p150 MODEL_WEIGHTS=AutowareFoundation/auto_e2e MODEL_ARCH=blackhole MODEL_PROFILES=default MODEL_TT_METAL_SHA=44d66500520fda9f2c7060c0f6b41ec48f7ab37e MODEL_TT_METAL_DESCRIBE= MODEL_PLUGIN_SHA= TT_VLLM_BUILTIN_MODELS= /bin/sh -c bash /ctx/verify.sh # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T22:59:45.549522716+09:00","created_by":"USER root","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:45.850721395+09:00","created_by":"RUN |12 OMPI_DIR=/opt/openmpi-v5.0.7-ulfm EXTRA_MODELS_DIR= TT_MODEL_KIND=tt-dit-server MODEL_NAME=auto_e2e-p150 MODEL_REPO=changh95/auto_e2e-p150 MODEL_WEIGHTS=AutowareFoundation/auto_e2e MODEL_ARCH=blackhole MODEL_PROFILES=default MODEL_TT_METAL_SHA=44d66500520fda9f2c7060c0f6b41ec48f7ab37e MODEL_TT_METAL_DESCRIBE= MODEL_PLUGIN_SHA= TT_VLLM_BUILTIN_MODELS= /bin/sh -c chmod -R a+rwX /home/tt # buildkit","comment":"buildkit.dockerfile.v0"},{"created":"2026-12-05T22:59:45.850721395+09:00","created_by":"USER tt","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:45.850721395+09:00","created_by":"LABEL org.tenstorrent.tt-model=auto_e2e-p150 org.tenstorrent.tt-model.repo=changh95/auto_e2e-p150 org.tenstorrent.tt-model.weights=AutowareFoundation/auto_e2e org.tenstorrent.tt-model.arch=blackhole org.tenstorrent.tt-model.kind=tt-dit-server org.tenstorrent.tt-model.profiles=default org.opencontainers.image.revision=44d66500520fda9f2c7060c0f6b41ec48f7ab37e org.tenstorrent.tt-model.tt-metal= org.tenstorrent.tt-model.plugin=","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:45.850721395+09:00","created_by":"ENTRYPOINT [\"/usr/local/bin/entrypoint.sh\"]","comment":"buildkit.dockerfile.v0","empty_layer":true},{"created":"2026-12-05T22:59:45.850721395+09:00","created_by":"CMD [\"/usr/local/bin/serve-default.sh\"]","comment":"buildkit.dockerfile.v0","empty_layer":true}],"os":"linux","rootfs":{"type":"layers","diff_ids":["sha256:ea16cace89338c84eb6bcb91a7efdfcae6838fff359efe951858227436486c34","sha256:3dd1ac48a70dd22daa1ffcb0d48b11e6f6182adf5294978fb4ba76d952ef0783","sha256:d6603778cc6fd3644acabd272a700e30287d90530646e5251f0d71d8f20af1f0","sha256:2bd0d4c59deb92321e511a3e3898fff70d2a1b007a7fb7477a62d1603f2e07fc","sha256:15d39bf3938c81b3767aec3be0a176d632697bc5879f9b918f025b5f7a1fcf86","sha256:52565ae1530a1f730685ff8f74e3b7c28fc35d2ae6c18d537fb0df62075fe7c9","sha256:241d4a5b2a827d8e1238d9227a5ebde070af2a9a0b0918ec8cf3839c7691e3de","sha256:188ff78ba17c8232a2f3aba4b35f5c7dbd5307be0d492e11ef26c958623660d3","sha256:3eaf130059f3e4080f8dc71afcb2ed53310ee60187b4bca947458c563849a457","sha256:6b1f63635e5e7cd962ea3f65b6036e86d4e838a24de9559a546834c1b49ed396","sha256:8ba27c0105636d886344b2db6eeb3f7c41fc587c486aa74e11d069912840ef55","sha256:be2c3263fa139c48ac5163fb402a10ff90827fd38c3c613a372549bacde47ee0","sha256:9df66ea49aa0dedf21915ca1731ec8ec470892518778685652756275ba89eea5","sha256:eafd2f0c5ccfc07ea4fc93c0763b5b6b72eaa55f8cf8535f5c7d6e90a09cb988","sha256:807500fca677e534be2ce5dfa50ad6d152c0654eecf98afe6a9f132bcfb950e6","sha256:911536ee12614e924d480b52f58e8682139a877f7f74730411615e86203779e1","sha256:84e404bdc8a041effeeffdfd9eedc4f40a618c19c8dc142d7b6012891dc56fa2","sha256:f19dbd2342a14e3564a5c014fd3b805a776ff07fa5ab2174e56cff486299e3e3","sha256:da39eddd281ec9c469573d49cda87eb07e04c102a2f2a098f5b2e2a5eedf5408","sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef","sha256:5b7a27d05e6bed4da52cefef7e59cb1f91ea8214a022a1e6e62ec6081f3df589","sha256:6706e1ed57bf105dc9cd1e3eef974838bbc2d69aca3c7d5a31d8f6224337e6fe","sha256:508946978b347a9317dcda6349a6e3a9468f6446dfc6ae299f2862ba38d300b3"]}}1{"id":"e44520045167e9e4fb9f38d8484d298b2214ddd6facc0ace40b1ad4f1596f073","parent":"4d0c5cb64b2d4029b4f1542714e0d07a4e82e88de5adf65427953f55b67729d0","created":"1970-01-01T09:00:00+09:00","container_config":{"Hostname":"","Domainname":"","User":"","AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":null,"Cmd":null,"Image":"","Volumes":null,"WorkingDir":"","Entrypoint":null,"OnBuild":null,"Labels":null},"os":"linux"}1{"id":"0cd30d0ad7fb9ba062c9cb2f31b4508600c1f265c2f8aa1dff412427cdf9b6a0","parent":"0d583c3437323871f4649efef25073a459e9be53e3920fe7212860d19670be10","created":"1970-01-01T09:00:00+09:00","container_config":{"Hostname":"","Domainname":"","User":"","AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":null,"Cmd":null,"Image":"","Volumes":null,"WorkingDir":"","Entrypoint":null,"OnBuild":null,"Labels":null},"os":"linux"}123version https://git-lfs.github.com/spec/v1oid sha256:241d4a5b2a827d8e1238d9227a5ebde070af2a9a0b0918ec8cf3839c7691e3desize 10445578241{"id":"723893cae97f84df75919601f1a0278804aad19244dfe01d8543d7fe3b2f25c0","parent":"99ac2302f22e7dd9c96c663d732462a434621f70401c9f254a816218c0fc419f","created":"1970-01-01T09:00:00+09:00","container_config":{"Hostname":"","Domainname":"","User":"","AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":null,"Cmd":null,"Image":"","Volumes":null,"WorkingDir":"","Entrypoint":null,"OnBuild":null,"Labels":null},"os":"linux"}1{"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v1+json","config":{"mediaType":"application/vnd.oci.image.config.v1+json","digest":"sha256:0f4b5bb0adf19a18c065d16e0056ab8b28f2982602edbe333d5f45d51b47f3fe","size":14910},"layers":[{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:ea16cace89338c84eb6bcb91a7efdfcae6838fff359efe951858227436486c34","size":80641024},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:3dd1ac48a70dd22daa1ffcb0d48b11e6f6182adf5294978fb4ba76d952ef0783","size":204253184},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:d6603778cc6fd3644acabd272a700e30287d90530646e5251f0d71d8f20af1f0","size":352256},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:2bd0d4c59deb92321e511a3e3898fff70d2a1b007a7fb7477a62d1603f2e07fc","size":33464832},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:15d39bf3938c81b3767aec3be0a176d632697bc5879f9b918f025b5f7a1fcf86","size":454126592},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:52565ae1530a1f730685ff8f74e3b7c28fc35d2ae6c18d537fb0df62075fe7c9","size":187642880},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:241d4a5b2a827d8e1238d9227a5ebde070af2a9a0b0918ec8cf3839c7691e3de","size":1044557824},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:188ff78ba17c8232a2f3aba4b35f5c7dbd5307be0d492e11ef26c958623660d3","size":2048},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:3eaf130059f3e4080f8dc71afcb2ed53310ee60187b4bca947458c563849a457","size":454823936},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:6b1f63635e5e7cd962ea3f65b6036e86d4e838a24de9559a546834c1b49ed396","size":144154624},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:8ba27c0105636d886344b2db6eeb3f7c41fc587c486aa74e11d069912840ef55","size":144154624},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:be2c3263fa139c48ac5163fb402a10ff90827fd38c3c613a372549bacde47ee0","size":208406016},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:9df66ea49aa0dedf21915ca1731ec8ec470892518778685652756275ba89eea5","size":73226240},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:eafd2f0c5ccfc07ea4fc93c0763b5b6b72eaa55f8cf8535f5c7d6e90a09cb988","size":6246400},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:807500fca677e534be2ce5dfa50ad6d152c0654eecf98afe6a9f132bcfb950e6","size":23552},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:911536ee12614e924d480b52f58e8682139a877f7f74730411615e86203779e1","size":1564672},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:84e404bdc8a041effeeffdfd9eedc4f40a618c19c8dc142d7b6012891dc56fa2","size":5632},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:f19dbd2342a14e3564a5c014fd3b805a776ff07fa5ab2174e56cff486299e3e3","size":4608},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:da39eddd281ec9c469573d49cda87eb07e04c102a2f2a098f5b2e2a5eedf5408","size":4608},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef","size":1024},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:5b7a27d05e6bed4da52cefef7e59cb1f91ea8214a022a1e6e62ec6081f3df589","size":4096},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:6706e1ed57bf105dc9cd1e3eef974838bbc2d69aca3c7d5a31d8f6224337e6fe","size":241664},{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"sha256:508946978b347a9317dcda6349a6e3a9468f6446dfc6ae299f2862ba38d300b3","size":39936}]}1{"id":"4d0c5cb64b2d4029b4f1542714e0d07a4e82e88de5adf65427953f55b67729d0","parent":"085601d6b3bfa51e539a42f7162d171143ff2ff2b2b930b1aec7e6cf440d849e","created":"1970-01-01T09:00:00+09:00","container_config":{"Hostname":"","Domainname":"","User":"","AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":null,"Cmd":null,"Image":"","Volumes":null,"WorkingDir":"","Entrypoint":null,"OnBuild":null,"Labels":null},"os":"linux"}1{"id":"085601d6b3bfa51e539a42f7162d171143ff2ff2b2b930b1aec7e6cf440d849e","parent":"bb1572528b77d76d7d32e95cf98cc5ceaa09861e28cf162468c03b2ead1c9358","created":"1970-01-01T09:00:00+09:00","container_config":{"Hostname":"","Domainname":"","User":"","AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":null,"Cmd":null,"Image":"","Volumes":null,"WorkingDir":"","Entrypoint":null,"OnBuild":null,"Labels":null},"os":"linux"}123version https://git-lfs.github.com/spec/v1oid sha256:3eaf130059f3e4080f8dc71afcb2ed53310ee60187b4bca947458c563849a457size 4548239361{"id":"5e8935035e1dc27f5f213bd0451c05e53c07d8f406310d07f22d141ccbe89b27","parent":"e44520045167e9e4fb9f38d8484d298b2214ddd6facc0ace40b1ad4f1596f073","created":"1970-01-01T09:00:00+09:00","container_config":{"Hostname":"","Domainname":"","User":"","AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":null,"Cmd":null,"Image":"","Volumes":null,"WorkingDir":"","Entrypoint":null,"OnBuild":null,"Labels":null},"os":"linux"}1{"id":"dac71ae9029bfa1837bd103dd3b5a382d73ea0ba900faff8568b1ae0253500b4","parent":"723893cae97f84df75919601f1a0278804aad19244dfe01d8543d7fe3b2f25c0","created":"1970-01-01T09:00:00+09:00","container_config":{"Hostname":"","Domainname":"","User":"","AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":null,"Cmd":null,"Image":"","Volumes":null,"WorkingDir":"","Entrypoint":null,"OnBuild":null,"Labels":null},"os":"linux"}123version https://git-lfs.github.com/spec/v1oid sha256:6706e1ed57bf105dc9cd1e3eef974838bbc2d69aca3c7d5a31d8f6224337e6fesize 241664123version https://git-lfs.github.com/spec/v1oid sha256:6b1f63635e5e7cd962ea3f65b6036e86d4e838a24de9559a546834c1b49ed396size 1441546241{"id":"7118941695bfb6484d8ffe52181c964167275bb265d9122136f5a3f51cb16411","parent":"dac71ae9029bfa1837bd103dd3b5a382d73ea0ba900faff8568b1ae0253500b4","created":"1970-01-01T09:00:00+09:00","container_config":{"Hostname":"","Domainname":"","User":"","AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":null,"Cmd":null,"Image":"","Volumes":null,"WorkingDir":"","Entrypoint":null,"OnBuild":null,"Labels":null},"os":"linux"}.gitattributes+9
README.md+29-8
build_info.json+7-7
code/tt_autoe2e/api.py+24-8
code/tt_autoe2e/host/geometry.py+88-24
code/tt_autoe2e/tests/dev_api.py+7-4
code/tt_autoe2e/tests/dev_cm_probe.pyAdded+135
code/tt_autoe2e/tests/dev_encoder.py+2-2
code/tt_autoe2e/tests/dev_eval.py+2-2
code/tt_autoe2e/tests/dev_frame_prof.pyAdded+102
code/tt_autoe2e/tests/dev_layer_ops.pyAdded+189
code/tt_autoe2e/tests/dev_msda_probe.py+16-2
code/tt_autoe2e/tests/dev_msda_riscs.pyAdded+102
code/tt_autoe2e/tests/dev_msda_unit.py+8-2
code/tt_autoe2e/tests/dev_prof.pyAdded+172
code/tt_autoe2e/tests/dev_runner.py+4-3
code/tt_autoe2e/tests/dev_step.py+2-2
code/tt_autoe2e/tests/dev_t8_prof.pyAdded+104
code/tt_autoe2e/tests/dev_t8_sweep.pyAdded+120
code/tt_autoe2e/tests/host_geometry.pyAdded+91
code/tt_autoe2e/tt/encoder.py+277-37
code/tt_autoe2e/tt/image.py+7-1
code/tt_autoe2e/tt/kernels/msda_cm_compute.cppAdded+360
code/tt_autoe2e/tt/kernels/msda_cm_reader.cppAdded+338
code/tt_autoe2e/tt/kernels/msda_k_compute.cpp+100-13
code/tt_autoe2e/tt/kernels/msda_k_reader.cpp+285-35
code/tt_autoe2e/tt/kernels/pairmap2_dm.cpp+43-13
code/tt_autoe2e/tt/msda_cm.pyAdded+125
code/tt_autoe2e/tt/msda_k.py+25-12
code/tt_autoe2e/tt/pairmap.py+6-3
code/tt_autoe2e/tt/runner.py+64-18
code/tt_autoe2e/tt/t8.py+39-8
image/blobs/sha256/0ee85adffdf6df32309b3e71402c5c982f7c6fd6e52c7a5143a979548cd172d0Added+1
image/blobs/sha256/0f4b5bb0adf19a18c065d16e0056ab8b28f2982602edbe333d5f45d51b47f3feAdded+1
image/blobs/sha256/188ff78ba17c8232a2f3aba4b35f5c7dbd5307be0d492e11ef26c958623660d3Added
image/blobs/sha256/1ae0d5f9058b59d711d64697b6fd66f7352eb6f99d0acabcaedc0756af0d5bc4Added+1
image/blobs/sha256/1c431ceec10d195155444a08b220938ba6cc6892d72cd0ca32e6e3dee371532aAdded+1
image/blobs/sha256/241d4a5b2a827d8e1238d9227a5ebde070af2a9a0b0918ec8cf3839c7691e3deAdded+3
image/blobs/sha256/2e540ce4b247929a60b17412f50ddc77ce0374487a916f7b85c4873cf2f6d17aAdded+1
image/blobs/sha256/30e958a3682167e11e043ef27b0bba08a720570a9a5a848b6afb9c97b1db44dbAdded+1
image/blobs/sha256/37ffd05da440e151828a5098fe24b8cc4eb2b747f1536dffccd223ccd5f5b4bdAdded+1
image/blobs/sha256/3ba05941cae059ea9b5b3f14cf8b93a664c9de02d175acda61f7c0c7446a5edbAdded+1
image/blobs/sha256/3eaf130059f3e4080f8dc71afcb2ed53310ee60187b4bca947458c563849a457Added+3
image/blobs/sha256/508946978b347a9317dcda6349a6e3a9468f6446dfc6ae299f2862ba38d300b3Added
image/blobs/sha256/50d4519dcf5bd619f82687a07c264641bb7731831868a3f16ba0736edf10f3e5Added+1
image/blobs/sha256/5b7a27d05e6bed4da52cefef7e59cb1f91ea8214a022a1e6e62ec6081f3df589Added
image/blobs/sha256/5d611147b10a84989047de9d9456d5e3e7ebdbae72b4d7042a1ecf0db2c5d4d8Added+1
image/blobs/sha256/6706e1ed57bf105dc9cd1e3eef974838bbc2d69aca3c7d5a31d8f6224337e6feAdded+3
image/blobs/sha256/6b1f63635e5e7cd962ea3f65b6036e86d4e838a24de9559a546834c1b49ed396Added+3
image/blobs/sha256/6b4c3d2493d54e0d53054e8fbeaa0ad99b0ab33907187485a62dd2b7b74e3a72Added+1