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