BEVFormer-style: learnable BEV queries look up six camera feeds through deformable attention, guided by camera geometry, and produce a dense top-down feature map — the classic perception front end for camera-based driving.
Why deformable attention keeps the cost linear in the number of BEV cells
Where the FLOPs and milliseconds actually go (the image backbone), and what to optimize on Orin / Thor
What changed in driving perception after BEVFormer, as of Oct 2026
🎬 Learn it visually
Watch or read one of these first if a section feels abstract. Ordered: best intuition first, code last.
🎥 Tesla AI Day 2021, "Tesla Vision" segment, Andrej Karpathy (starts at 48:44, about 25 min). Best intuition: why per-camera predictions fail, and how a transformer fuses all cameras into one top-down "vector space".
💻 BEVFormer official code. Read spatial_cross_attention.py next to §4 once the toy bev.py makes sense.
The Core Problem: 6 Cameras → One Top-Down Map
Intuition first. BEV is painting camera pixels onto a map seen from above. Every cell of a top-down grid asks "which pixels, in which cameras, show me?" and copies their features. Because the cell knows where it is in metres, geometry can answer that question.
A self-driving car has cameras mounted around the vehicle, each seeing a different slice of the surrounding world. Planning needs a single coherent top-down view — a feature map in the car's ego-centric frame showing everything nearby. The job of the BEV ("bird's-eye view") tokenizer is to turn multi-view imagery into that feature map.
1The BEV grid is a 2D grid of physical cells centred on the ego vehicle; BEVFormer-base uses 200 × 200 cells of 0.512 m. Each cell has a fixed (x, y) in metres, a pillar of 4 heights z, and one learnable query vector of size d_model (256). The objective: fill every cell with a feature vector answering "what is at this physical location?"
2Each cell looks up the relevant pixels in the cameras that can see it. That is usually 1 of the 6, or 2 where neighbouring views overlap, like this car seen by the front and front-left cameras.
Ego frame convention used throughout: x forward, y left, z up. Wedges are schematic fields of view; the object in the overlap is visible to two cameras.
Why this matters. 3D detection, map segmentation, motion forecasting and planning all become easier on a metric top-down grid, because distances and directions are explicit. BEVFormer (2022) made the camera-only version of this practical, and later end-to-end planners such as UniAD built directly on its BEV features. Production stacks rarely publish their internals, so treat BEVFormer as the clean, well-documented reference design rather than "what every car runs".
BEVFormer-base at a glance
Setting
Value (paper / official config)
Cameras, image size
6 views (nuScenes, 360°), 900×1600, padded to 928×1600
Backbone
ResNet-101-DCN + FPN (multi-scale features, C = 256)
BEV grid
200×200 cells, 0.512 m each → ±51.2 m around the car
4 anchors sampled uniformly in −5 m … 3 m (LiDAR-centred frame)
Deformable attention
8 heads; spatial cross-attn: 8 points per head; temporal self-attn: 4 points per head
1. Two Approaches: LSS vs BEVFormer
Intuition. Push or pull. LSS throws every pixel out onto the map (it has to guess how far away each pixel is); BEVFormer lets every map cell go and fetch the pixels it needs.
There are two classic families for building the BEV feature map. They solve the same problem in opposite directions:
Approach
How it builds BEV features
Pros
Cons
LSS (Lift-Splat-Shoot) Philion & Fidler, 2020
"Push": predict a depth distribution for every pixel, lift each pixel to a frustum of weighted 3D points, then "splat" (sum-pool) them into BEV cells.
Simple, parallel, no iterative attention.
Quality is capped by monocular depth prediction.
BEVFormer Li et al., 2022 (this guide)
"Pull": each BEV cell is a learnable query; geometry tells it where to look in each camera; deformable attention samples a few points there.
No explicit depth network. Geometry is built in via projection. Adds temporal context cheaply.
More complex attention; needs a custom sampling kernel to be fast.
Both produce the same kind of output: a dense BEV feature map. Many later systems mix ideas from both families.
2. Full Model Pipeline
Intuition. Turn the six images into feature maps once, then refine a grid of map cells layer by layer. Each layer lets every cell look at the cameras and at last frame's map.
The BEVFormer encoder from camera images to BEV feature map:
1The backbone (BEVFormer-base: ResNet-101-DCN + FPN) runs once per frame on all six images [B, 6, 3, 928, 1600] and gives multi-scale features, e.g. [B, 6, 256, 58, 100] at 1/16 scale. Every layer's spatial cross-attention reads these same features.
2Camera calibration (intrinsics [B, 6, 3, 3], ego_to_cam [B, 6, 4, 4]) is fixed per rig. Projecting the pillar points gives reference points [B, 6, 40000, 4, 2] and a validity mask [B, 6, 40000, 4]: fixed geometry, no learning (§3).
3The output map Bt is kept and becomes Bt−1 for every layer's temporal self-attention at the next frame (§4b).
4The learnable BEV queries [40000, 256] (+ positional embedding) enter the first layer. Each layer is temporal self-attention + spatial cross-attention + FFN and keeps the shape [40000, 256]; the last output is reshaped to [B, 200, 200, 256] for the detection, segmentation or planning heads.
Three observations worth staring at:
The image features are computed once per frame by the backbone and read by every layer's cross-attention. The same is true for the reference points and validity masks from camera geometry.
The BEV queries keep their shape through the stack: [B, 40000, 256] in, [B, 40000, 256] out after every layer. The final output is reshaped into [B, 200, 200, 256] for the heads.
What is learned vs fixed: the backbone, the query table, and all attention / FFN weights are learned. Intrinsics and extrinsics are calibration constants, so for a fixed rig the reference points can be precomputed once.
3. Camera Projection: The Geometry Hook
Intuition. A pinhole camera: things twice as far away look half as big, so you divide by depth. That one division turns a 3D point into a pixel.
What makes BEV work is that every BEV cell has a known 3D location in the car's ego frame. We can therefore project it to 2D pixel coordinates in every camera with plain linear algebra, no neural network involved. That is how the cross-attention knows where to look in each image.
One subtlety: a cell is a column of space, not a point. A car's roof and its wheels sit at different heights, so they land on different image rows. BEVFormer therefore lifts each cell into a pillar of Nref = 4 heights and projects every height. A camera counts as "hit" if at least one of the 4 points lands inside its image.
What to notice: every step is plain linear algebra, no network. The same cell gets different reference points in different cameras, and most cameras cannot see it at all (a cell 20 m ahead is behind the rear camera): that is the validity mask, valid = Zcam > 0 ∧ 0 < u < W ∧ 0 < v < H. For the whole grid the result is a tensor [B, 6, 40000, 4, 2] (camera, cell, height, uv), the sampling centres for grid_sample in deformable cross-attention.
The maths, one step at a time
Camera projection, step by step
Intuition. Move the point into the camera's own axes, then divide by depth: far things shrink toward the image centre, exactly like a pinhole camera.
pcam = R (pego − C)u = fx X/Z + cxv = fy Y/Z + cy
Read it aloud
"p-cam equals R times p-ego minus C; u equals f-x times X over Z plus c-x, and the same for v." pego [3] is the point in the car frame (x forward, y left, z up); C [3] is the camera centre and R the 3 × 3 rotation into camera axes (X right, Y down, Z forward = depth); fx, fy are focal lengths in pixels and (cx, cy) the image centre; (u, v) is the pixel. Last, (2u/W − 1, 2v/H − 1) rescales to grid_sample's [−1, 1].
Why it exists
It tells every BEV cell exactly where to look in each image, with no learning. Without it, attention would have to search every pixel of every camera (6 × 58 × 100 = 34,800 positions per head at 1/16 scale). Dividing by Z is what makes far objects small, and Z ≤ 0 means "behind the camera", which is one part of the validity mask.
Tiny example
The toy rig from bev.py: images 800×448, f = 500 px (so cx = 400, cy = 224), cameras 1.6 m above the ground. Project the ground point p = (10, 2, 0), 10 m ahead and 2 m to the left, into the front camera (yaw 0°):
Relative to the camera centre C = (0, 0, 1.6): p − C = (10, 2, −1.6).
Camera axes for the front camera: right = −y, down = −z, forward = +x. So Xcam = −2, Ycam = 1.6, Zcam = 10 (depth).
Pixels: u = 500 · (−2/10) + 400 = 300, v = 500 · (1.6/10) + 224 = 304 — left of centre and below the horizon, as expected.
Two consequences fall out of the same formula. A ground point is only visible once v < H, i.e. Zcam > f·h / (H/2) = 500 · 1.6 / 224 ≈ 3.6 m: the ground right next to the car is below the bottom edge of every image. And a point at camera height (z = 1.6 m) always lands on the image's middle row, v = cy, at any distance — which is why the higher pillar anchors keep nearby cells visible.
Interactive: camera-to-BEV projection explorer
Click or drag on the top-down map to pick a BEV cell (range ±25 m). Its 4 pillar points (z = 0, 1, 2, 3 m) are projected into the six 800×448 images of the same toy rig bev.py uses.
table shows height
In each image the dots are the pillar heights, from z = 0 (darkest) to 3 m; the dashed line is the image's middle row (v = 224). What to notice: most cells hit one camera, cells in the overlap of two wedges hit two; the four heights of a pillar land on one vertical line; and cells within a few metres of the car only show up through their higher pillar points.
For a fixed camera rig, steps 1–4 are entirely deterministic. You can precompute the reference points and masks once at startup and keep them as a static lookup table. Moving the car does not change them: BEV cells live in the ego frame, which moves with the car. Only a change of calibration does.
4. Deformable Spatial Cross-Attention
Intuition. Don't search every pixel. Geometry already points to the right spot in each image; the network only learns where to look nearby (a few small nudges) and how much to trust each look.
With reference points in hand, each BEV query needs to read features near those points in the cameras that see it. Dense cross-attention from every query to every feature pixel would score 40,000 × 6 × 58 × 100 ≈ 1.4 billion query–key pairs per head per layer. Deformable attention instead lets each query predict a handful of sampling offsets around a reference point and bilinearly interpolates the features there.
1Offsets. A Linear layer on the query predicts a 2D offset Δp (in feature pixels) per head h, height j and point k: [8 heads, 4 heights × 2 points, 2]. The offsets depend only on the query, so the same pattern is replayed around each camera's reference point; a seventh camera adds no parameters.
2Sample near the reference point. The reference point comes from geometry, outside the network: ref[cam, j] = project(x, y, zj) (§3). Sampling locations are loc = ref[cam, j] + Δp[h, j, k], read with bilinear grid_sample from head h's own 32-channel slice of the value projection: [hit cams, 8, 8, 32].
3Weights. Another Linear + softmax per head over its 8 points gives w [8 heads, 8 points]. Per head, Σpoints w · sample gives 32 channels; the 8 heads are concatenated.
4Average over hit cameras (not a softmax across cameras), then Wo → [256]. Cost per query per layer: 8 heads × 8 points × (1–2 hit cameras) bilinear lookups of 32 channels, instead of scoring all 6 × 58 × 100 = 34,800 feature pixels. MSDeformAttn fuses the sampling and the weighted sum in one kernel.
Written as math (paper Eq. 2), for query Qp at cell p:
Vhit is the set of cameras hit by the pillar, and P(p, i, j) is the projection of pillar point j into camera i. Three details that are easy to get wrong:
Offsets and weights do not depend on the camera. They come from the query alone, so the same pattern is replayed around each camera's reference point. Adding a seventh camera adds no parameters.
Heads are real heads. Each head reads its own 32-channel slice of the value features at its own points with its own softmax, and the head outputs are concatenated — exactly like multi-head attention in the Transformer module.
Average over hit cameras, not a softmax across cameras. A cell seen by two cameras should not get twice the magnitude, and a camera that cannot see the cell must contribute nothing.
# One query q, one layer — BEVFormer-base shapes: 8 heads, 4 heights, 2 points per height
offsets = Linear(q).view(8, 4, 2, 2) # [head, height, point, xy] in feature pixels
weights = Linear(q).view(8, 8).softmax(-1) # per head, over its 8 points
out = 0for cam in hit_cams: # usually 1-2 of the 6 cameras
heads = []
for h inrange(8):
loc = ref[cam][:, None, :] + offsets[h] # [height, point, 2]
s = bilinear(V[cam][h], loc) # [height, point, 32]
heads.append((weights[h].view(4, 2, 1) * s).sum((0, 1)))
out += concat(heads) # [256]
q_new = W_o(out / len(hit_cams)) # average over hit cameras
4b. Temporal self-attention
Intuition. Remember last frame's map, shift it to undo the car's own motion, and let every cell look at it. Two frames are enough to tell a parked car from a moving one.
BEVFormer has no dense self-attention over the 40,000 queries (that would cost O(N²), see Section 8). Its "self-attention" is temporal self-attention (TSA): another deformable attention, where each query samples 4 points per head around its own cell in two value maps — the previous frame's BEV map B't−1 (re-aligned for ego motion) and the current queries Q — and averages the two:
TSA(Qp) = ΣV ∈ {Q, B't−1} DeformAttn(Qp, p, V)
(The paper writes a sum; the official code takes the mean, which only rescales.) The offsets are predicted from the concatenation of Q and B't−1. On the first frame of a sequence there is no history, so {Q, B't−1} is replaced by {Q, Q}. The cost is linear in the number of cells, and the only state carried between frames is one BEV map (200 × 200 × 256 × 2 bytes ≈ 20 MB in FP16). The paper's nuScenes validation results (ResNet-101-DCN) show what history buys:
Model
NDS ↑
mAP ↑
mAVE (velocity error, m/s) ↓
BEVFormer-S (no temporal information)
0.448
0.375
0.802
BEVFormer (with temporal self-attention)
0.517
0.416
0.394
Velocity error roughly halves (0.802 → 0.394 m/s). A single frame cannot tell a parked car from a moving one, and two frames can.
5. Code Walkthrough
make_bev_pillar_points + project_ego_to_image — the geometry▼
Purpose: build the 3D pillar points of every BEV cell, then project them through each camera's extrinsics and intrinsics. Returns normalised reference points and a validity mask. Nothing here is learned.
defmake_bev_pillar_points(bev_h, bev_w, resolution=0.5, z_anchors=(0.0, 1.0, 2.0, 3.0)):
x = (torch.arange(bev_h) - (bev_h - 1) / 2) * resolution # forward
y = (torch.arange(bev_w) - (bev_w - 1) / 2) * resolution # left
... # stack (x, y, z_j) for every heightreturn pts.reshape(bev_h * bev_w, N_z, 3) # [N_q, N_z, 3]defproject_ego_to_image(points_3d, intrinsics, ego_to_cam, img_h, img_w):
pts = points_3d.reshape(-1, 3)
p_ego_h = torch.cat([pts, ones], dim=-1).T # [4, N_pts] homogeneous
p_cam = (ego_to_cam @ p_ego_h)[..., :3, :] # [B, N_cam, 3, N_pts]
pix_h = intrinsics @ p_cam # K · p_cam
z = pix_h[..., 2, :]
uv = pix_h[..., :2, :] / z.clamp(min=1e-5).unsqueeze(-2) # divide by depth
u, v = uv[..., 0, :], uv[..., 1, :]
valid = (z > 1e-5) & (u > 0) & (u < img_w) & (v > 0) & (v < img_h)
# grid_sample(align_corners=False) convention, same normalisation as BEVFormer
uv_norm = torch.stack([2.0 * u / img_w - 1.0, 2.0 * v / img_h - 1.0], dim=-1)
return uv_norm, valid # [B, N_cam, N_q, N_z, 2], [B, N_cam, N_q, N_z]
Why 2u/W − 1 works on the feature map too: with align_corners=False, −1 and +1 are the outer edges of the grid. An image of width W and its stride-16 feature map of width W/16 cover the same physical extent, so one normalised coordinate addresses both. (You can check it: sampling a stride-16 feature map at image pixel (16c + 8, 16r + 8) returns exactly feature pixel (r, c).)
SpatialCrossAttention.forward — deformable sampling over hit cameras▼
defforward(self, query, img_feats, ref_uv, valid):
# query [B, N_q, d]; img_feats [B, N_cam, d, H_f, W_f]# ref_uv [B, N_cam, N_q, N_z, 2]; valid [B, N_cam, N_q, N_z]
v = self.value_proj(img_feats.permute(0, 1, 3, 4, 2)) # project channels
v = v.view(B, N_cam, H_f, W_f, nH, hd).permute(0, 1, 4, 5, 2, 3) # split heads
off = self.sampling_offsets(query).view(B, N_q, nH, nZ, P, 2)
off = off * off.new_tensor([2.0 / W_f, 2.0 / H_f]) # feature px -> [-1, 1] units
w = self.attention_weights(query).view(B, N_q, nH, nZ * P).softmax(-1)
hit = valid.any(dim=-1) # [B, N_cam, N_q]: any height inside?
out = 0for c inrange(N_cam): # official code gathers hit queries only
loc = ref_uv[:, c][:, :, None, :, None, :] + off # [B, N_q, nH, nZ, P, 2]
s = F.grid_sample(v[:, c] (as B*nH, hd, H_f, W_f), loc (as B*nH, N_q, nZ*P, 2),
align_corners=False) # [B*nH, hd, N_q, nZ*P]
o = (s * w).sum(-1) # weighted sum per head
out = out + concat_heads(o) * hit[:, c, :, None] # zero if camera not hit
count = hit.sum(dim=1).clamp(min=1) # |V_hit|return self.output_proj(out / count[..., None])
Initialisation detail: the offset layer starts with zero weights and a bias that points head h in direction 2πh/8 at radii 1, 2, … feature pixels (Deformable DETR's trick). Every head therefore starts looking at a different neighbourhood instead of all collapsing onto the reference point.
TemporalSelfAttention + BEVFormer.forward — tying it together▼
classTemporalSelfAttention(nn.Module):
defforward(self, query, prev_bev, bev_h, bev_w):
if prev_bev isNone:
prev_bev = query # first frame: {Q, Q}
values = torch.stack([prev_bev, query], dim=1) # two value maps
q_cat = torch.cat([prev_bev, query], dim=-1) # offsets see both
off = self.sampling_offsets(q_cat).view(B, N, 2, nH, P, 2) # in BEV cells
w = self.attention_weights(q_cat).view(B, N, 2, nH, P).softmax(-1)
loc = own_cell_centre + off # sample around ITSELF
... # grid_sample per head, weighted sumreturn self.output_proj(o.mean over the two value maps)
classBEVFormer(nn.Module):
defforward(self, images, intrinsics, ego_to_cam, prev_bev=None):
B, N_cam, _, H, W = images.shape
feats = self.backbone(images.reshape(B * N_cam, 3, H, W)) # cameras folded into batch
feats = feats.reshape(B, N_cam, self.d_model, H // 16, W // 16)
ref_uv, valid = project_ego_to_image(self.bev_pillars, intrinsics, ego_to_cam, H, W)
bev_q = self.bev_queries.unsqueeze(0) + self.bev_pos().unsqueeze(0)
for layer in self.layers: # TSA -> SCA -> FFN
bev_q = layer(bev_q, prev_bev, feats, ref_uv, valid, self.bev_h, self.bev_w)
return bev_q.reshape(B, self.bev_h, self.bev_w, self.d_model)
Positional embedding: BEVFormer's learned positional embedding is factorised — a row table [200, 128] and a column table [200, 128], concatenated per cell. That is 51,200 parameters, not 200 × 200 × 256. The query table itself (10.24 M parameters) is the big one.
6. Complexity Calculator
Defaults match BEVFormer-base geometry with the ResNet-101 backbone estimate. The formulas are the same as bev_cost() in bev.py, so you can cross-check any number in Python. One FLOP is one multiply or add (a multiply-accumulate is 2 FLOPs). ResNet backbone FLOPs scale the paper's 224×224 multiply-add counts (3.8 G for ResNet-50, 7.6 G for ResNet-101) by pixel count; FPN and DCN are not included.
Try: switch the backbone to the toy stub and watch the encoder become a large share of the work; then set the BEV grid to 128 and compare the "full self-attention" line (quadratic) with the encoder line (linear).
7. Critical Optimizations
The general techniques behind these (batching, precomputation, fused kernels, INT8/FP16 mixed precision, roofline budgeting) are collected in the Memory & inference efficiency cookbook. Here is how they apply to BEVFormer.
7.1 The fused deformable-attention kernel (MSDeformAttn)▼
The pure-PyTorch path materialises every sampled feature: for BEVFormer-base, 40,000 queries × 8 heads × 8 points × 32 channels per hit camera and layer, written to memory by grid_sample and read back for the weighted sum. The Deformable-DETR CUDA kernel instead launches one thread per output element (batch, query, head, channel). Each thread loops over levels × points, does the bilinear interpolation, multiplies by the attention weight and accumulates in a register, then writes one number. The intermediate tensor never touches DRAM.
The offset and weight predictions stay ordinary Linear layers (GEMMs), so they run on Tensor Cores; the sampling itself is a gather-heavy, memory-bound operation. BEVFormer's code adds a per-camera "rebatching" step: each camera processes only the queries it hits. With ~1–2 hit cameras out of 6, that skips most of the sampling work.
7.2 Shared backbone, batched cameras▼
All 6 cameras share one backbone's weights. Rather than calling it 6 times, fold the cameras into the batch dimension:
# Bad: 6 sequential calls, 6x the kernel launches, small batches
feats_per_cam = [backbone(images[:, c]) for c inrange(6)]
# Good: one batched call
feats = backbone(images.reshape(B * 6, 3, H, W))
feats = feats.reshape(B, 6, d, H_feat, W_feat)
Each convolution then runs once on a 6× larger batch, which keeps the GPU busier and makes a single TensorRT engine serve all cameras.
7.3 Precompute the camera geometry▼
For a fixed rig, project_ego_to_image always returns the same answer. Precompute once at startup:
Per-camera lists of hit queries (for the rebatching in 7.1)
If calibration can change at runtime (re-calibration, a camera knocked out of place), recompute on the GPU; it is one small batched matmul.
7.4 Temporal state is cheap; keep it▼
Temporal self-attention carries exactly one previous BEV map between frames (≈ 20 MB at 200×200×256 FP16). It needs no growing history, much like a recurrent state. Its compute is another deformable attention, linear in the number of cells, and the accuracy gain is large (Section 4b). The implementation cost is the ego-motion warp of Bt−1: a rotation + translation of the grid, i.e. one grid_sample of the whole map. bev.py skips it; exercise 5 adds it.
StreamPETR takes a different route to the same goal: it propagates a small set of object queries frame to frame instead of a dense map.
7.5 Quantization — measured numbers from NVIDIA's reference▼
NVIDIA's DL4AGX BEVFormer INT8 sample quantizes BEVFormer-tiny with TensorRT and ModelOpt and reports, on an A40 GPU (TensorRT 10.14, median GPU compute time):
Precision
Latency
NDS / mAP
FP32
18.68 ms
0.355 / 0.252
FP16
9.27 ms
0.355 / 0.252
INT8, TensorRT implicit PTQ
6.16 ms
0.353 / 0.249
INT8, ModelOpt explicit quantization
5.76 ms
0.352 / 0.251
That is about 2.0× for FP32 → FP16 and another 1.6× for FP16 → INT8, at a cost of 0.003 NDS. The sample deliberately leaves the attention MatMuls in FP16 (MHA blocks are "currently recommended to run in FP16") and keeps the deformable-attention plugin in half precision. A sensible starting split:
Component
Start with
Why
Image backbone (convs)
INT8 PTQ
The largest compute slice; CNN quantization is mature
Linear projections (value / offset / weight / FFN)
INT8 or FP16
Plain GEMMs; measure accuracy per layer
Attention MatMuls, deformable sampling
FP16
Sampling locations are sub-pixel coordinates, so precision matters
Heads
FP16
Small; keep precision near the outputs
8. Deployment: Where the Milliseconds Go
The BEVFormer paper measured its own latency (Table 6; one V100 GPU, ResNet-101-DCN, 900×1600 input):
Configuration
Backbone
BEV encoder
Head
FPS
NDS
BEVFormer (multi-scale, 200×200, 6 layers)
391 ms
130 ms
19 ms
1.7
0.517
C: 1 encoder layer
391 ms
25 ms
19 ms
2.1
0.501
D: single-scale, 100×100, 1 layer
387 ms
7 ms
18 ms
2.3
0.478
The lesson the authors draw: the backbone is the bottleneck. Shrinking the encoder from 130 ms to 7 ms only lifts the frame rate from 1.7 to 2.3 FPS, because six ResNet-101 passes at full resolution still cost ~390 ms. The calculator says the same: six ResNet-101s at 928×1600 are ≈ 2.7 TFLOPs, about 7× the whole BEV encoder.
Edge targets for reference (NVIDIA spec pages): Jetson AGX Orin 64GB — 275 sparse INT8 TOPS in total (the GPU's share is 85 dense INT8 TOPS), 204.8 GB/s LPDDR5; Jetson AGX Thor T5000 — 2070 sparse FP4 TFLOPS, 128 GB LPDDR5X at 273 GB/s. Headline TOPS are sparse, low-precision peaks. Budget from measurements (trtexec on the device), not from these numbers.
The N² trap — why there is no dense BEV self-attention. A 200×200 grid has N = 40,000 queries. Dense self-attention would form N² = 1.6 billion scores per head per layer: 1.6e9 × 8 heads × 2 bytes = 25.6 GB in FP16 if materialised, and 4·N²·d = 1.64 TFLOPs per layer even with a FlashAttention-style kernel that never stores them. Over 6 layers (plus projections) that is ≈ 10 TFLOPs, about 3.7× the six ResNet-101 passes. BEVFormer sidesteps it with deformable temporal self-attention, whose cost grows linearly with N.
Knobs for tight budgets, roughly biggest win first:
Lighter or lower-resolution backbone. 1600×928 → 800×464 is 4× fewer pixels, so ~4× fewer backbone FLOPs. ResNet-101 → ResNet-50 halves the multiply-adds (7.6 G → 3.8 G at 224²).
INT8 for the backbone (Section 7.5), with FP16 for attention.
Fewer encoder layers. Paper config C: 6 → 1 layer cuts the encoder from 130 ms to 25 ms for −1.6 NDS.
Smaller BEV grid. 200×200 → 128×128 is 2.44× fewer cells; the deformable encoder's cost scales about linearly with that.
Gather hit queries per camera (7.1) and precompute geometry (7.3).
9. As of Oct 2026: Where Driving Perception Went Next
BEVFormer is still the clearest way to learn camera-to-BEV lifting, but the field has moved in three directions:
Sparse, query-based temporal perception. Instead of a dense 200×200 map, methods such as StreamPETR (2023) propagate a sparse set of object queries across frames, which is cheaper when you only need objects.
End-to-end planning on top of BEV features.UniAD (CVPR 2023 Best Paper) chains tracking, mapping, motion forecasting and planning on BEVFormer features; VAD uses vectorised scene representations for faster planning.
Vision-language-action models for driving. Waymo's EMMA (2024) maps raw camera data to trajectories, objects and road graph as text on a Gemini-based model. NVIDIA's Alpamayo-R1 (Oct 2025) pairs a Cosmos-Reason VLM with a diffusion trajectory decoder and reports 99 ms on-vehicle latency. In August 2026 NVIDIA released Alpamayo 2 Super: a 32B VLM backbone plus a diffusion action expert (34B total) that takes multi-camera video and outputs a trajectory plus a reasoning trace. These models consume camera tokens directly, with no explicit BEV grid. The next module (VLA) explains the architecture they share with robot policies.
Other connections:
3D occupancy — replace the 2D grid with a 3D voxel grid (or three orthogonal planes, as in TPVFormer) and predict which voxels are occupied. Occ3D is the standard benchmark. The cross-attention mechanics are the same, with an extra z dimension.
Robot VLAs (next module) usually skip BEV: each camera's ViT tokens go straight into a vision-language model. BEV pays off when you need a metric layout across many cameras over tens of metres, which is the driving case.
Diffusion planners — the BEV map (or camera tokens) becomes the conditioning input of a diffusion or flow model that generates future trajectories, using the same machinery as the diffusion module and the next module's action expert.
Key Takeaways
A BEV cell has a known 3D position, so camera projection (no learning) tells attention where to look in each image.
BEVFormer lifts each cell to a pillar of 4 heights. A camera is "hit" if any height lands in its image, and most cells hit 1–2 of 6 cameras.
Spatial cross-attention = deformable attention around the projected points, with camera-independent offsets and real per-head channels, averaged over hit cameras.
Temporal self-attention is also deformable. It carries one previous BEV map and roughly halves velocity error on nuScenes.
Nothing in the encoder is O(N²) in BEV cells. Dense self-attention over 40,000 cells would cost 1.64 TFLOPs and 25.6 GB of scores per layer.
The image backbone dominates both FLOPs and latency, so optimize it first (resolution, size, INT8). Keep sampling in FP16 and use the fused kernel.
As of Oct 2026, end-to-end planners and driving VLAs (EMMA, Alpamayo) build on or bypass BEV, but the geometry lessons carry over.
Self-Check
1. Why can BEVFormer afford to sample only a few points per query, when ViT-style attention looks at every token?
Answer
Because geometry already says where the relevant pixels are. The projected pillar points give a reference location in each camera, so the network only needs to learn small offsets around it, not search the whole image.
2. With the toy rig (800×448 image, f = 500 px, camera height 1.6 m), where does the ground point (x, y, z) = (10, 2, 0) land in the front camera, in pixels and in grid_sample coordinates?
Answer
Xcam = −2, Ycam = 1.6, Zcam = 10, so u = 500·(−0.2) + 400 = 300 and v = 500·0.16 + 224 = 304. Normalised: (2·300/800 − 1, 2·304/448 − 1) = (−0.25, 0.357).
3. In that rig, how far ahead must a ground point be before the front camera can see it? What about a point 1.6 m above the ground?
Answer
Ground: v = f·1.6/Z + 224 < 448 requires Z > 500·1.6/224 ≈ 3.57 m. At z = 1.6 m, Ycam = 0, so v = cy = 224 at every distance: always on the middle row (as long as it is in front and u is in range). That is one reason the pillar has several heights.
4. How big is the BEV feature map for a 200×200 grid at d = 256 in FP16, and what is the only state temporal self-attention carries between frames?
5. Why does spatial cross-attention divide by |Vhit| instead of summing over all six cameras?
Answer
Cameras that cannot see the cell would contribute garbage (zero-padded or wrong features), so they are masked out. Cells seen by two cameras would otherwise get roughly twice the magnitude of cells seen by one. Averaging over the hit cameras keeps the scale consistent across the grid.
6. For BEVFormer-base, how many sampling points does one query use per hit camera per layer, and how does that compare to dense cross-attention over one 1/16-scale feature level of all cameras?
Answer
8 heads × 8 points = 64 bilinear lookups (of 32 channels each) per hit camera. Dense attention would score all 6 × 58 × 100 = 34,800 feature pixels per head, about 540× more positions than 64.
7. Dense self-attention over 40,000 BEV queries with d = 256 and 8 heads: how much memory for the FP16 score matrices of one layer, and how many FLOPs?
Answer
Scores: 40,000² × 8 × 2 bytes = 25.6 GB. FLOPs for QKᵀ and AV: 4·N²·d = 4 × 1.6e9 × 256 ≈ 1.64 TFLOPs per layer. A fused attention kernel avoids storing the scores but not the FLOPs. BEVFormer's deformable temporal self-attention avoids both.
8. On the paper's V100 measurement, which optimization would you try first to double BEVFormer-base's frame rate, and why?
Answer
The backbone (resolution, a lighter network, INT8/TensorRT): it takes 391 of ~540 ms. Even deleting the encoder entirely (130 ms) could not double the frame rate.
9. You precompute the reference points [6, 40000, 4, 2] in FP32. How large is the table, and when must you recompute it?
Answer
6 × 40,000 × 4 × 2 × 4 bytes = 7.68 MB (plus a 0.96 MB byte mask). Recompute only when the calibration (intrinsics/extrinsics) or the BEV grid changes. Ego motion does not change it, because the grid is in the ego frame.
Hands-On Exercises
Build it yourself. Start with the guided lab labs/lab09.html: build camera intrinsics and extrinsics, project 3-D points to pixels (it reproduces the worked example above), lift BEV cells to pillar points, compute reference points with a visibility mask, and sample features with grid_sample. Check each step with python labs/check.py 9, then do the exercises below.
All exercises run on CPU against bev.py (cd bev; python). Easy first.
1. Verify the worked example and find the blind zone
Run bev.probe_point(10, 2, 0) and check the front camera prints u = 300, v = 304. Then scan x from 0 to 6 m at y = 0, z = 0 and find the first x the front camera can see.
For bev_small(), compute the mean number of cameras hit per cell with the default rig, then with make_camera_rig(..., focal_frac=0.4) (wider lenses). Check that the mean grows (about 1.28 → 1.72 cameras per cell).
m = bev.bev_small()
for ff in (0.625, 0.4):
K, T = bev.make_camera_rig(448, 800, focal_frac=ff)
_, valid = bev.project_ego_to_image(m.bev_pillars, K, T, 448, 800)
hits = valid.any(-1).sum(1).float()
print(ff, hits.mean().item(), hits.max().item())
3. Unit-test spatial cross-attention
Zero the offset bias and set value_proj and output_proj to identity. Then the output for a query must equal the mean, over its hit cameras, of the mean over its 4 heights of the bilinear sample at the reference point. Build a tiny case (d = 8, 3 cameras, 5 queries) and assert torch.allclose(...) against a hand-written bilinear interpolation. (Remember the align_corners=False pixel convention: pixel coordinate = (x + 1)·W/2 − 0.5.)
4. Break the averaging on purpose
Set value_proj and output_proj of a SpatialCrossAttention to identity and feed constant features (torch.ones) for all cameras of the demo rig. Group cells by how many cameras they hit. With the division by |Vhit|, 1-hit and 2-hit cells both come out at ≈ 1 per channel; replace out / count with plain out and the 2-hit cells jump to ≈ 2. That jump is exactly the seam you would see in the BEV map along camera overlaps.
5. Add the ego-motion warp to temporal self-attention
Write warp_bev(prev_bev, dx, dy, dyaw, res) that resamples the previous BEV map into the current ego frame with one F.grid_sample. Test it: a pure forward motion of exactly 3 cells (dx = 3·res, dyaw = 0) must equal torch.roll by −3 along the x (row) axis on all rows that stay inside the grid.
6. Where do the FLOPs go?
Using bev.bev_cost(), show that with backbone="resnet101" the backbone is more than 80% of total FLOPs for BEVFormer-base geometry, and find the smallest BEV grid at which the dense self-attention line (for contrast) would exceed the ResNet-101 backbone (you should land near 144×144).
c = bev.bev_cost(backbone="resnet101")
assert c["backbone_flops"] / c["total_flops"] > 0.8