"""
VLA (Vision-Language-Action) Reference Implementation — pi0-style

A robot policy that takes
    - camera images (one or more views)
    - a language instruction ("put the block in the red bowl")
    - proprioception (the robot's current joint state)
and produces
    - an ACTION CHUNK: H future actions (H = 50 in pi0), generated by flow matching.

Usage:
    python vla.py

Architecture — ONE transformer with TWO sets of weights (pi0, arXiv 2410.24164):

    prefix tokens  [image patches..., text tokens...]  -> VLM weights          (PaliGemma 3B in pi0)
    suffix tokens  [state, a_1 ... a_H (noisy actions + flow time)] -> action-expert weights (300M)

    Every layer runs ONE self-attention over the concatenated sequence with a
    block-causal mask (3 blocks):
        [images + text]  — attend among themselves only
        [state]          — attends to prefix + itself
        [actions]        — attend to prefix + state + all actions (bidirectional)
    So the weights only interact through attention, and the prefix never looks at
    the suffix. That is what makes inference cheap: run the prefix ONCE, cache its
    per-layer keys/values, then run only the small suffix 10 times (Euler steps).

    (This is NOT "cross-attention to the VLM's final output". Each action-expert
    layer attends to the SAME layer's VLM keys/values. pi0's appendix contrasts its
    main model with a smaller baseline whose action expert cross-attends to the
    encoder outputs; GR00T N1 — next module — uses that cross-attention style.)

Flow matching convention used in this file (and in the guide):
    x_t = (1 - t) * eps + t * a,   t = 0 is pure noise, t = 1 is data
    target velocity v = a - eps,   integrate dx/dt = v from t = 0 to 1 (10 Euler steps)
  openpi's code uses the mirrored convention (x_t = t*eps + (1-t)*a, u = eps - a,
  integrate from t = 1 down to 0 with dt = -0.1). Same ODE, time axis flipped:
  t_openpi = 1 - t_here and u_openpi = -v_here.
  Training times are drawn from a Beta(1.5, 1)-based density that favours the
  noisy end (pi0 appendix; also GR00T's code).

Model configs (toy backbones, CPU friendly):
    - VLA-S: d_vlm=256, d_action=128, 4 layers
    - VLA-B: d_vlm=512, d_action=256, 6 layers
  Real pi0: SigLIP-So400m + Gemma-2B (width 2048, 18 layers, 8 query heads,
  1 KV head, head_dim 256) + Gemma-300M action expert (width 1024, same depth and
  heads) = 3.3B. pi0_cost() below models that configuration analytically.

Simplifications:
- Vision encoder is a small ViT stub, not SigLIP; text is a token-embedding table.
- LayerNorm + GELU MLP instead of Gemma's RMSNorm + GeGLU; learned positions
  instead of RoPE.
"""
import math
from typing import Dict, List, Optional, Tuple

import torch
import torch.nn as nn
import torch.nn.functional as F


# ============================================================================
# 1. Vision encoder — stub SigLIP / ViT (bidirectional, per camera)
# ============================================================================

class ViTBlock(nn.Module):
    def __init__(self, d: int, n_heads: int, mlp_ratio: float = 4.0):
        super().__init__()
        self.norm1, self.norm2 = nn.LayerNorm(d), nn.LayerNorm(d)
        self.attn = nn.MultiheadAttention(d, n_heads, batch_first=True)
        self.mlp = nn.Sequential(nn.Linear(d, int(d * mlp_ratio)), nn.GELU(),
                                 nn.Linear(int(d * mlp_ratio), d))

    def forward(self, x):
        h = self.norm1(x)
        x = x + self.attn(h, h, h, need_weights=False)[0]
        return x + self.mlp(self.norm2(x))


class VisionEncoder(nn.Module):
    """images [B, N_cam, 3, H, W] -> tokens [B, N_cam * N_patches, d]. pi0: SigLIP-So400m,
    224x224 images, 14x14 patches -> 256 tokens per image."""
    def __init__(self, img_size: int = 224, patch_size: int = 14, d: int = 256,
                 depth: int = 2, n_heads: int = 4):
        super().__init__()
        self.n_patches = (img_size // patch_size) ** 2
        self.patch_embed = nn.Conv2d(3, d, kernel_size=patch_size, stride=patch_size)
        self.pos_embed = nn.Parameter(torch.zeros(1, self.n_patches, d))
        nn.init.trunc_normal_(self.pos_embed, std=0.02)
        self.blocks = nn.ModuleList([ViTBlock(d, n_heads) for _ in range(depth)])
        self.norm = nn.LayerNorm(d)

    def forward(self, images):
        B, N_cam = images.shape[:2]
        x = self.patch_embed(images.flatten(0, 1)).flatten(2).transpose(1, 2) + self.pos_embed
        for blk in self.blocks:
            x = blk(x)
        return self.norm(x).reshape(B, N_cam * self.n_patches, -1)


# ============================================================================
# 2. Shared attention between two experts ("mixture of transformers")
# ============================================================================

def attention(q, k, v, mask: Optional[torch.Tensor]):
    """q [B, H, Tq, hd]; k, v [B, H_kv, Tk, hd]; mask [Tq, Tk] bool (True = may attend).
    Grouped/multi-query attention: each KV head serves H / H_kv query heads."""
    if k.shape[1] != q.shape[1]:
        rep = q.shape[1] // k.shape[1]
        k, v = k.repeat_interleave(rep, dim=1), v.repeat_interleave(rep, dim=1)
    return F.scaled_dot_product_attention(q, k, v, attn_mask=mask)


class ExpertBlock(nn.Module):
    """One expert's weights for one layer: pre-norm, Q/K/V/O projections, MLP.
    Both experts project into the SAME number of heads and head_dim so their
    tokens can share one attention operation; their widths d can differ."""
    def __init__(self, d: int, n_heads: int, n_kv_heads: int, head_dim: int,
                 mlp_ratio: float = 4.0):
        super().__init__()
        self.n_heads, self.n_kv, self.hd = n_heads, n_kv_heads, head_dim
        self.norm1, self.norm2 = nn.LayerNorm(d), nn.LayerNorm(d)
        self.wq = nn.Linear(d, n_heads * head_dim, bias=False)
        self.wk = nn.Linear(d, n_kv_heads * head_dim, bias=False)
        self.wv = nn.Linear(d, n_kv_heads * head_dim, bias=False)
        self.wo = nn.Linear(n_heads * head_dim, d, bias=False)
        self.mlp = nn.Sequential(nn.Linear(d, int(d * mlp_ratio)), nn.GELU(),
                                 nn.Linear(int(d * mlp_ratio), d))

    def qkv(self, x):
        B, T, _ = x.shape
        h = self.norm1(x)
        q = self.wq(h).view(B, T, self.n_heads, self.hd).transpose(1, 2)
        k = self.wk(h).view(B, T, self.n_kv, self.hd).transpose(1, 2)
        v = self.wv(h).view(B, T, self.n_kv, self.hd).transpose(1, 2)
        return q, k, v

    def finish(self, x, attn_out):
        B, H, T, hd = attn_out.shape
        x = x + self.wo(attn_out.transpose(1, 2).reshape(B, T, H * hd))
        return x + self.mlp(self.norm2(x))


class MoTLayer(nn.Module):
    """One layer of the joint transformer: VLM weights for prefix tokens,
    action-expert weights for suffix tokens, one shared attention."""
    def __init__(self, d_vlm, d_act, n_heads, n_kv_heads, head_dim):
        super().__init__()
        self.vlm = ExpertBlock(d_vlm, n_heads, n_kv_heads, head_dim)
        self.act = ExpertBlock(d_act, n_heads, n_kv_heads, head_dim)

    def prefix(self, x):
        """Prefix tokens see only the prefix (bidirectionally). Returns new x and this
        layer's (K, V) — the KV cache the suffix will read."""
        q, k, v = self.vlm.qkv(x)
        return self.vlm.finish(x, attention(q, k, v, None)), (k, v)

    def suffix(self, y, kv_prefix, suffix_mask):
        """Suffix tokens attend to [cached prefix K/V ; their own K/V]."""
        q, k, v = self.act.qkv(y)
        k_all = torch.cat([kv_prefix[0], k], dim=2)
        v_all = torch.cat([kv_prefix[1], v], dim=2)
        T_p, T_s = kv_prefix[0].shape[2], y.shape[1]
        mask = torch.cat([torch.ones(T_s, T_p, dtype=torch.bool, device=y.device),
                          suffix_mask], dim=1)                     # [T_s, T_p + T_s]
        return self.act.finish(y, attention(q, k_all, v_all, mask))


def suffix_block_mask(horizon: int, device=None) -> torch.Tensor:
    """[1 + H, 1 + H] mask for [state, a_1..a_H]: the state token does not see the
    actions (it is its own block); actions see the state and each other."""
    m = torch.ones(1 + horizon, 1 + horizon, dtype=torch.bool, device=device)
    m[0, 1:] = False
    return m


# ============================================================================
# 3. Flow matching helpers
# ============================================================================

def sinusoidal_time_embedding(t: torch.Tensor, d: int, min_period: float = 4e-3,
                              max_period: float = 4.0) -> torch.Tensor:
    """Sine-cosine embedding of flow time t in [0, 1] (periods between min and max,
    as in openpi's posemb_sincos)."""
    frac = torch.linspace(0.0, 1.0, d // 2, device=t.device)
    period = min_period * (max_period / min_period) ** frac
    ang = t[:, None] * (2 * math.pi / period[None])
    return torch.cat([torch.sin(ang), torch.cos(ang)], dim=-1)


def sample_flow_time(batch: int, dist: str = "beta", s: float = 0.999) -> torch.Tensor:
    """Training flow times in this file's convention (t = 0 noise, t = 1 data).
    'beta':    t = s * (1 - u), u ~ Beta(1.5, 1)  -> more samples near the noisy end
               (pi0 appendix: p(tau) = Beta((s - tau)/s; 1.5, 1), s = 0.999)
    'uniform': t ~ U[0, 1)."""
    if dist == "uniform":
        return torch.rand(batch)
    u = torch.distributions.Beta(1.5, 1.0).sample((batch,))
    return s * (1.0 - u)


def gaussian_mixture_velocity(x: torch.Tensor, t: float, means, std: float,
                              weights=None) -> torch.Tensor:
    """EXACT marginal velocity v(x, t) = E[a - eps | x_t = x] for 1-D data
    a ~ sum_k w_k N(mu_k, std^2), eps ~ N(0, 1), x_t = (1 - t) eps + t a.
    This is what a perfectly trained flow model would predict. The guide's 1-D
    step-through widget uses the identical formula."""
    means = torch.as_tensor(means, dtype=x.dtype)
    K = means.numel()
    w = torch.full((K,), 1.0 / K, dtype=x.dtype) if weights is None else torch.as_tensor(weights, dtype=x.dtype)
    var = (1 - t) ** 2 + (t * std) ** 2                     # Var[x_t | component k]
    xm = x[..., None] - t * means                            # x - E[x_t | k]
    logp = torch.log(w) - 0.5 * xm ** 2 / var
    r = torch.softmax(logp, dim=-1)                          # responsibilities P(k | x_t)
    e_a = means + (t * std ** 2 / var) * xm                  # E[a   | x_t, k]
    e_eps = ((1 - t) / var) * xm                             # E[eps | x_t, k]
    return (r * (e_a - e_eps)).sum(-1)


def euler_integrate(v_fn, noise: torch.Tensor, n_steps: int, return_path: bool = False):
    """x <- x + v(x, t) * dt from t = 0 (noise) to t = 1 (action)."""
    x, dt, path = noise, 1.0 / n_steps, [noise]
    for i in range(n_steps):
        x = x + v_fn(x, i * dt) * dt
        path.append(x)
    return (x, path) if return_path else x


# ============================================================================
# 4. The pi0-style model
# ============================================================================

class Pi0(nn.Module):
    def __init__(
        self,
        img_size: int = 224, patch_size: int = 14, n_cams_max: int = 3,
        vision_depth: int = 2, vocab_size: int = 32000, max_text_len: int = 48,
        d_vlm: int = 256, d_action: int = 128, n_layers: int = 4,
        n_heads: int = 4, n_kv_heads: int = 1, head_dim: int = 64,
        state_dim: int = 14, action_dim: int = 14, horizon: int = 50,
    ):
        super().__init__()
        self.horizon, self.action_dim, self.state_dim = horizon, action_dim, state_dim
        self.d_action = d_action

        # Prefix side (VLM): image tokens + text tokens
        self.vision = VisionEncoder(img_size, patch_size, d_vlm, vision_depth, n_heads)
        self.tok_embed = nn.Embedding(vocab_size, d_vlm)
        max_prefix = n_cams_max * self.vision.n_patches + max_text_len
        self.prefix_pos = nn.Parameter(torch.zeros(1, max_prefix, d_vlm))
        nn.init.trunc_normal_(self.prefix_pos, std=0.02)

        # Suffix side (action expert): state token + H action tokens
        self.state_proj = nn.Linear(state_dim, d_action)
        self.action_in = nn.Linear(action_dim, d_action)
        self.action_time_mlp_in = nn.Linear(2 * d_action, d_action)   # pi0: MLP(concat(action, time))
        self.action_time_mlp_out = nn.Linear(d_action, d_action)
        self.suffix_pos = nn.Parameter(torch.zeros(1, 1 + horizon, d_action))
        nn.init.trunc_normal_(self.suffix_pos, std=0.02)

        self.layers = nn.ModuleList([MoTLayer(d_vlm, d_action, n_heads, n_kv_heads, head_dim)
                                     for _ in range(n_layers)])
        self.norm_out = nn.LayerNorm(d_action)
        self.action_out = nn.Linear(d_action, action_dim)

    # ---- prefix: run once per observation -------------------------------
    def embed_prefix(self, images, token_ids):
        x = torch.cat([self.vision(images), self.tok_embed(token_ids)], dim=1)
        return x + self.prefix_pos[:, :x.shape[1]]

    def run_prefix(self, images, token_ids) -> List[Tuple[torch.Tensor, torch.Tensor]]:
        """The expensive part. Returns the per-layer KV cache of the prefix."""
        x = self.embed_prefix(images, token_ids)
        cache = []
        for layer in self.layers:
            x, kv = layer.prefix(x)
            cache.append(kv)
        return cache

    # ---- suffix: run once per Euler step ---------------------------------
    def embed_suffix(self, state, x_t, t):
        a = self.action_in(x_t)                                              # [B, H, d_a]
        temb = sinusoidal_time_embedding(t, self.d_action)[:, None].expand_as(a)
        a = self.action_time_mlp_out(F.silu(self.action_time_mlp_in(torch.cat([a, temb], -1))))
        s = self.state_proj(state)[:, None]                                  # [B, 1, d_a]
        return torch.cat([s, a], dim=1) + self.suffix_pos

    def run_suffix(self, state, x_t, t, cache):
        """Velocity prediction for the noisy chunk x_t, reading the cached prefix."""
        y = self.embed_suffix(state, x_t, t)
        mask = suffix_block_mask(self.horizon, y.device)
        for layer, kv in zip(self.layers, cache):
            y = layer.suffix(y, kv, mask)
        return self.action_out(self.norm_out(y[:, 1:]))                      # drop the state token

    def velocity(self, images, token_ids, state, x_t, t):
        return self.run_suffix(state, x_t, t, self.run_prefix(images, token_ids))

    def forward_joint(self, images, token_ids, state, x_t, t):
        """Reference implementation WITHOUT the cache: one attention over the full
        [prefix ; suffix] sequence with the 3-block causal mask, each token using its
        own expert's weights. Must equal velocity() exactly (see the tests)."""
        x = self.embed_prefix(images, token_ids)
        y = self.embed_suffix(state, x_t, t)
        T_p, T_s = x.shape[1], y.shape[1]
        mask = torch.zeros(T_p + T_s, T_p + T_s, dtype=torch.bool, device=x.device)
        mask[:T_p, :T_p] = True                                              # prefix block
        mask[T_p:, :T_p] = True                                              # suffix sees prefix
        mask[T_p:, T_p:] = suffix_block_mask(self.horizon, x.device)
        for layer in self.layers:
            qp, kp, vp = layer.vlm.qkv(x)
            qs, ks, vs = layer.act.qkv(y)
            o = attention(torch.cat([qp, qs], 2), torch.cat([kp, ks], 2),
                          torch.cat([vp, vs], 2), mask)
            x, y = layer.vlm.finish(x, o[:, :, :T_p]), layer.act.finish(y, o[:, :, T_p:])
        return self.action_out(self.norm_out(y[:, 1:]))

    # ---- training ----------------------------------------------------------
    def compute_loss(self, batch: Dict[str, torch.Tensor], time_dist: str = "beta"):
        """Flow-matching loss. batch: images [B,N_cam,3,H,W], token_ids [B,T],
        state [B,state_dim], action [B,H,action_dim]."""
        a = batch["action"]
        B = a.shape[0]
        t = sample_flow_time(B, time_dist).to(a.device)
        eps = torch.randn_like(a)
        tt = t.view(B, 1, 1)
        x_t = (1 - tt) * eps + tt * a                 # straight line from noise (t=0) to data (t=1)
        v_target = a - eps                            # its constant velocity
        v_pred = self.velocity(batch["images"], batch["token_ids"], batch["state"], x_t, t)
        return F.mse_loss(v_pred, v_target)

    # ---- inference ---------------------------------------------------------
    @torch.no_grad()
    def generate_action(self, images, token_ids, state, n_steps: int = 10,
                        noise: Optional[torch.Tensor] = None):
        """Prefix once (KV cache), then n_steps Euler steps of the action expert."""
        B = images.shape[0]
        cache = self.run_prefix(images, token_ids)                         # expensive, ONCE
        x = noise if noise is not None else torch.randn(B, self.horizon, self.action_dim,
                                                        device=images.device)
        dt = 1.0 / n_steps
        for i in range(n_steps):
            t = torch.full((B,), i * dt, device=images.device)
            x = x + self.run_suffix(state, x, t, cache) * dt                 # cheap, n_steps times
        return x


# ============================================================================
# Model configs
# ============================================================================

def vla_small() -> Pi0:
    return Pi0(d_vlm=256, d_action=128, n_layers=4, n_heads=4, n_kv_heads=1, head_dim=64,
               vision_depth=2)


def vla_base() -> Pi0:
    return Pi0(d_vlm=512, d_action=256, n_layers=6, n_heads=8, n_kv_heads=1, head_dim=64,
               vision_depth=4)


# ============================================================================
# Analysis — the guide's calculator implements exactly pi0_cost()
# ============================================================================

def count_parameters(m: nn.Module) -> int:
    return sum(p.numel() for p in m.parameters() if p.requires_grad)


# Jetson memory bandwidth from NVIDIA's spec pages. Peak FP16 TFLOPS: Orin Nano Super
# uses NVIDIA's spec-table value (17); AGX Orin and Thor are DERIVED from the published
# sparse headline numbers (see the guide for the derivation).
DEVICES = {
    "orin_nano_super": {"bw_gbs": 102.0, "fp16_tflops": 17.0},
    "agx_orin_64gb": {"bw_gbs": 204.8, "fp16_tflops": 42.5},
    "agx_thor_t5000": {"bw_gbs": 273.0, "fp16_tflops": 259.0},
}


def pi0_cost(n_cams: int = 3, img_tokens: int = 256, text_tokens: int = 48,
             vision_params: float = 400e6, d_vlm: int = 2048, mlp_vlm: int = 16384,
             d_act: int = 1024, mlp_act: int = 4096, n_layers: int = 18, n_heads: int = 8,
             n_kv_heads: int = 1, head_dim: int = 256, horizon: int = 50, n_steps: int = 10,
             mlp_mats: int = 3, bytes_per_param: float = 2.0,
             bw_gbs: float = 204.8, tflops: float = 42.5) -> Dict[str, float]:
    """Analytic cost of ONE action chunk (defaults: pi0 = SigLIP-So400m + Gemma-2B +
    Gemma-300M expert, 3 cameras). FLOPs ~ 2 x params x tokens for every linear layer
    plus 4 x Tq x Tk x (heads*head_dim) per layer for attention. Embedding tables
    are excluded. Time floors are max(FLOPs / peak, bytes / bandwidth) per phase."""
    hq, hkv = n_heads * head_dim, n_kv_heads * head_dim
    p_vlm_layer = d_vlm * hq + 2 * d_vlm * hkv + hq * d_vlm + mlp_mats * d_vlm * mlp_vlm
    p_act_layer = d_act * hq + 2 * d_act * hkv + hq * d_act + mlp_mats * d_act * mlp_act
    P_llm, P_act = n_layers * p_vlm_layer, n_layers * p_act_layer
    T_img = n_cams * img_tokens
    T_p, T_s = T_img + text_tokens, 1 + horizon

    vision_flops = 2 * vision_params * T_img
    prefix_flops = 2 * P_llm * T_p + n_layers * 4 * T_p * T_p * hq
    step_flops = 2 * P_act * T_s + n_layers * 4 * T_s * (T_p + T_s) * hq
    kv_cache_bytes = n_layers * 2 * T_p * hkv * bytes_per_param
    prefix_bytes = (vision_params + P_llm) * bytes_per_param + kv_cache_bytes
    step_bytes = P_act * bytes_per_param + kv_cache_bytes

    peak, bw = tflops * 1e12, bw_gbs * 1e9
    t_prefix = max((vision_flops + prefix_flops) / peak, prefix_bytes / bw)
    t_step = max(step_flops / peak, step_bytes / bw)
    return {
        "T_prefix": T_p, "T_suffix": T_s,
        "params_llm": P_llm, "params_expert": P_act,
        "params_total": vision_params + P_llm + P_act,
        "vision_flops": vision_flops, "prefix_flops": prefix_flops,
        "step_flops": step_flops, "expert_flops": n_steps * step_flops,
        "total_flops": vision_flops + prefix_flops + n_steps * step_flops,
        "kv_cache_bytes": kv_cache_bytes, "prefix_bytes": prefix_bytes, "step_bytes": step_bytes,
        "prefix_intensity": (vision_flops + prefix_flops) / prefix_bytes,
        "step_intensity": step_flops / step_bytes,
        "ridge": peak / bw,
        "t_prefix_ms": 1e3 * t_prefix, "t_step_ms": 1e3 * t_step,
        "t_total_ms": 1e3 * (t_prefix + n_steps * t_step),
        "no_cache_total_ms": 1e3 * n_steps * (t_prefix + t_step),
    }


def print_model_summary(model: Pi0, name: str):
    vis = count_parameters(model.vision)
    tok = model.tok_embed.weight.numel()
    vlm = sum(count_parameters(l.vlm) for l in model.layers)
    act = sum(count_parameters(l.act) for l in model.layers)
    act_io = sum(count_parameters(m) for m in (model.state_proj, model.action_in,
                                                 model.action_time_mlp_in, model.action_time_mlp_out,
                                                 model.norm_out, model.action_out)) + model.suffix_pos.numel()
    total = count_parameters(model)
    print("=" * 64)
    print(f"{name}: pi0-style VLA ({len(model.layers)} shared-attention layers)")
    print("=" * 64)
    print(f"Vision encoder (stub SigLIP):     {vis:>12,}")
    print(f"Token embedding table:            {tok:>12,}")
    print(f"VLM weights in the {len(model.layers)} layers:      {vlm:>12,}")
    print(f"Action-expert weights in layers:  {act:>12,}")
    print(f"Action expert in/out + time MLP:  {act_io:>12,}")
    print("-" * 64)
    print(f"Total:                            {total:>12,}  ({total / 1e6:.2f}M)")
    print(f"horizon H = {model.horizon}, action_dim = {model.action_dim}")


def demo():
    print("\n" + "=" * 64)
    print("Forward pass demo (VLA-S)")
    print("=" * 64)
    torch.manual_seed(0)
    model = vla_small().eval()
    B, N_cam, T = 2, 3, 16
    batch = {
        "images": torch.randn(B, N_cam, 3, 224, 224),
        "token_ids": torch.randint(0, 32000, (B, T)),
        "state": torch.randn(B, 14),
        "action": torch.randn(B, model.horizon, model.action_dim),
    }
    with torch.no_grad():
        cache = model.run_prefix(batch["images"], batch["token_ids"])
    k0 = cache[0][0]
    print(f"1. Prefix tokens: {N_cam} x 256 image + {T} text = {k0.shape[2]}")
    print(f"   KV cache: {len(cache)} layers x K,V of {list(k0.shape)} "
          f"(1 KV head -> {sum(k.numel() + v.numel() for k, v in cache):,} numbers)")
    loss = model.compute_loss(batch)
    print(f"2. Flow-matching loss (untrained): {loss.item():.3f}")
    with torch.no_grad():
        x_t = torch.randn_like(batch["action"])
        t = torch.full((B,), 0.3)
        v_cached = model.velocity(batch["images"], batch["token_ids"], batch["state"], x_t, t)
        v_joint = model.forward_joint(batch["images"], batch["token_ids"], batch["state"], x_t, t)
        print(f"3. Cached-prefix velocity == joint-sequence velocity: "
              f"max |diff| = {(v_cached - v_joint).abs().max().item():.2e}")
        chunk = model.generate_action(batch["images"], batch["token_ids"], batch["state"])
    print(f"4. Generated action chunk: {list(chunk.shape)} (prefix once + 10 Euler steps)")

    # Flow matching on a 1-D bimodal "action": what Euler step counts do
    torch.manual_seed(1)
    noise = torch.randn(20000)
    v = lambda x, t: gaussian_mixture_velocity(x, t, means=(-1.0, 1.0), std=0.1)
    print("\n5. 1-D bimodal actions (-1 or +1), exact velocity field, Euler from noise:")
    for n in (1, 2, 4, 10, 50):
        x_end = euler_integrate(v, noise, n)
        near = ((x_end.abs() - 1).abs() < 0.3).float().mean().item()
        print(f"   {n:>2} steps: mean |x| = {x_end.abs().mean().item():.3f}, "
              f"{near * 100:5.1f}% land within 0.3 of a mode")
    print("   One step = predict E[a] = 0 for everyone: the average of two good actions is a bad one.")


if __name__ == "__main__":
    for name, fn in [("VLA-S", vla_small), ("VLA-B", vla_base)]:
        print_model_summary(fn(), name)
    demo()

    print("\n" + "=" * 64)
    print("pi0 cost model (3 cameras, FP16 weights) — the guide's calculator")
    print("=" * 64)
    c = pi0_cost()
    print(f"Params: LLM layers {c['params_llm'] / 1e9:.2f}B, expert layers "
          f"{c['params_expert'] / 1e6:.0f}M, + 0.4B vision = {c['params_total'] / 1e9:.2f}B "
          f"(embedding tables excluded)")
    print(f"Prefix: {c['T_prefix']} tokens, {(c['vision_flops'] + c['prefix_flops']) / 1e12:.2f} TFLOPs, "
          f"{c['prefix_bytes'] / 1e9:.2f} GB read  -> intensity {c['prefix_intensity']:.0f} FLOP/B")
    print(f"Each Euler step: {c['T_suffix']} tokens, {c['step_flops'] / 1e9:.1f} GFLOPs, "
          f"{c['step_bytes'] / 1e9:.2f} GB read -> intensity {c['step_intensity']:.0f} FLOP/B")
    for dev, spec in DEVICES.items():
        r = pi0_cost(bw_gbs=spec["bw_gbs"], tflops=spec["fp16_tflops"])
        print(f"  {dev:<16} floor: prefix {r['t_prefix_ms']:6.1f} ms + 10 x {r['t_step_ms']:5.2f} ms "
              f"= {r['t_total_ms']:6.1f} ms   (no KV cache: {r['no_cache_total_ms']:6.0f} ms)")
