Rohit-R-Rao commited on
Commit
4b5ff89
·
0 Parent(s):
.gitattributes ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ media/023b7fcc.mp4 filter=lfs diff=lfs merge=lfs -text
37
+ media/02eadd92.mp4 filter=lfs diff=lfs merge=lfs -text
38
+ media/07981e6a.mp4 filter=lfs diff=lfs merge=lfs -text
39
+ media/6f34d20b.mp4 filter=lfs diff=lfs merge=lfs -text
40
+ media/6f3be572.mp4 filter=lfs diff=lfs merge=lfs -text
41
+ media/cdb709d1.mp4 filter=lfs diff=lfs merge=lfs -text
42
+ media/d7a656c2.mp4 filter=lfs diff=lfs merge=lfs -text
43
+ media/e39fb49b.mp4 filter=lfs diff=lfs merge=lfs -text
44
+ media/f41175b5.mp4 filter=lfs diff=lfs merge=lfs -text
45
+ media/fe0c2168.mp4 filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ OpenMDW License Agreement, version 1.1 (OpenMDW-1.1)
2
+
3
+ By exercising rights granted to you under this agreement, you accept and agree
4
+ to its terms.
5
+
6
+ As used in this agreement, "Model Materials" means the materials provided to
7
+ you under this agreement, consisting of: (1) one or more machine learning
8
+ models (including architecture and parameters); and (2) all related artifacts
9
+ (including associated data, documentation and software) that are provided to
10
+ you hereunder.
11
+
12
+ Subject to your compliance with this agreement, permission is hereby granted,
13
+ free of charge, to deal in the Model Materials without restriction, including
14
+ under all copyright, patent, database, and trade secret rights included or
15
+ embodied therein.
16
+
17
+ If you distribute any portion of the Model Materials, you shall retain in your
18
+ distribution (1) a copy of this agreement, and (2) all copyright notices and
19
+ other notices of origin included in the Model Materials that are applicable to
20
+ your distribution.
21
+
22
+ If you file, maintain, or voluntarily participate in a lawsuit against any
23
+ person or entity asserting that the Model Materials directly or indirectly
24
+ infringe any patent or copyright, then all rights and grants made to you
25
+ hereunder are terminated, unless that lawsuit was in response to a
26
+ corresponding lawsuit first brought against you.
27
+
28
+ This agreement does not impose any restrictions or obligations with respect to
29
+ any use, modification, or sharing of any outputs generated by using the Model
30
+ Materials.
31
+
32
+ THE MODEL MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
33
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
34
+ FITNESS FOR A PARTICULAR PURPOSE, TITLE, NONINFRINGEMENT, ACCURACY, OR THE
35
+ ABSENCE OF LATENT OR OTHER DEFECTS OR ERRORS, WHETHER OR NOT DISCOVERABLE, ALL
36
+ TO THE GREATEST EXTENT PERMISSIBLE UNDER APPLICABLE LAW.
37
+
38
+ YOU ARE SOLELY RESPONSIBLE FOR (1) CLEARING RIGHTS OF OTHER PERSONS THAT MAY
39
+ APPLY TO THE MODEL MATERIALS OR ANY USE THEREOF, INCLUDING WITHOUT LIMITATION
40
+ ANY PERSON'S COPYRIGHTS OR OTHER RIGHTS INCLUDED OR EMBODIED IN THE MODEL
41
+ MATERIALS; (2) OBTAINING ANY NECESSARY CONSENTS, PERMISSIONS OR OTHER RIGHTS
42
+ REQUIRED FOR ANY USE OF THE MODEL MATERIALS; OR (3) PERFORMING ANY DUE
43
+ DILIGENCE OR UNDERTAKING ANY OTHER INVESTIGATIONS INTO THE MODEL MATERIALS OR
44
+ ANYTHING INCORPORATED OR EMBODIED THEREIN.
45
+
46
+ IN NO EVENT SHALL THE PROVIDERS OF THE MODEL MATERIALS BE LIABLE FOR ANY CLAIM,
47
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
48
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MODEL MATERIALS, THE
49
+ USE THEREOF OR OTHER DEALINGS THEREIN.
NOTICE ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ alpamini
2
+ Copyright 2026 Rohit Rao
3
+
4
+ alpamini is a modification of NVIDIA Alpamayo 2 Edge (https://huggingface.co/nvidia/Alpamayo2-Edge,
5
+ source https://github.com/NVlabs/alpamayo2-edge), developed by NVIDIA as part of the Alpamayo Open Platform.
6
+ The Alpamayo 2 Edge model weights are released by NVIDIA under the OpenMDW License Agreement, version 1.1
7
+ (see LICENSE, retained unmodified as that agreement requires). Alpamayo 2 Edge source code is licensed by NVIDIA
8
+ under the Apache License 2.0.
9
+
10
+ Model Materials in this repository:
11
+ alpamini.safetensors tensors derived from Alpamayo 2 Edge by width pruning, per-camera resolution changes and
12
+ further training (vision tower, projector, action expert), plus newly trained slot
13
+ embeddings and slot LoRA adapters. Distributed under OpenMDW-1.1.
14
+ alpamini/ Python code written for alpamini (Apache-2.0); it calls the alpamayo2-edge package, which
15
+ is installed separately and not redistributed here.
16
+ The unchanged Alpamayo 2 Edge language model is not redistributed; alpamini.load() downloads it from
17
+ nvidia/Alpamayo2-Edge.
18
+
19
+ Training inputs were drawn from NVIDIA PhysicalAI-Autonomous-Vehicles. No dataset content (frames, poses, labels,
20
+ or caches derived from them) is included in this repository.
README.md ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: openmdw-1.1
3
+ base_model:
4
+ - nvidia/Alpamayo2-Edge
5
+ datasets:
6
+ - nvidia/PhysicalAI-Autonomous-Vehicles
7
+ pipeline_tag: robotics
8
+ language:
9
+ - en
10
+ tags:
11
+ - alpamayo
12
+ - autonomous-driving
13
+ - vision-language-action
14
+ - model-compression
15
+ - pytorch
16
+ ---
17
+
18
+ # alpamini
19
+
20
+ **NVIDIA Alpamayo 2 Edge at under a third of the FLOPs: ~93 ms per driving decision instead of 264–305 ms, with no
21
+ loss of accuracy.**
22
+
23
+ alpamini is a compressed [Alpamayo 2 Edge](https://huggingface.co/nvidia/Alpamayo2-Edge). It takes the same inputs
24
+ (6 cameras, 22 frames, ego history and a navigation instruction) and gives the same outputs (a 6.4 s trajectory and a
25
+ reasoning text), at 10.6 decisions per second on one RTX 5090. Full bf16 PyTorch: no quantization, no TensorRT.
26
+
27
+ **Code and setup:** [github.com/Rohit-R-Rao/alpamini](https://github.com/Rohit-R-Rao/alpamini)
28
+
29
+ <video src="https://huggingface.co/Rohit-R-Rao/alpamini/resolve/main/media/07981e6a.mp4" controls autoplay muted loop playsinline width="100%"></video>
30
+
31
+ *Closed loop in [AlpaSim](https://github.com/NVlabs/alpasim), bird's-eye view with each run's metrics. Left: Alpamayo 2 Edge. Right: alpamini. The camera view is cropped out of all videos: AlpaSim's scenes are reconstructions of real drives from NVIDIA's dataset, and its license doesn't allow redistributing that footage.*
32
+
33
+ ## At a glance
34
+
35
+ | per decision, RTX 5090, bf16 | Alpamayo 2 Edge | alpamini |
36
+ |---|---|---|
37
+ | end-to-end latency (CUDA graphs on both) | 264–305 ms | **92–94 ms** |
38
+ | speedup | 1.0× | **2.8–3.3×** |
39
+ | native with frame caching too | 159–207 ms | **1.7–2.3× faster than that** |
40
+ | decision rate | 3.3–3.8 Hz | **10.6–10.9 Hz** |
41
+ | compute | 23.3 TFLOP | **6.6 TFLOP (3.6× fewer)** |
42
+ | GT FDE, 132 held-out samples | 4.60 m | **4.28 m** |
43
+ | mean lateral error | 0.241 m | **0.208 m** |
44
+ | closed loop, 9 scenes (mean score) | 0.97 | **1.00** |
45
+ | peak GPU memory | 5.9 GiB | 5.6 GiB |
46
+
47
+ ## Quick start
48
+
49
+ Full setup steps (environment, PyTorch, flash-attn, Hugging Face access) are in the
50
+ [GitHub README](https://github.com/Rohit-R-Rao/alpamini#setup). In short:
51
+
52
+ ```bash
53
+ git clone https://github.com/Rohit-R-Rao/alpamini && cd alpamini
54
+ pip install -e ".[dataset]"
55
+ pip install flash-attn==2.8.3 --no-build-isolation
56
+ python -m alpamini.example # drives a PhysicalAI-AV clip at 10 Hz and prints per-decision latency
57
+ ```
58
+
59
+ ```python
60
+ import alpamini
61
+
62
+ model = alpamini.load() # downloads nvidia/Alpamayo2-Edge + this repo's weights
63
+ out = alpamini.predict(model, raw_sample) # raw_sample = alpamayo2_edge's input dict
64
+ out["xyz"] # (1, 64, 3) trajectory, 10 Hz for 6.4 s, ego frame at t0
65
+ out["cot_text"] # reasoning text
66
+ ```
67
+
68
+ Call `predict` once per decision, in time order, at 10 Hz: frames seen at earlier decisions are reused from a cache.
69
+
70
+ ## How it works
71
+
72
+ Two stages own 97% of native's compute: the vision tower and the language model's prefill over the image tokens it
73
+ produces. alpamini cuts both, and replaces token-by-token reasoning with a single pass.
74
+
75
+ | part | Alpamayo 2 Edge | alpamini |
76
+ |---|---|---|
77
+ | per-camera resolution | full for all 6 cameras | front tele full, front wide 75%, the other 4 cameras 50% |
78
+ | vision tower (27 blocks) | 16 heads, MLP 4,304 | width-pruned to 12 heads, MLP 3,200, + a rank-64 adapter per block, retrained |
79
+ | past-frame image tokens | all | 25% kept at random (original positions); front tele and newest frames all kept |
80
+ | reasoning decode | autoregressive, one token per step | **one-shot**: 40 learned slots in one bidirectional pass (slot-only LoRA, rank 128) |
81
+ | frame caching | | vision features of earlier frames reused; 6 of 22 frames are new per decision |
82
+ | language model | | unchanged (downloaded from `nvidia/Alpamayo2-Edge`, not redistributed) |
83
+ | action expert | | retrained (10 Euler steps, as native) |
84
+
85
+ | ms per stage, RTX 5090 | Alpamayo 2 Edge | alpamini |
86
+ |---|---|---|
87
+ | preprocessing | 40–42 | 10–13 |
88
+ | vision | 95 | 24–25 |
89
+ | LM prefill | 67 | 29–30 |
90
+ | reasoning decode | 25–76 (grows with length) | 5.5 (any length) |
91
+ | action expert | 20–22 | 17 |
92
+
93
+ Training distills native (reasoning tokens, KV states, flow-matching targets) and adds ground-truth flow matching
94
+ plus explicit lateral and longitudinal trajectory losses, on 8,000 PhysicalAI-AV samples.
95
+
96
+ ## Evaluation
97
+
98
+ **Open loop.** 132 held-out PhysicalAI-AV samples, 12 for each of 11 driving situations (stops, braking, turns, lane
99
+ changes, curves, cruise, …), 4 flow seeds each. Errors against the recorded future, in metres:
100
+
101
+ | | Alpamayo 2 Edge | alpamini |
102
+ |---|---|---|
103
+ | GT FDE (6.4 s) | 4.60 | **4.28** |
104
+ | lateral, 1 / 2 / 3 s | 0.019 / 0.073 / 0.150 | 0.019 / 0.069 / 0.142 |
105
+ | lateral, 6.4 s | 0.764 | **0.643** |
106
+ | lateral, mean over the horizon | 0.241 | **0.208** |
107
+
108
+ Native is teacher-forced on its own reasoning; alpamini runs its one-shot decode. At 1–3 s the differences are
109
+ within noise.
110
+
111
+ **Closed loop.** 10 AlpaSim scenes, one rollout each: 5 development scenes and 5 drawn at random from the public
112
+ evaluation set.
113
+
114
+ | scene | score, Alpamayo 2 Edge | score, alpamini | max lateral to GT, Alpamayo 2 Edge | max lateral to GT, alpamini |
115
+ |---|---|---|---|---|
116
+ | cdb709d1 | 0.76 | **1.00** | 2.89 m | 0.64 m |
117
+ | 6f3be572 | 1.00 | 1.00 | 0.21 m | 0.07 m |
118
+ | 6f34d20b | 1.00 | 1.00 | 3.59 m | 0.63 m |
119
+ | 02eadd92 | 1.00 | 1.00 | 2.36 m | 0.24 m |
120
+ | fe0c2168 | 1.00 | 1.00 | 3.50 m | 0.54 m |
121
+ | e39fb49b | 1.00 | 1.00 | 1.28 m | 0.57 m |
122
+ | 07981e6a | 1.00 | 1.00 | 0.28 m | 0.24 m |
123
+ | d7a656c2 | 1.00 | 1.00 | 0.95 m | 0.73 m |
124
+ | 023b7fcc | 1.00 | 1.00 | 0.44 m | 0.52 m |
125
+ | **mean** | 0.97 | **1.00** | 1.72 m | **0.46 m** |
126
+
127
+ The tenth scene, f41175b5, is not in the mean: its navigation command says *continue straight* for the whole scene,
128
+ while the recorded driver turns left. alpamini follows the command and is scored 0 for leaving the recorded corridor;
129
+ Alpamayo 2 Edge drifts left with the driver and scores 0.93.
130
+
131
+ <table>
132
+ <tr>
133
+ <td width="50%"><video src="https://huggingface.co/Rohit-R-Rao/alpamini/resolve/main/media/cdb709d1.mp4" controls muted loop playsinline width="100%"></video><br><b>cdb709d1</b>: Alpamayo 2 Edge stalls at 60% of the route with front and rear contacts; alpamini drives it through.</td>
134
+ <td width="50%"><video src="https://huggingface.co/Rohit-R-Rao/alpamini/resolve/main/media/6f34d20b.mp4" controls muted loop playsinline width="100%"></video><br><b>6f34d20b</b>: Alpamayo 2 Edge spends 8.5 s in the wrong lane, alpamini 0.3 s.</td>
135
+ </tr>
136
+ <tr>
137
+ <td width="50%"><video src="https://huggingface.co/Rohit-R-Rao/alpamini/resolve/main/media/6f3be572.mp4" controls muted loop playsinline width="100%"></video><br><b>6f3be572</b>: stop behind a lead car. Both stop cleanly.</td>
138
+ <td width="50%"><video src="https://huggingface.co/Rohit-R-Rao/alpamini/resolve/main/media/f41175b5.mp4" controls muted loop playsinline width="100%"></video><br><b>f41175b5</b>: the command says straight, the recorded driver turns left. alpamini goes straight.</td>
139
+ </tr>
140
+ </table>
141
+
142
+ All 10 side-by-side videos are in [`media/`](https://huggingface.co/Rohit-R-Rao/alpamini/tree/main/media).
143
+
144
+ ## Limitations
145
+
146
+ - Closed-loop evaluation covers 10 scenes with one seed each. That is evidence it works, not a safety validation.
147
+ - Not bit-identical to the eager path: frame caching and CUDA graphs change bf16 rounding. Trajectories move by at
148
+ most 0.03 m, and the reasoning text can change.
149
+ - The one-shot reasoning text can come out garbled; the trajectory doesn't depend on its exact wording.
150
+ - About 2.68 B parameters vs 2.65 B for native. The speedup comes from fewer tokens, a narrower vision tower and
151
+ one-shot decoding, not from a smaller model.
152
+ - Tuned on PhysicalAI-AV camera rigs; other rigs and resolutions are untested.
153
+ - Evaluated offline and in simulation only. Not for use in a vehicle on public roads.
154
+
155
+ ## Files
156
+
157
+ | file | contents |
158
+ |---|---|
159
+ | `alpamini.safetensors` | every tensor that differs from native: vision tower, projector, action expert, slot embeddings and slot LoRA |
160
+ | `alpamini.json` | weight metadata |
161
+ | `alpamini/` | the runtime package (also on GitHub) |
162
+ | `media/` | closed-loop side-by-side videos |
163
+
164
+ ## License
165
+
166
+ The weights are a modification of Alpamayo 2 Edge's Model Materials and are distributed under
167
+ [OpenMDW-1.1](https://openmdw.ai/license/1-1/) (`LICENSE`). The code (`alpamini/`) is Apache-2.0. See `NOTICE`.
168
+ This is independent work, not affiliated with or endorsed by NVIDIA.
alpamini.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "alpamini",
3
+ "version": "1.0.0",
4
+ "base_model": "nvidia/Alpamayo2-Edge",
5
+ "base_revision": "b92b6aa326bd3e2235db28f248ad5a30b5890e64",
6
+ "stack": "native LM + width-pruned vision tower/projector at per-camera resolution + retrained action expert + one-shot slot reasoning decode, past-frame thinning keep 0.25 (cameras [6] exempt), frame caching, CUDA graphs",
7
+ "camera_sides": {
8
+ "0": 0.5,
9
+ "1": 0.75,
10
+ "2": 0.5,
11
+ "3": 0.5,
12
+ "5": 0.5,
13
+ "6": 1.0
14
+ },
15
+ "keep_frac": 0.25,
16
+ "thin_exempt": [
17
+ 6
18
+ ],
19
+ "num_slots": 40,
20
+ "lora_alpha": 128.0,
21
+ "overwritten_from_alpamini_ckpt": {
22
+ "visual": 599,
23
+ "projector": 6,
24
+ "expert": 237,
25
+ "lora": 336,
26
+ "slots": 1
27
+ },
28
+ "sources": {
29
+ "nano4_s280": {
30
+ "model.safetensors": "056d42562d1baf6a854a5a243a5009733dfba454c6638aa93866a27a0964d103",
31
+ "buffers.safetensors": "7e9334d32395cb3833fa29dc19e0eb9d970d54e0c42f64d67c04b644abf75b83"
32
+ },
33
+ "alpamini_ckpt": "4ef44be6107b542c2d6991712fc432f1e007673e871167f0ec9118ad579051dd"
34
+ },
35
+ "weights_sha256": "3152f4268f75933a918a6010ccf10a5b5c94f0c9332d2b304f5374e80595ef41",
36
+ "n_tensors": 1188
37
+ }
alpamini.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3152f4268f75933a918a6010ccf10a5b5c94f0c9332d2b304f5374e80595ef41
3
+ size 1704203640
alpamini/__init__.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """alpamini: compressed Alpamayo2-Edge for low-latency driving (93 ms per decision on one GPU vs 264 ms native).
2
+
3
+ native LM (unchanged) + width-pruned vision tower / projector at per-camera resolution + retrained action expert
4
+ + one-shot reasoning decode (40 slots, one bidirectional pass, slot LoRA) + 25 % past-frame token thinning
5
+ (front tele exempt) + frame caching + torch.compile / CUDA graphs.
6
+
7
+ import alpamini
8
+ model = alpamini.load() # downloads nvidia/Alpamayo2-Edge + alpamini weights
9
+ out = alpamini.predict(model, raw_sample) # raw sample: see preprocess.py
10
+ out["xyz"] (S, 64, 3) out["rot"] (S, 64, 3, 3) out["cot_text"] (6.4 s at 10 Hz, ego frame at t0)
11
+
12
+ Call predict once per decision, in time order, at 10 Hz: frames seen at earlier decisions come from the caches.
13
+ Settings: config.py. Latency: bench.py.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import torch
18
+
19
+ from . import config
20
+ from .decode import sample
21
+ from .model import load
22
+ from .preprocess import GpuPreprocessor, frame_keys, prepare_inputs
23
+
24
+ __version__ = "1.0.0"
25
+ __all__ = ["clear_frame_cache", "config", "load", "predict", "prepare_inputs", "sample"]
26
+
27
+
28
+ def _preprocessor(model):
29
+ if getattr(model, "_alpamini_pre", None) is None:
30
+ model._alpamini_pre = GpuPreprocessor(model)
31
+ return model._alpamini_pre
32
+
33
+
34
+ def clear_frame_cache(model):
35
+ """Forget every cached frame (both caches). Not needed between clips (keys carry a content fingerprint)."""
36
+ model._fc_cache.clear()
37
+ _preprocessor(model).clear()
38
+
39
+
40
+ def predict(model, raw: dict, num_samples: int = 1, seed: int | None = None, device="cuda", timer=None) -> dict:
41
+ """One driving decision. Accelerated (CUDA graphs) when the model was loaded with accel and num_samples == 1,
42
+ else the eager path. timer(name): optional stage marks (bench.py)."""
43
+ fc = config.FRAME_CACHE
44
+ inputs = _preprocessor(model)(raw, cache=fc)
45
+ if timer:
46
+ timer("pre")
47
+ if seed is not None:
48
+ torch.manual_seed(seed)
49
+ torch.cuda.manual_seed_all(seed)
50
+ model._fc_keys = frame_keys(raw) if fc else None
51
+ acc = model._alpamini_accel
52
+ try:
53
+ with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
54
+ if acc is not None and num_samples == 1:
55
+ xyz, rot, text = acc.sample(inputs, timer=timer)
56
+ else:
57
+ xyz, rot, text = sample(model, inputs, num_samples)
58
+ finally:
59
+ model._fc_keys = None
60
+ return {"xyz": xyz[0, 0].float().cpu(), "rot": rot[0, 0].float().cpu(), "cot_text": text,
61
+ "frame_cache": {"preprocess": dict(_preprocessor(model).stats), "vision": dict(model._fc_stats)}}
alpamini/accel.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """decode.sample, compiled + CUDA-graphed (the 93 ms configuration; same computation as decode.py).
2
+
3
+ Uses alpamayo2_edge.accel (mode "tuned", the native model's acceleration), applied to the one-shot path:
4
+ prefill the thinned prompt through accel's compiled PrefillStep into its FlashKVCache, one CUDA graph per
5
+ KV_BUCKET-padded length
6
+ slots the ONE bidirectional slot pass (K slots, slot LoRA on), accel's decoder_block, compiled, one CUDA graph
7
+ expert accel's ExpertAccelerator: the whole Euler loop, one CUDA graph, over prompt + the first n slots
8
+ The vision tower runs eager (as for native). Random draws (thinning mask on the CPU RNG, expert noise on the CUDA
9
+ RNG) are the same as decode.sample's, so the two paths take the same seed; values differ only in bf16 kernel
10
+ rounding (flash attention vs SDPA). The first call of each new shape compiles and captures (~1 min).
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import torch
15
+
16
+ from . import config as C
17
+ from .model import SlotLoRA
18
+ from .thin import thinned
19
+
20
+
21
+ class Accelerated:
22
+ def __init__(self, model):
23
+ from alpamayo2_edge.accel import AccelConfig, enable_acceleration
24
+ from alpamayo2_edge.accel.decode import decoder_block
25
+ from alpamayo2_edge.accel.graphs import maybe_compile
26
+
27
+ self.model = model
28
+ self.handle = enable_acceleration(model, AccelConfig(mode="tuned", kv_bucket=C.KV_BUCKET))
29
+ if self.handle.skipped:
30
+ raise RuntimeError(f"acceleration unavailable: {self.handle.skipped} (needs flash-attn on a CUDA GPU)")
31
+ self.dec, self.exp = self.handle.accelerators
32
+ lm, head = model.vlm.model.language_model, model.vlm.lm_head
33
+
34
+ class SlotStep(torch.nn.Module):
35
+ """decode.sample's slot pass: K slot embeddings, bidirectional over prompt KV + slots, LM head."""
36
+
37
+ def __init__(self):
38
+ super().__init__()
39
+ self.text, self.lm_head = lm, head
40
+
41
+ def forward(self, hidden, positions, seqlens, k_caches, v_caches):
42
+ cos, sin = self.text.rotary_emb(hidden, positions)
43
+ for i, layer in enumerate(self.text.layers):
44
+ hidden = decoder_block(layer, hidden, cos, sin, k_caches[i], v_caches[i], seqlens, False)
45
+ return self.lm_head(self.text.norm(hidden))
46
+
47
+ self.compiled_slot = maybe_compile(SlotStep(), True, "default")
48
+ self.graphs: dict = {}
49
+ self.n_expert = model.expert.action_space.get_action_space_dims()[0]
50
+
51
+ def _graphed(self, name, key, fn, static):
52
+ from alpamayo2_edge.accel.graphs import GraphedCall
53
+
54
+ g = self.graphs.get((name, key))
55
+ if g is None:
56
+ g = GraphedCall(name, key, fn, static, stats=self.handle.stats, warmup=self.dec.warmup, cuda_graph=True,
57
+ device=torch.device("cuda"))
58
+ self.graphs[(name, key)] = g
59
+ return g
60
+
61
+ @torch.inference_mode()
62
+ def sample(self, inputs: dict, num_samples: int = 1, steps: int = C.DIFFUSION_STEPS, keep_frac: float = C.KEEP_FRAC,
63
+ timer=None):
64
+ """decode.sample, graphed. Call under bf16 autocast. timer(name) marks the end of a stage (optional)."""
65
+ from alpamayo2_edge.accel.graphs import bucket
66
+ from alpamayo2_edge.models.expert_utils import build_expert_pos_ids_and_attn_mask
67
+ from alpamayo2_edge.models.utils import fuse_traj_tokens
68
+
69
+ if num_samples != 1: # the graphed KV cache holds one row; decode.sample (eager) takes any num_samples
70
+ raise ValueError("accelerated decode draws 1 trajectory per call; use load(accel=False) for more")
71
+ model, vm, dec = self.model, self.model.vlm.model, self.dec
72
+ mark = timer or (lambda _name: None)
73
+ slots = model._oneshot_slots
74
+ K = slots.shape[0]
75
+ anchor = model.config.traj_ids["future_start"]
76
+ hx, hr = inputs["ego_history_xyz"], inputs["ego_history_rot"]
77
+ dev = hx.device
78
+ with thinned(model, inputs["tokenized_data"], keep_frac) as (td, _n_rm):
79
+ ids = fuse_traj_tokens(model.history_traj_tokenizer, model.future_traj_tokenizer, td["input_ids"],
80
+ {"ego_history_xyz": hx, "ego_history_rot": hr}, model.config.traj_ids)
81
+ mark("other")
82
+ # Cosmos3EdgeModel.forward's own steps (as accel's _graph_prefill); the decoder stack is graphed
83
+ embeds = vm.get_input_embeddings()(ids)
84
+ img = vm.get_image_features(td["pixel_values"], td["image_grid_thw"], return_dict=True)
85
+ mark("vision")
86
+ img = torch.cat(img.pooler_output, 0).to(embeds.dtype)
87
+ mask, _ = vm.get_placeholder_mask(ids, inputs_embeds=embeds, image_features=img)
88
+ embeds = embeds.masked_scatter(mask, img)
89
+ pos, rd = vm.get_rope_index(ids) # thinned: the kept tokens' original positions
90
+ lp = ids.shape[1]
91
+ cache = dec._cache(1, bucket(lp + K + self.n_expert, dec.kv_bucket))
92
+ padded = bucket(lp, dec.kv_bucket)
93
+ g = self._graphed("prefill", (cache.max_len, padded), dec.compiled_prefill,
94
+ (embeds.new_zeros(1, padded, embeds.shape[-1]),
95
+ torch.zeros(3, 1, padded, dtype=pos.dtype, device=dev), cache.k, cache.v))
96
+ h_in, p_in = g.args[:2]
97
+ h_in[:, :lp].copy_(embeds)
98
+ h_in[:, lp:].zero_()
99
+ p_in[:, :, :lp].copy_(pos[:, :1])
100
+ p_in[:, :, lp:].copy_(pos[:, :1, -1:])
101
+ g()
102
+ cache.start(lp, rd.reshape(-1))
103
+ mark("prefill")
104
+ # one-shot slot pass (slot LoRA on while compiling / capturing; replays need no Python state)
105
+ key = (cache.max_len,)
106
+ if ("slots", key) not in self.graphs:
107
+ SlotLoRA.active = True
108
+ try:
109
+ self._graphed("slots", key, self.compiled_slot,
110
+ (slots[None].clone(), torch.zeros(3, 1, K, dtype=torch.long, device=dev),
111
+ torch.zeros(1, dtype=torch.int32, device=dev), cache.k, cache.v))
112
+ finally:
113
+ SlotLoRA.active = False
114
+ g = self.graphs[("slots", key)]
115
+ g.args[1].copy_((lp + rd.view(1, 1, 1)) + torch.arange(K, device=dev).view(1, 1, K))
116
+ g.args[2].fill_(lp)
117
+ logits = g().float().masked_fill(model._oneshot_logit_mask, float("-inf"))
118
+ pred = logits[0].argmax(-1)
119
+ hit = (pred == anchor).nonzero()
120
+ n = int(hit[0, 0]) + 1 if hit.numel() else K
121
+ L = lp + n
122
+ mark("decode")
123
+ # action expert over prompt + the first n slots (accel's graphed Euler loop; noise from the CUDA RNG)
124
+ b = num_samples
125
+ pos_e, mask_e = build_expert_pos_ids_and_attn_mask(
126
+ offset=torch.full((b,), L, device=dev), rope_deltas=rd.view(1, -1).expand(b, -1), kv_cache_seq_len=L,
127
+ n_diffusion_tokens=self.n_expert, b_star=b, device=dev,
128
+ prefix_mask=torch.ones(b, L, dtype=torch.long, device=dev))
129
+ x = self.exp.sample_actions(cache, L, pos_e, mask_e, b, dev, {"inference_step": steps})
130
+ mark("expert")
131
+ xyz, rot = model.expert.action_space.action_to_traj(
132
+ x, hx[:, -1].expand(b, *hx.shape[2:]), hr[:, -1].expand(b, *hr.shape[2:]))
133
+ text = model.tokenizer.decode(pred[: n - 1 if hit.numel() else n].tolist(), skip_special_tokens=False)
134
+ mark("other")
135
+ return xyz[None, None], rot[None, None], text
alpamini/bench.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Per-decision latency of the shipped configuration (CUDA graphs + frame caching), per stage.
3
+
4
+ python -m alpamini.bench # one decision of a PhysicalAI-AV clip
5
+
6
+ Steady state at 10 Hz is emulated: before every timed call the 6 t0 frames are
7
+ evicted from both frame caches (they are new at every decision), the 16 past frames stay cached.
8
+ Per sample: WARMUP calls (compile + graph capture), then RUNS timed calls with per-stage syncs and RUNS plain calls
9
+ (end-to-end syncs only). Medians. Needs the PhysicalAI-AV access terms accepted on the Hub.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import statistics as st
14
+ import time
15
+
16
+ import torch
17
+
18
+ import alpamini
19
+
20
+ CLIP = ("ea7bbd31-b7a5-4972-8dbd-7089e6b53de4", 4_000_000, "Turn right in 30m") # upstream README's example clip
21
+ WARMUP = 3
22
+ RUNS = 10
23
+ SEED = 43
24
+ STAGES = ("pre", "vision", "prefill", "decode", "expert", "other")
25
+
26
+
27
+ def sync_time():
28
+ torch.cuda.synchronize()
29
+ return time.perf_counter()
30
+
31
+
32
+ class Timer:
33
+ def __init__(self):
34
+ self.t, self.ms = 0.0, {}
35
+
36
+ def start(self):
37
+ self.ms, self.t = {}, sync_time()
38
+
39
+ def __call__(self, name):
40
+ t = sync_time()
41
+ self.ms[name] = self.ms.get(name, 0.0) + 1e3 * (t - self.t)
42
+ self.t = t
43
+
44
+
45
+ def evict_t0(model, raw):
46
+ keys = alpamini.frame_keys(raw)
47
+ t0 = {max((k for k in keys if k[0] == c), key=lambda k: k[1]) for c in {k[0] for k in keys}}
48
+ for cache in (model._fc_cache, model._alpamini_pre.frames):
49
+ for k in [k for k in cache if k[:3] in t0]:
50
+ del cache[k]
51
+
52
+
53
+ def raw_samples():
54
+ from alpamayo2_edge.load_physical_aiavdataset import load_physical_aiavdataset
55
+
56
+ clip, t0, nav = CLIP
57
+ yield clip[:8], load_physical_aiavdataset(clip, t0_us=t0, nav_text=nav)
58
+
59
+
60
+ def main():
61
+ model = alpamini.load()
62
+ timer = Timer()
63
+ print(f"| sample | {' | '.join(s + ' ms' for s in STAGES)} | end-to-end ms | max Hz | CoT |")
64
+ print("|---|" + "---|" * (len(STAGES) + 3))
65
+ for name, raw in raw_samples():
66
+ alpamini.clear_frame_cache(model)
67
+ for _ in range(WARMUP):
68
+ alpamini.predict(model, raw, seed=SEED)
69
+ evict_t0(model, raw)
70
+ stage = {s: [] for s in STAGES}
71
+ e2e = []
72
+ for mode in ("timed", "plain"):
73
+ for _ in range(RUNS):
74
+ evict_t0(model, raw)
75
+ t0 = sync_time()
76
+ timer.start()
77
+ out = alpamini.predict(model, raw, seed=SEED, timer=timer if mode == "timed" else None)
78
+ t1 = sync_time()
79
+ if mode == "timed":
80
+ for s in STAGES:
81
+ stage[s].append(timer.ms.get(s, 0.0))
82
+ else:
83
+ e2e.append(1e3 * (t1 - t0))
84
+ assert out["frame_cache"]["vision"] == {"new": 6, "cached": 16}, out["frame_cache"]
85
+ m = st.median(e2e)
86
+ print(f"| {name} | " + " | ".join(f"{st.median(stage[s]):.1f}" for s in STAGES) +
87
+ f" | **{m:.1f}** | {1e3 / m:.1f} | {out['cot_text'][:40]!r} |", flush=True)
88
+ print(f"peak GPU memory {torch.cuda.max_memory_allocated() / 2**30:.1f} GiB, {torch.cuda.get_device_name()}")
89
+
90
+
91
+ if __name__ == "__main__":
92
+ main()
alpamini/config.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """alpamini settings (constants, as everywhere in alpamini)."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+
6
+ # ----------------------------------------------------------------------------- checkpoints
7
+ NATIVE_CHECKPOINT = "nvidia/Alpamayo2-Edge" # native LM, tokenizer, config (HF id or local dir); not stored here
8
+ NATIVE_REVISION = "b92b6aa326bd3e2235db28f248ad5a30b5890e64" # the native revision alpamini was trained / evaluated on
9
+ REPO_ID = "Rohit-R-Rao/alpamini" # this model on the Hugging Face Hub (weights file below)
10
+ WEIGHTS_FILE = "alpamini.safetensors" # every tensor that differs from native (vision, projector, expert, slots)
11
+ # local weights file or directory instead of the Hub (for development / offline use); None = download REPO_ID
12
+ WEIGHTS_PATH = os.environ.get("ALPAMINI_WEIGHTS")
13
+
14
+ # ----------------------------------------------------------------------------- model
15
+ # per-camera input resolution: camera c's (min, max) pixel budget x side^2 (camera ids: 0 cross left, 1 front wide,
16
+ # 2 cross right, 3 rear left, 5 rear right, 6 front tele)
17
+ CAMERA_SIDES = {0: 0.5, 1: 0.75, 2: 0.5, 3: 0.5, 5: 0.5, 6: 1.0}
18
+ KEEP_FRAC = 0.25 # past-frame LM image tokens kept (random, original RoPE positions)
19
+ THIN_EXEMPT = (6,) # front telephoto: never thinned
20
+ NUM_SLOTS = 40 # one-shot reasoning slots (one bidirectional pass)
21
+ LORA_ALPHA = 128.0 # slot LoRA (rank 128), active on the slots only
22
+ DIFFUSION_STEPS = 10 # Euler steps of the action expert
23
+
24
+ # ----------------------------------------------------------------------------- runtime (the 93 ms configuration)
25
+ ACCEL = True # torch.compile + CUDA graphs: prefill, one-shot slot pass, expert loop (needs flash-attn)
26
+ FRAME_CACHE = True # reuse per-frame preprocessing + vision-tower outputs of frames seen at earlier decisions
27
+ # frames kept per cache: at 10 Hz every input frame is an earlier decision's t0 frame up to 2 s back
28
+ # (20 decisions x 6 cameras = 120) plus the current 6
29
+ FRAME_CACHE_MAX = 160
30
+ KV_BUCKET = 256 # prefill length padded to a multiple of this (one CUDA graph per bucket)
alpamini/decode.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One-shot reasoning decode + action expert, eager (accel.py is the same computation compiled + CUDA-graphed).
2
+
3
+ thinned prompt prefill (slot LoRA off) -> ONE bidirectional pass over the 40 slots (slot LoRA on)
4
+ -> n = first slot whose argmax is <traj_future_start> (+1) -> the expert reads prompt KV + the first n slot KV
5
+ -> 10 Euler steps of flow matching -> trajectory.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import torch
10
+ from transformers import DynamicCache
11
+
12
+ from . import config as C
13
+ from .model import SlotLoRA
14
+ from .thin import thinned
15
+
16
+
17
+ def _expert_velocity(model, kv, x, t, prefix_len, rope_deltas):
18
+ from alpamayo2_edge.models.expert_utils import build_expert_pos_ids_and_attn_mask
19
+
20
+ b = x.shape[0]
21
+ n_tok = model.expert.action_space.get_action_space_dims()[0]
22
+ cache = DynamicCache(ddp_cache_data=[(k.expand(b, -1, -1, -1), v.expand(b, -1, -1, -1)) for k, v in kv])
23
+ pos, mask = build_expert_pos_ids_and_attn_mask(
24
+ offset=torch.full((b,), prefix_len, device=x.device), rope_deltas=rope_deltas.expand(b, -1),
25
+ kv_cache_seq_len=prefix_len, n_diffusion_tokens=n_tok, b_star=b, device=x.device,
26
+ prefix_mask=torch.ones(b, prefix_len, dtype=torch.long, device=x.device))
27
+ ex = model.expert
28
+ emb = ex.action_in_proj(x, t).reshape(b, n_tok, -1)
29
+ hs = ex.expert(inputs_embeds=emb, position_ids=pos, past_key_values=cache, attention_mask=mask,
30
+ use_cache=True, is_causal=False).last_hidden_state
31
+ return ex.action_out_proj(hs).reshape(b, *ex.action_space.get_action_space_dims())
32
+
33
+
34
+ @torch.inference_mode()
35
+ def sample(model, inputs: dict, num_samples: int = 1, steps: int = C.DIFFUSION_STEPS, keep_frac: float = C.KEEP_FRAC):
36
+ """Call under bf16 autocast. Returns xyz (1, 1, S, T, 3), rot (1, 1, S, T, 3, 3), reasoning text."""
37
+ from alpamayo2_edge.models.utils import fuse_traj_tokens
38
+
39
+ vm, lm = model.vlm.model, model.vlm.model.language_model
40
+ dev = inputs["ego_history_xyz"].device
41
+ slots = model._oneshot_slots
42
+ K = slots.shape[0]
43
+ anchor = model.config.traj_ids["future_start"]
44
+ hx, hr = inputs["ego_history_xyz"], inputs["ego_history_rot"]
45
+ with thinned(model, inputs["tokenized_data"], keep_frac) as (td, _n_rm):
46
+ ids = fuse_traj_tokens(model.history_traj_tokenizer, model.future_traj_tokenizer, td["input_ids"],
47
+ {"ego_history_xyz": hx, "ego_history_rot": hr}, model.config.traj_ids)
48
+ SlotLoRA.active = False
49
+ cache = DynamicCache()
50
+ vm(input_ids=ids, attention_mask=torch.ones_like(ids), pixel_values=td["pixel_values"],
51
+ image_grid_thw=td["image_grid_thw"], mm_token_type_ids=td["mm_token_type_ids"],
52
+ past_key_values=cache, use_cache=True)
53
+ rd = vm.rope_deltas
54
+ lp = ids.shape[1]
55
+ # first CoT position (all 3 RoPE axes equal for text) = kept length + rope_deltas = full prompt length + deltas
56
+ slot_pos = ((lp + rd.view(1, 1, 1)) + torch.arange(K, device=dev).view(1, 1, K)).expand(3, 1, K)
57
+ SlotLoRA.active = True
58
+ try:
59
+ out = lm(inputs_embeds=slots[None], position_ids=slot_pos, past_key_values=cache, use_cache=True,
60
+ attention_mask=torch.ones(1, 1, K, lp + K, dtype=torch.bool, device=dev))
61
+ finally:
62
+ SlotLoRA.active = False
63
+ logits = model.vlm.lm_head(out.last_hidden_state[0]).float().masked_fill(model._oneshot_logit_mask, float("-inf"))
64
+ pred = logits.argmax(-1)
65
+ hit = (pred == anchor).nonzero()
66
+ n = int(hit[0, 0]) + 1 if hit.numel() else K
67
+ L = lp + n
68
+ kv = [(layer.keys[..., :L, :], layer.values[..., :L, :]) for layer in cache.layers]
69
+ dims = model.expert.action_space.get_action_space_dims()
70
+ x = torch.randn(num_samples, *dims, device=dev)
71
+ ts = torch.linspace(0.0, 1.0, steps + 1, device=dev)
72
+ for i in range(steps):
73
+ x = x + (ts[i + 1] - ts[i]) * _expert_velocity(
74
+ model, kv, x, ts[i].view(1, 1, 1).expand(num_samples, 1, 1), L, rd).float()
75
+ xyz, rot = model.expert.action_space.action_to_traj(
76
+ x, hx[:, -1].expand(num_samples, *hx.shape[2:]), hr[:, -1].expand(num_samples, *hr.shape[2:]))
77
+ text = model.tokenizer.decode(pred[: n - 1 if hit.numel() else n].tolist(), skip_special_tokens=False)
78
+ return xyz[None, None], rot[None, None], text
alpamini/example.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Out-of-box test: drive alpamini through a real PhysicalAI-AV clip at 10 Hz, as a car would call it.
3
+
4
+ python -m alpamini.example
5
+
6
+ Needs the dataset extra (`pip install "alpamayo2-edge[dataset]"`) and the PhysicalAI-Autonomous-Vehicles access
7
+ terms accepted on the Hugging Face Hub (frames are streamed from the Hub; nothing of the dataset ships with alpamini).
8
+ Every 100 ms of clip time: load the 22 camera frames + ego history at t0, predict, print the decision's latency
9
+ (dataset loading excluded), frame-cache hits and reasoning. The first decisions compile + capture CUDA graphs and
10
+ fill the caches; the summary is over the steady state (every input frame already seen, 6 new per decision).
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import statistics as st
15
+ import time
16
+
17
+ import torch
18
+
19
+ import alpamini
20
+
21
+ CLIP = "ea7bbd31-b7a5-4972-8dbd-7089e6b53de4" # the upstream Alpamayo 2 Edge README's example clip
22
+ NAV_TEXT = "Turn right in 30m"
23
+ T0_START_US = 4_000_000
24
+ DECISIONS = 40 # 4 s of driving at 10 Hz
25
+ STEADY_AFTER = 21 # by then every input frame (up to 2 s back) was a t0 frame before
26
+ SEED = 43
27
+
28
+
29
+ def main():
30
+ import physical_ai_av
31
+ from alpamayo2_edge.load_physical_aiavdataset import load_physical_aiavdataset
32
+
33
+ avdi = physical_ai_av.PhysicalAIAVDatasetInterface()
34
+ model = alpamini.load()
35
+ steady = []
36
+ for i in range(DECISIONS):
37
+ t0 = T0_START_US + 100_000 * i
38
+ raw = load_physical_aiavdataset(CLIP, t0_us=t0, nav_text=NAV_TEXT, avdi=avdi)
39
+ torch.cuda.synchronize()
40
+ start = time.perf_counter()
41
+ out = alpamini.predict(model, raw, seed=SEED)
42
+ torch.cuda.synchronize()
43
+ ms = 1e3 * (time.perf_counter() - start)
44
+ if i >= STEADY_AFTER:
45
+ steady.append(ms)
46
+ end = out["xyz"][0, -1]
47
+ print(f"t0 {t0 / 1e6:5.1f} s {ms:7.1f} ms vision frames new/cached "
48
+ f"{out['frame_cache']['vision']['new']:2d}/{out['frame_cache']['vision']['cached']:2d} "
49
+ f"6.4 s endpoint ({end[0]:6.1f}, {end[1]:5.1f}) m {out['cot_text'].strip()[:60]!r}", flush=True)
50
+ m = st.median(steady)
51
+ print(f"\nsteady state ({len(steady)} decisions): median {m:.1f} ms = {1e3 / m:.1f} Hz on {torch.cuda.get_device_name()}")
52
+
53
+
54
+ if __name__ == "__main__":
55
+ main()
alpamini/frame_cache.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frame caching: each frame's vision-tower + projector output is stored under (frame_keys = camera, capture timestamp,
2
+ content fingerprint; + grid);
3
+ at the next decision only frames not seen before go through the tower (at 10 Hz: the 6 new t0 frames of 22).
4
+
5
+ The tower attends within each frame, so a cached frame's features are the same computation; the values can differ
6
+ in the last bf16 bit from a full 22-frame batch (different kernel shapes), max |diff| 0.03-0.06.
7
+ predict() sets model._fc_keys (prompt order) before the forward; None = no caching.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from collections import OrderedDict
12
+
13
+ import torch
14
+ from transformers.modeling_outputs import BaseModelOutputWithPooling
15
+
16
+ from .config import FRAME_CACHE_MAX
17
+
18
+
19
+ def install(model):
20
+ vm = model.vlm.model
21
+ orig = vm.get_image_features # bound class method
22
+ cache: OrderedDict = OrderedDict()
23
+ model._fc_cache, model._fc_keys, model._fc_stats = cache, None, {"new": 0, "cached": 0}
24
+
25
+ def get_image_features(pixel_values, image_grid_thw=None, **kw):
26
+ keys = model._fc_keys
27
+ if keys is None:
28
+ return orig(pixel_values, image_grid_thw, **kw)
29
+ grid = image_grid_thw.tolist()
30
+ assert len(keys) == len(grid), (len(keys), len(grid))
31
+ keys = [(*k, *g) for k, g in zip(keys, grid)]
32
+ rows = image_grid_thw.prod(-1).tolist()
33
+ starts = [0]
34
+ for r in rows:
35
+ starts.append(starts[-1] + r)
36
+ miss = [i for i, k in enumerate(keys) if k not in cache]
37
+ if miss:
38
+ out = orig(torch.cat([pixel_values[starts[i]:starts[i + 1]] for i in miss]), image_grid_thw[miss], **kw)
39
+ for i, feat in zip(miss, out.pooler_output):
40
+ cache[keys[i]] = feat
41
+ else:
42
+ out = BaseModelOutputWithPooling()
43
+ for k in keys:
44
+ cache.move_to_end(k)
45
+ while len(cache) > FRAME_CACHE_MAX:
46
+ cache.popitem(last=False)
47
+ model._fc_stats = {"new": len(miss), "cached": len(keys) - len(miss)}
48
+ out.pooler_output = tuple(cache[k] for k in keys)
49
+ return out
50
+
51
+ vm.get_image_features = get_image_features
52
+
53
+
54
+ def clear(model):
55
+ model._fc_cache.clear()
alpamini/model.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build alpamini on top of the native Alpamayo2-Edge checkpoint.
2
+
3
+ native Alpamayo2-Edge (LM, tokenizer, embeddings, lm_head: unchanged, loaded from the Hub)
4
+ + alpamini vision tower + projector (width-pruned: 12 heads, MLP 3200; rank-64 parallel adapter per block)
5
+ + alpamini action expert
6
+ + slot LoRA (rank 128) on every LM linear, ACTIVE ONLY during the one-shot slot pass, + 40 slot embeddings
7
+ + frame cache on the vision tower (frame_cache.py) + torch.compile / CUDA graphs (accel.py)
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import os
12
+
13
+ import torch
14
+ import torch.nn.functional as F
15
+ from safetensors import safe_open
16
+ from torch import nn
17
+
18
+ from . import config as C
19
+
20
+ LM_LINEARS = ("self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.o_proj", "mlp.fc1", "mlp.fc2")
21
+ DTYPE = torch.bfloat16
22
+
23
+
24
+ class VisionBlockAdapter(nn.Module):
25
+ """up(gelu_tanh(down(LayerNorm(x)))) on a vision block's input x, added to the block output"""
26
+
27
+ def __init__(self, dim: int, rank: int, eps: float = 1e-6, device=None, dtype=None):
28
+ super().__init__()
29
+ kw = {"device": device, "dtype": dtype}
30
+ self.adapter_norm = nn.LayerNorm(dim, eps=eps, **kw)
31
+ self.adapter_down = nn.Linear(dim, rank, **kw)
32
+ self.adapter_up = nn.Linear(rank, dim, **kw)
33
+ self.active = True
34
+
35
+ def forward(self, x):
36
+ return self.adapter_up(F.gelu(self.adapter_down(self.adapter_norm(x)), approximate="tanh"))
37
+
38
+
39
+ def adapter_hook(module, args, out):
40
+ a = module.adapter
41
+ return out + a(args[0]).to(out.dtype) if a.active else out
42
+
43
+
44
+ class SlotLoRA(nn.Module):
45
+ """y = base(x) + scale * B A x while SlotLoRA.active (the reasoning-slot pass only)."""
46
+ active = False
47
+
48
+ def __init__(self, base: nn.Linear, A: torch.Tensor, B: torch.Tensor, alpha: float):
49
+ super().__init__()
50
+ self.base = base
51
+ self.register_buffer("A", A.to(base.weight.device, DTYPE))
52
+ self.register_buffer("B", B.to(base.weight.device, DTYPE))
53
+ self.scale = alpha / A.shape[0]
54
+
55
+ def forward(self, x):
56
+ y = self.base(x)
57
+ if SlotLoRA.active:
58
+ y = y + (F.linear(F.linear(x, self.A.to(x.dtype)), self.B.to(x.dtype)) * self.scale).to(y.dtype)
59
+ return y
60
+
61
+
62
+ def _set(root, name, module):
63
+ parent, _, attr = name.rpartition(".")
64
+ setattr(root.get_submodule(parent) if parent else root, attr, module)
65
+
66
+
67
+ def _install_vision(model, f, device):
68
+ """Make the native vision tower match the stored (pruned + adapter) tensors, then load them strictly."""
69
+ vis, proj = model.vlm.model.visual, model.vlm.model.projector
70
+ pre_v, pre_p = "vlm.model.visual.", "vlm.model.projector."
71
+ shapes = {k[len(pre_v):]: tuple(f.get_slice(k).get_shape()) for k in f.keys() if k.startswith(pre_v)}
72
+ for name, mod in list(vis.named_modules()):
73
+ if not isinstance(mod, nn.Linear):
74
+ continue
75
+ w = shapes[f"{name}.weight"]
76
+ has_bias = f"{name}.bias" in shapes
77
+ if tuple(mod.weight.shape) == w and (mod.bias is not None) == has_bias:
78
+ continue
79
+ _set(vis, name, nn.Linear(w[1], w[0], bias=has_bias, device=device, dtype=DTYPE))
80
+ if name.endswith(".q_proj"): # vision attention heads follow q_proj
81
+ att = vis.get_submodule(name.rpartition(".")[0])
82
+ att.num_heads = w[0] // att.head_dim
83
+ for i, layer in enumerate(vis.encoder.layers):
84
+ key = f"encoder.layers.{i}.adapter.adapter_down.weight"
85
+ if key in shapes:
86
+ rank, dim = shapes[key]
87
+ layer.adapter = VisionBlockAdapter(dim, rank, device=device, dtype=DTYPE)
88
+ layer.register_forward_hook(adapter_hook)
89
+ vis.load_state_dict({k: f.get_tensor(pre_v + k) for k in shapes}, strict=True)
90
+ proj.load_state_dict({k[len(pre_p):]: f.get_tensor(k) for k in f.keys() if k.startswith(pre_p)}, strict=True)
91
+
92
+
93
+ def _install_expert(model, f, device):
94
+ ex = model.expert
95
+ params, bufs = dict(ex.named_parameters()), dict(ex.named_buffers())
96
+ p_keys = {k[len("expert."):] for k in f.keys() if k.startswith("expert.")}
97
+ b_keys = {k[len("buffer.expert."):] for k in f.keys() if k.startswith("buffer.expert.")}
98
+ assert p_keys == set(params), (sorted(set(params) ^ p_keys)[:5])
99
+ assert b_keys == set(bufs), (sorted(set(bufs) ^ b_keys)[:5])
100
+ with torch.no_grad():
101
+ for k, p in params.items():
102
+ p.copy_(f.get_tensor("expert." + k).to(p.device, p.dtype))
103
+ for k in b_keys: # bit-identical to the evaluated expert
104
+ mod_name, _, attr = k.rpartition(".")
105
+ ex.get_submodule(mod_name)._buffers[attr] = f.get_tensor("buffer.expert." + k).to(device)
106
+
107
+
108
+ def _install_slots(model, f, device):
109
+ lm = model.vlm.model.language_model
110
+ for li, layer in enumerate(lm.layers):
111
+ for path in LM_LINEARS:
112
+ parent_name, leaf = path.rsplit(".", 1)
113
+ parent = layer.get_submodule(parent_name)
114
+ setattr(parent, leaf, SlotLoRA(getattr(parent, leaf), f.get_tensor(f"lora.{li}.{path}.A"),
115
+ f.get_tensor(f"lora.{li}.{path}.B"), C.LORA_ALPHA))
116
+ model._oneshot_slots = f.get_tensor("slots").to(device, DTYPE)
117
+ cfg, ids = model.config, model.config.traj_ids
118
+ mask = torch.zeros(model.vlm.lm_head.out_features, dtype=torch.bool, device=device)
119
+ mask[ids["history_id0"]: ids["history_id0"] + cfg.history_vocab_size] = True
120
+ mask[ids["future_id0"]: ids["future_id0"] + cfg.future_vocab_size] = True
121
+ eos = model.vlm.generation_config.eos_token_id
122
+ eos = [eos] if isinstance(eos, int) else list(eos or [])
123
+ mask[[e for e in eos if e != ids["future_start"]]] = True
124
+ model._oneshot_logit_mask = mask
125
+
126
+
127
+ def resolve_weights(weights=None) -> str:
128
+ """Local file / dir holding WEIGHTS_FILE, the file next to the package (Hub repo clone), else the Hub (REPO_ID)."""
129
+ w = weights or C.WEIGHTS_PATH
130
+ beside = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), C.WEIGHTS_FILE)
131
+ if w is None and os.path.isfile(beside): # a clone of the Hub repo (pip install -e .)
132
+ return beside
133
+ if w is None:
134
+ from huggingface_hub import hf_hub_download
135
+
136
+ return hf_hub_download(C.REPO_ID, C.WEIGHTS_FILE)
137
+ w = os.path.expanduser(str(w))
138
+ return os.path.join(w, C.WEIGHTS_FILE) if os.path.isdir(w) else w
139
+
140
+
141
+ def load(device: str = "cuda", native_checkpoint: str = C.NATIVE_CHECKPOINT, weights=None, accel: bool = C.ACCEL):
142
+ """alpamini in bf16 on `device`, eval mode. accel: compile + CUDA-graph the decode (first calls capture)."""
143
+ from alpamayo2_edge.checkpoint import load_model
144
+ from huggingface_hub import constants as hf_constants
145
+
146
+ from .frame_cache import install as install_frame_cache
147
+
148
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
149
+ local = os.path.isdir(os.path.expanduser(str(native_checkpoint)))
150
+ kw = {} if local else {"revision": C.NATIVE_REVISION}
151
+ model, _ = load_model(native_checkpoint, local_files_only=local or hf_constants.HF_HUB_OFFLINE, device=device,
152
+ dtype="bfloat16", attn_implementation="sdpa", **kw)
153
+ weights = resolve_weights(weights)
154
+ with safe_open(str(weights), framework="pt", device="cpu") as f:
155
+ n_used = len(list(f.keys()))
156
+ _install_vision(model, f, device)
157
+ _install_expert(model, f, device)
158
+ _install_slots(model, f, device)
159
+ model.requires_grad_(False)
160
+ model.eval()
161
+ model._thin_exempt = tuple(C.THIN_EXEMPT)
162
+ model.alpamini = {"weights": str(weights), "n_tensors": n_used}
163
+ install_frame_cache(model) # inactive unless predict() passes frame keys (config.FRAME_CACHE)
164
+ torch.cuda.empty_cache()
165
+ model._alpamini_accel = None
166
+ if accel:
167
+ from .accel import Accelerated
168
+
169
+ model._alpamini_accel = Accelerated(model)
170
+ return model
alpamini/preprocess.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Raw sample -> model inputs at alpamini's per-camera resolution.
2
+
3
+ Raw sample = the dict alpamayo2_edge expects: image_frames (22, 1, 3, H, W) uint8, camera_indices (22,),
4
+ absolute_timestamps (22,) us, ego_history_xyz (1, 20, 3), ego_history_rot (1, 20, 3, 3), nav_text [str].
5
+ Frames: cameras 1 and 6 at t0 - 2.0 / 1.0 / 0.5 / 0.1 / 0 s, cameras 0, 2, 3, 5 at t0 - 1.0 / 0.1 / 0 s.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from collections import OrderedDict
10
+
11
+ import torch
12
+
13
+ from .config import CAMERA_SIDES, FRAME_CACHE_MAX
14
+
15
+ GPU_RESIZE = True # per-frame bicubic resize on the GPU (as in the sim runs); False = CPU path used in training
16
+ _PROCESSORS: dict = {}
17
+
18
+
19
+ def _install_processor_cache():
20
+ from alpamayo2_edge import helper
21
+
22
+ if getattr(helper.get_processor, "_cached", False):
23
+ return
24
+ orig = helper.get_processor
25
+
26
+ def cached(tokenizer, model_config):
27
+ if id(tokenizer) not in _PROCESSORS:
28
+ _PROCESSORS[id(tokenizer)] = orig(tokenizer, model_config)
29
+ return _PROCESSORS[id(tokenizer)]
30
+
31
+ cached._cached = True
32
+ helper.get_processor = cached
33
+
34
+
35
+ def pixel_bounds(bounds: dict | None = None) -> dict[int, tuple[int, int]]:
36
+ from alpamayo2_edge.sample import CAMERA_PIXEL_BOUNDS
37
+
38
+ base = {int(c): tuple(v) for c, v in (bounds or CAMERA_PIXEL_BOUNDS).items()}
39
+ return {c: (int(lo * CAMERA_SIDES.get(c, 1.0) ** 2), int(hi * CAMERA_SIDES.get(c, 1.0) ** 2))
40
+ for c, (lo, hi) in base.items()}
41
+
42
+
43
+ def frame_keys(raw: dict) -> list[tuple[int, int, int]]:
44
+ """(camera, capture timestamp, content fingerprint) per image in prompt order (upstream sorts by camera, then
45
+ timestamp). The fingerprint (sum of a sparse pixel grid) keeps two clips with equal timestamps apart."""
46
+ from alpamayo2_edge.sample import canonical_frame_order
47
+
48
+ order = canonical_frame_order(raw["camera_indices"], raw["absolute_timestamps"])
49
+ fr = raw["image_frames"]
50
+ return [(int(raw["camera_indices"][i]), int(raw["absolute_timestamps"][i]),
51
+ int(fr[i, ..., ::37, ::41].sum())) for i in order.tolist()]
52
+
53
+
54
+ def prepare_inputs(model, raw: dict, device="cuda") -> dict:
55
+ from alpamayo2_edge import helper
56
+
57
+ _install_processor_cache()
58
+ data = dict(raw)
59
+ data["camera_pixel_bounds"] = pixel_bounds(raw.get("camera_pixel_bounds"))
60
+ orig_resize = helper.resize
61
+ if GPU_RESIZE and torch.device(device).type == "cuda":
62
+ helper.resize = lambda frame, size, interpolation: orig_resize(
63
+ frame.to(device, non_blocking=True), size, interpolation=interpolation).cpu()
64
+ try:
65
+ p = helper.prepare_model_inputs(data, model.config, model.tokenizer)
66
+ finally:
67
+ helper.resize = orig_resize
68
+ td = {k: v.contiguous() for k, v in p["tokenized_data"].items()}
69
+ td["pixel_values"] = td["pixel_values"].to(torch.bfloat16)
70
+ return {"tokenized_data": {k: v.to(device) for k, v in td.items()},
71
+ "ego_history_xyz": p["ego_history_xyz"].to(device),
72
+ "ego_history_rot": p["ego_history_rot"].to(device)}
73
+
74
+
75
+ class GpuPreprocessor:
76
+ """prepare_inputs with every pixel op on the GPU, cached prompt tokens and a per-frame cache of preprocessed
77
+ patches (same math: GPU bicubic resize, the processor's patchify, float32 normalize, bf16 cast, equal to
78
+ prepare_inputs). Frames are cached under (frame_keys, target size), LRU,
79
+ FRAME_CACHE_MAX entries; at 10 Hz only the 6 new t0 frames of 22 are preprocessed per decision."""
80
+
81
+ def __init__(self, model, device="cuda"):
82
+ from alpamayo2_edge import helper
83
+
84
+ _install_processor_cache()
85
+ ip = helper.get_processor(model.tokenizer, model.config).image_processor
86
+ self.model, self.device = model, torch.device(device)
87
+ self.p, self.m, self.c, self.tp = ip.patch_size, ip.merge_size, len(ip.image_mean), ip.temporal_patch_size
88
+ scale = 1.0 / ip.rescale_factor
89
+ self.mean = (torch.tensor(ip.image_mean, dtype=torch.float32) * scale).to(self.device).reshape(1, 1, -1, 1)
90
+ self.std = (torch.tensor(ip.image_std, dtype=torch.float32) * scale).to(self.device).reshape(1, 1, -1, 1)
91
+ self.templates: dict = {}
92
+ self.frames: OrderedDict = OrderedDict()
93
+ self.stats = {"new": 0, "cached": 0}
94
+
95
+ def clear(self):
96
+ self.frames.clear()
97
+
98
+ def _template(self, raw, order):
99
+ from alpamayo2_edge.chat_template import relative_time_labels
100
+
101
+ # the prompt only sees capture times as 0.1 s labels (<t=-0.1s>), so key on those: real camera timestamps
102
+ # jitter by a few ms and would miss the cache at every decision
103
+ key = (tuple(raw["nav_text"]), tuple(raw["camera_indices"][order].tolist()),
104
+ tuple(relative_time_labels(raw["absolute_timestamps"][order])), tuple(raw["image_frames"].shape[-2:]))
105
+ if key not in self.templates: # once per prompt layout: the reference path (tokens identical by construction)
106
+ td = prepare_inputs(self.model, raw, self.device)["tokenized_data"]
107
+ g = td["image_grid_thw"].cpu()
108
+ if len(self.templates) > 16:
109
+ self.templates.clear()
110
+ self.templates[key] = ({k: v for k, v in td.items() if k != "pixel_values"},
111
+ [(int(h) * self.p, int(w) * self.p) for _, h, w in g.tolist()])
112
+ return self.templates[key]
113
+
114
+ def _patches(self, x):
115
+ """(B, 3, H, W) uint8 -> list of (H/p * W/p, p*p*C*tp) normalized bf16, the processor's layout."""
116
+ b, c, h, w = x.shape
117
+ p, m = self.p, self.m
118
+ gh, gw = h // p, w // p
119
+ x = x.reshape(b, c, gh // m, m, p, gw // m, m, p).permute(0, 2, 5, 3, 6, 4, 7, 1)
120
+ x = x.unsqueeze(-1).expand(*x.shape, self.tp).reshape(b, gh * gw, p * p, c, self.tp).float()
121
+ x = (x - self.mean) / self.std
122
+ return list(x.reshape(b, gh * gw, -1).to(torch.bfloat16).unbind(0))
123
+
124
+ def __call__(self, raw, cache: bool = True):
125
+ from alpamayo2_edge.sample import canonical_frame_order
126
+ from torchvision.transforms.functional import InterpolationMode, resize
127
+
128
+ order = canonical_frame_order(raw["camera_indices"], raw["absolute_timestamps"])
129
+ td, sizes = self._template(raw, order)
130
+ keys = [(*k, *sizes[j]) for j, k in enumerate(frame_keys(raw))]
131
+ out = [self.frames.get(k) if cache else None for k in keys]
132
+ todo = [j for j, o in enumerate(out) if o is None]
133
+ by_size: dict = {}
134
+ for j in todo:
135
+ by_size.setdefault(sizes[j], []).append(j)
136
+ for (h, w), js in by_size.items():
137
+ fr = raw["image_frames"][[int(order[j]) for j in js]].reshape(len(js), 3, *raw["image_frames"].shape[-2:])
138
+ x = resize(fr.to(self.device, non_blocking=True), [h, w], interpolation=InterpolationMode.BICUBIC)
139
+ for j, pt in zip(js, self._patches(x)):
140
+ out[j] = pt
141
+ if cache:
142
+ for k, o in zip(keys, out):
143
+ self.frames[k] = o
144
+ self.frames.move_to_end(k)
145
+ while len(self.frames) > FRAME_CACHE_MAX:
146
+ self.frames.popitem(last=False)
147
+ self.stats = {"new": len(todo), "cached": len(keys) - len(todo)}
148
+ return {"tokenized_data": {**td, "pixel_values": torch.cat(out, 0)},
149
+ "ego_history_xyz": raw["ego_history_xyz"].reshape(1, 1, -1, 3).to(self.device),
150
+ "ego_history_rot": raw["ego_history_rot"].reshape(1, 1, -1, 3, 3).to(self.device)}
alpamini/thin.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Past-frame token thinning at inference.
2
+
3
+ Each past-frame (non-t0) LM image token is kept with probability `keep_frac`; t0 frames stay full. Removed
4
+ tokens are deleted from the prompt; kept tokens keep their ORIGINAL 3D RoPE positions and rope_deltas is
5
+ shifted by the number removed, so CoT decode and expert positions equal those of the full prompt. The vision
6
+ tower still encodes every frame (thinning happens after it).
7
+
8
+ Usage: `with thinned(model, tokenized_data, keep_frac) as td: model.sample_trajectories_from_data({..., "tokenized_data": td})`.
9
+ The upstream generation code is untouched; inside the context the VLM's get_image_features / get_rope_index
10
+ are wrapped so the thinned prompt is consistent. keep_frac >= 1 is a no-op (identical to the full path).
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import contextlib
15
+
16
+ import torch
17
+
18
+ # frames per camera in prompt order (alpamayo2_edge CAMERA_FRAME_COUNTS order: 0, 1, 2, 3, 5, 6); last = t0
19
+ FRAME_COUNTS = (3, 5, 3, 3, 3, 5)
20
+ CAMERA_IDS = (0, 1, 2, 3, 5, 6) # 6 = front telephoto
21
+
22
+
23
+ def past_token_mask(image_grid_thw: torch.Tensor, merge: int, exempt: tuple = ()) -> torch.Tensor:
24
+ """Bool over the LM image tokens (prompt order): True = a past-frame (non-t0) token of a camera not in
25
+ `exempt` (exempt cameras keep every frame)."""
26
+ out, i = [], 0
27
+ for cam, n in zip(CAMERA_IDS, FRAME_COUNTS):
28
+ for k in range(n):
29
+ t, h, w = image_grid_thw[i].tolist()
30
+ out.append(torch.full((t * (h // merge) * (w // merge),), k < n - 1 and cam not in exempt,
31
+ dtype=torch.bool))
32
+ i += 1
33
+ assert i == image_grid_thw.shape[0], f"expected {i} images, got {image_grid_thw.shape[0]}"
34
+ return torch.cat(out)
35
+
36
+
37
+ _LAYOUTS: dict = {} # prompt layout -> full-prompt 3D RoPE positions, image-token positions, past mask
38
+
39
+
40
+ def _layout(vm, ids, mm, grid, exempt=()):
41
+ """Everything that depends only on the prompt layout (token types, image grids, length), computed once.
42
+ Text token VALUES (nav text, history placeholders) do not enter the positions, only the types."""
43
+ mm_cpu, grid_cpu = mm.cpu(), grid.cpu()
44
+ key = (mm_cpu.numpy().tobytes(), grid_cpu.numpy().tobytes(), tuple(exempt))
45
+ lay = _LAYOUTS.get(key)
46
+ if lay is None:
47
+ with torch.no_grad():
48
+ pos, rd = vm.get_rope_index(ids.cpu(), mm_token_type_ids=mm_cpu, image_grid_thw=grid_cpu,
49
+ attention_mask=torch.ones_like(mm_cpu))
50
+ img_pos = (ids[0].cpu() == vm.config.image_token_id).nonzero().squeeze(1)
51
+ past = past_token_mask(grid_cpu, vm.visual.config.spatial_merge_size, tuple(exempt))
52
+ assert past.shape[0] == img_pos.shape[0], (past.shape, img_pos.shape)
53
+ lay = {"pos": pos.to(ids.device), "rd": rd.to(ids.device), "img_pos": img_pos, "past": past}
54
+ if len(_LAYOUTS) > 64:
55
+ _LAYOUTS.clear()
56
+ _LAYOUTS[key] = lay
57
+ return lay
58
+
59
+
60
+ @contextlib.contextmanager
61
+ def thinned(model, tokenized_data: dict, keep_frac: float, generator: torch.Generator | None = None,
62
+ exempt: tuple | None = None):
63
+ """exempt: camera ids never thinned (default: model._thin_exempt, else none)."""
64
+ exempt = tuple(getattr(model, "_thin_exempt", ()) if exempt is None else exempt)
65
+ if keep_frac >= 1:
66
+ yield tokenized_data, 0
67
+ return
68
+ vm = model.vlm.model
69
+ ids, mm, grid = tokenized_data["input_ids"], tokenized_data["mm_token_type_ids"], tokenized_data["image_grid_thw"]
70
+ assert ids.shape[0] == 1, "thinning supports batch 1"
71
+ lay = _layout(vm, ids, mm, grid, exempt)
72
+ u = torch.rand(lay["past"].shape[0], generator=generator) # CPU: the only per-call work, no GPU sync
73
+ drop_img = lay["past"] & (u >= keep_frac) # over image tokens
74
+ keep_cpu = torch.ones(ids.shape[1], dtype=torch.bool)
75
+ keep_cpu[lay["img_pos"][drop_img]] = False
76
+ n_rm = int(drop_img.sum())
77
+ keep_img = (~drop_img).to(ids.device, non_blocking=True)
78
+ keep = keep_cpu.to(ids.device, non_blocking=True)
79
+ pos_kept, rd_kept = lay["pos"][:, :, keep], lay["rd"] + n_rm
80
+
81
+ td = dict(tokenized_data)
82
+ td["input_ids"] = ids[:, keep]
83
+ td["mm_token_type_ids"] = mm[:, keep]
84
+ td["attention_mask"] = torch.ones_like(td["input_ids"])
85
+
86
+ orig_feat, orig_rope = vm.get_image_features, vm.get_rope_index
87
+ saved = {k: vars(vm)[k] for k in ("get_image_features", "get_rope_index") if k in vars(vm)} # caller's wrappers
88
+
89
+ def get_image_features(*a, **k):
90
+ out = orig_feat(*a, **k)
91
+ out.pooler_output = (torch.cat(out.pooler_output, 0)[keep_img],)
92
+ return out
93
+
94
+ def get_rope_index(input_ids, *a, **k): # called on prefixes of the thinned prompt only
95
+ n = input_ids.shape[1]
96
+ return pos_kept[:, :, :n].expand(-1, input_ids.shape[0], -1), rd_kept.expand(input_ids.shape[0], -1)
97
+
98
+ vm.get_image_features, vm.get_rope_index = get_image_features, get_rope_index
99
+ try:
100
+ yield td, n_rm
101
+ finally:
102
+ del vm.get_image_features, vm.get_rope_index # restore the class methods / the caller's wrappers
103
+ vars(vm).update(saved)
media/023b7fcc.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f8c3ffae05675fbdc6163bfa10759df16bd8c6722067b8a669abf9d774a7ca59
3
+ size 718133
media/02eadd92.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:790d9dd38b9088d6af8e6c0ac46b7fde2e95d0aef89351a642d33535efcdda81
3
+ size 922992
media/07981e6a.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e87bc94d3a53a6a48f246a6e7a69b1efad09ba198fce2952f8c2376ab3aca1c
3
+ size 982281
media/6f34d20b.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ed5587106f7d3513adf8d4bf93555c32edcd3c088bd3fc246507e3f6e9f8f238
3
+ size 545749
media/6f3be572.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d95444cc426bacc2b2ed49fd3c40c9fae146f4b86c0340ab2f54636b5f1584c2
3
+ size 505212
media/cdb709d1.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4b3b6c402a13153f0da08919741734a4dba84502da480e0833b8434aa588c016
3
+ size 1318291
media/d7a656c2.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c2b3e4bfd7c9191bc1e109069437c2cfa86944497e539b09b3063d902a137a4c
3
+ size 1183771
media/e39fb49b.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:528b406bef91d3f19f5d658427e69a30520d4775383383291f27b35e44d04759
3
+ size 209078
media/f41175b5.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2eee437c7bb6d65bd8afa3259de06dafd698147e0a6956f5f791e8a5b8abc0be
3
+ size 991000
media/fe0c2168.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2798ecb50160b96fd5fecb923012dd3513370a3cbd9d1b53183e9ef7398edcee
3
+ size 505182
pyproject.toml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "alpamini"
7
+ version = "1.0.0"
8
+ description = "alpamini: compressed NVIDIA Alpamayo 2 Edge, 93 ms per driving decision"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "Apache-2.0 (code); OpenMDW-1.1 (weights)" }
12
+ dependencies = [
13
+ "alpamayo2-edge @ git+https://github.com/NVlabs/alpamayo2-edge@02f55a7",
14
+ "safetensors>=0.4",
15
+ "huggingface_hub>=1.0",
16
+ ]
17
+
18
+ [project.optional-dependencies]
19
+ # CUDA graphs / flash attention: the 93 ms configuration (alpamini.load(accel=False) runs without it)
20
+ flash = ["flash-attn==2.8.3"]
21
+ # the PhysicalAI-AV loader used by alpamini.example / alpamini.bench
22
+ dataset = ["physical-ai-av==0.2.0"]
23
+
24
+ [tool.setuptools]
25
+ packages = ["alpamini"]