File size: 26,366 Bytes
13189fb
3aa087b
13189fb
 
 
 
 
 
cc443b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3aa087b
 
c937ff4
 
13189fb
 
 
 
cc443b3
13189fb
 
cc443b3
 
 
 
13189fb
cc443b3
 
13189fb
 
 
 
 
 
 
cc443b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13189fb
 
cc443b3
13189fb
 
cc443b3
 
 
13189fb
 
cc443b3
 
 
 
 
 
 
 
13189fb
cc443b3
13189fb
cc443b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13189fb
 
cc443b3
 
13189fb
cc443b3
 
 
 
13189fb
cc443b3
 
 
 
 
 
 
13189fb
cc443b3
 
 
 
 
13189fb
cc443b3
 
 
 
 
 
 
 
 
 
 
 
13189fb
cc443b3
 
 
 
 
 
 
 
 
13189fb
 
cc443b3
 
 
13189fb
 
cc443b3
 
13189fb
cc443b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13189fb
 
cc443b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13189fb
cc443b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13189fb
cc443b3
 
 
 
 
 
c937ff4
 
 
 
 
cc443b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3aa087b
c937ff4
 
 
 
 
 
 
 
 
 
 
 
 
 
cc443b3
 
c937ff4
cc443b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13189fb
cc443b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13189fb
cc443b3
 
 
 
13189fb
 
cc443b3
 
 
 
3aa087b
cc443b3
13189fb
 
 
 
 
cc443b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3aa087b
cc443b3
 
 
 
 
 
 
 
 
 
 
 
 
 
c937ff4
cc443b3
 
 
 
 
 
 
 
 
 
 
 
 
 
13189fb
 
 
cc443b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13189fb
 
cc443b3
 
13189fb
 
cc443b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13189fb
 
cc443b3
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
# SPDX-License-Identifier: Apache-2.0
"""ASGI serving app for X-VLA (lerobot/xvla-base) on a Tenstorrent Blackhole p150.

Served by tt-model-manager as ``kind: tt-dit-server``::

    runtime:
      app: tt.server.app:app

uvicorn runs this module with ``--lifespan on``. Importing it is side-effect free
(stdlib, numpy, torch, fastapi, pydantic, PIL only); the device is opened, the 3.5 GB
checkpoint loaded, the on-chip modules swapped in and one warm-up chunk generated inside
the ASGI **lifespan**, so uvicorn's ``Application startup complete`` -- the line
``tt-model serve`` waits for -- means the chip is claimed and the kernels are compiled.

I/O: 3 camera views + language instruction + proprio state -> a 30 x 20 action chunk
(``ee6d`` action space: xyz, 6-D rotation, gripper, zero padding), raw model space.

Environment (read in the lifespan, never at import):

    HF_MODEL              weights repo id            (default lerobot/xvla-base; set by tt-model)
    TT_WEIGHTS_REVISION   commit sha of the weights  (default None = repo default branch)
    XVLA_WEIGHTS_DIR      local dir holding config.json + model.safetensors (overrides HF_MODEL)
    TT_MESH_SHAPE         "1x1" | "(1, 1)" | "1,1"  (anything else is refused: single chip only)
    TT_DEVICE_ID          chip id for ttnn.open_device (default 0)
    XVLA_TOKENIZER_PATH   dir with the facebook/bart-large tokenizer files (default: the copy
                          vendored under tt/assets/bart-large-tokenizer; falls back to the Hub id)
    XVLA_LANG_TOKENS      fixed language length in tokens (default 32; the port validated 16 and 32)
    XVLA_NUM_DENOISING_STEPS  default flow-matching steps (default 1 = the validated speed setting)
    XVLA_WARMUP           "1" (default) runs one warm-up chunk before READY; "0" skips it
    TT_FUSED              fused/traced device path (tt/fused.py), the default; "0" selects the
                          legacy path. With
                          TT_FUSED_TRACE=1 (default) the warm-up chunk captures the block-stack and
                          BART traces and READY is refused if they did not capture.
"""
from __future__ import annotations

import base64
import gc
import io
import os
import re
import sys
import threading
import time
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Any, Optional

import numpy as np
import torch
from fastapi import FastAPI, HTTPException
from PIL import Image
from pydantic import BaseModel, Field

# --------------------------------------------------------------------------------------
# Constants (from lerobot/xvla-base config.json at cdb7964e; re-read from the loaded
# config in the lifespan -- these are only the documented defaults).
# --------------------------------------------------------------------------------------
DEFAULT_WEIGHTS_REPO = "lerobot/xvla-base"
SOURCE_REPO = "https://github.com/changh95/tt-XVLA"
SOURCE_COMMIT = "a96e1f451d3dc520cf351f733bd7300572be8851"
IMAGE_SIZE = 224  # config.resize_imgs_with_padding
VIEW_KEYS = ("observation.images.image", "observation.images.image2", "observation.images.image3")
OBS_STATE_KEY = "observation.state"
OBS_LANGUAGE_TOKENS_KEY = "observation.language.tokens"
IMAGENET_MEAN = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
IMAGENET_STD = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
MAX_DENOISING_STEPS = 50
ASSETS_DIR = Path(__file__).resolve().parents[1] / "assets"
VENDORED_TOKENIZER_DIR = ASSETS_DIR / "bart-large-tokenizer"
TOKENIZER_HUB_ID = "facebook/bart-large"

STATE: dict[str, Any] = {}
_LOCK = threading.Lock()


def _log(msg: str) -> None:
    """Boot-checklist friendly logging: plain lines on stdout, flushed."""
    print(f"[xvla.server] {msg}", flush=True)


# --------------------------------------------------------------------------------------
# Env / config helpers
# --------------------------------------------------------------------------------------
def parse_mesh_shape(value: Optional[str]) -> tuple[int, int]:
    """Accept ``1x1``, ``(1, 1)``, ``1,1`` (tt-model exports ``RxC``); refuse anything else."""
    raw = "1x1" if value is None or not str(value).strip() else str(value)
    m = re.fullmatch(r"\s*\(?\s*(\d+)\s*[xX,]\s*(\d+)\s*\)?\s*", raw)
    if not m:
        raise RuntimeError(
            f"TT_MESH_SHAPE={raw!r} is not understood; expected '1x1', '(1, 1)' or '1,1'."
        )
    shape = (int(m.group(1)), int(m.group(2)))
    if shape != (1, 1):
        raise RuntimeError(
            f"TT_MESH_SHAPE={raw!r} is a multi-chip mesh; this port runs on ONE Blackhole "
            "chip (ttnn.open_device) and has no sharded variant."
        )
    return shape


def _env_int(name: str, default: int, lo: int, hi: int) -> int:
    try:
        v = int(os.environ.get(name, str(default)))
    except ValueError as e:
        raise RuntimeError(f"{name} must be an integer, got {os.environ.get(name)!r}") from e
    if not lo <= v <= hi:
        raise RuntimeError(f"{name}={v} outside [{lo}, {hi}]")
    return v


def _resolve_weights_dir(repo: str, revision: Optional[str], local_dir: Optional[str]) -> Path:
    """Directory holding ``config.json`` + ``model.safetensors`` at the pinned revision.

    ``tt-model serve`` pre-downloads the pinned snapshot into the HF cache mounted at
    ``/hf``; ``hf_hub_download`` with a commit-sha revision then returns the cached file
    without any network call. Anywhere else it downloads (or resolves the default branch
    when no revision is given).
    """
    if local_dir:
        d = Path(local_dir).expanduser()
        missing = [f for f in ("config.json", "model.safetensors") if not (d / f).is_file()]
        if missing:
            raise RuntimeError(f"XVLA_WEIGHTS_DIR={d} is missing {missing}")
        return d
    from huggingface_hub import hf_hub_download

    cfg = hf_hub_download(repo_id=repo, filename="config.json", revision=revision)
    hf_hub_download(repo_id=repo, filename="model.safetensors", revision=revision)
    # NOT .resolve(): the returned path is <cache>/snapshots/<sha>/config.json, a symlink
    # into blobs/ -- the snapshot dir is the one that holds both files by name.
    return Path(cfg).parent


def _load_tokenizer(path_or_id: str):
    from transformers import AutoTokenizer

    return AutoTokenizer.from_pretrained(path_or_id)


# --------------------------------------------------------------------------------------
# Preprocessing (mirrors lerobot 0.5.0 make_xvla_pre_post_processors + XVLAPolicy)
# --------------------------------------------------------------------------------------
def _decode_image(b64: str, idx: int) -> torch.Tensor:
    """base64 PNG/JPEG -> float32 [1, 3, H, W] in [0, 1] (XVLAImageToFloatProcessorStep)."""
    try:
        raw = base64.b64decode(b64, validate=True)
        im = Image.open(io.BytesIO(raw)).convert("RGB")
    except Exception as e:  # noqa: BLE001
        raise HTTPException(status_code=400, detail=f"images[{idx}]: not a decodable base64 PNG/JPEG ({e})") from None
    if im.width < 8 or im.height < 8:
        raise HTTPException(status_code=400, detail=f"images[{idx}]: {im.width}x{im.height} is too small")
    arr = np.asarray(im, dtype=np.uint8)  # H W 3
    t = torch.from_numpy(arr.copy()).permute(2, 0, 1).unsqueeze(0).float() / 255.0
    return t


def _imagenet_normalize(t: torch.Tensor) -> torch.Tensor:
    """XVLAImageNetNormalizeProcessorStep: (x - mean) / std on [0, 1] input."""
    return (t - IMAGENET_MEAN) / IMAGENET_STD


def _prepare_view(b64: str, idx: int, resize_with_pad) -> tuple[torch.Tensor, tuple[int, int]]:
    """One camera view -> normalised float32 [1, 3, 224, 224] exactly as the policy would see it.

    Order matches upstream: /255 -> ImageNet normalise -> ``resize_with_pad`` (aspect-
    preserving bilinear downscale, zero-pad top/left; zero in normalised space). Doing the
    resize here keeps every device tensor shape identical across requests.
    """
    t = _decode_image(b64, idx)
    orig = (t.shape[-1], t.shape[-2])  # (W, H)
    t = _imagenet_normalize(t)
    t = resize_with_pad(t, IMAGE_SIZE, IMAGE_SIZE)
    return t.contiguous(), orig


def _tokenize(tokenizer, text: str, max_length: int) -> torch.Tensor:
    """TokenizerProcessorStep: padding='max_length', right side, truncation; the policy
    reads only the token ids (the attention mask is ignored upstream too)."""
    out = tokenizer(
        text,
        max_length=max_length,
        truncation=True,
        padding="max_length",
        padding_side="right",
        return_tensors="pt",
    )
    return out["input_ids"].to(torch.long)


# --------------------------------------------------------------------------------------
# Lifespan: weights -> device -> on-chip swaps -> warm-up
# --------------------------------------------------------------------------------------
@asynccontextmanager
async def lifespan(_app: FastAPI):
    torch.set_grad_enabled(False)
    t_boot = time.perf_counter()

    parse_mesh_shape(os.environ.get("TT_MESH_SHAPE"))
    device_id = _env_int("TT_DEVICE_ID", 0, 0, 63)
    weights_repo = os.environ.get("HF_MODEL", DEFAULT_WEIGHTS_REPO) or DEFAULT_WEIGHTS_REPO
    revision = os.environ.get("TT_WEIGHTS_REVISION") or None
    local_dir = os.environ.get("XVLA_WEIGHTS_DIR") or None
    lang_tokens = _env_int("XVLA_LANG_TOKENS", 32, 4, 256)
    default_steps = _env_int("XVLA_NUM_DENOISING_STEPS", 1, 1, MAX_DENOISING_STEPS)
    do_warmup = os.environ.get("XVLA_WARMUP", "1") != "0"
    tok_path = os.environ.get("XVLA_TOKENIZER_PATH") or (
        str(VENDORED_TOKENIZER_DIR) if (VENDORED_TOKENIZER_DIR / "vocab.json").is_file() else TOKENIZER_HUB_ID
    )

    # 1. Weights + tokenizer on the host (cache hits when tt-model pre-downloaded them).
    _log(f"Loading weights ... repo={weights_repo} revision={revision} local_dir={local_dir}")
    weights_dir = _resolve_weights_dir(weights_repo, revision, local_dir)
    _log(f"Loading weights from {weights_dir} (model.safetensors 3.5 GB fp32 -> bf16)")
    tokenizer = _load_tokenizer(tok_path)
    _log(f"Tokenizer {type(tokenizer).__name__} from {tok_path}; language length {lang_tokens} tokens")

    # 2. The port module. Importing it runs ttnn_env.install() (TT_METAL_HOME / sys.path)
    #    and lerobot_bootstrap.install() (groot stub + transformers shim) -- it MUST be
    #    imported before anything imports ttnn or lerobot.policies, hence lazily here.
    import tt.policy as tt_policy  # noqa: E402
    from lerobot.policies.xvla.modeling_xvla import resize_with_pad  # noqa: E402

    os.environ["TT_DEVICE_ID"] = str(device_id)
    if tt_policy._TTNN_DEVICE is not None:
        raise RuntimeError("tt.policy already holds a device; refusing to double-open")

    # 3. Build: load_policy_ttnn loads the torch policy on CPU, then opens the device
    #    (ttnn.open_device(device_id=TT_DEVICE_ID), default kwargs -- the port's own
    #    recipe) and swaps the transformer blocks / BART encoder / DaViT FFN + attention
    #    onto the chip. Weights are uploaded with ttnn.from_torch at construction.
    policy = None
    try:
        policy = tt_policy.load_policy_ttnn(weights_dir)
        device = tt_policy._TTNN_DEVICE
        if device is None:
            raise RuntimeError("tt.policy.load_policy_ttnn returned without opening a device")
        policy.config.num_denoising_steps = default_steps
        cfg = policy.config
        fused = tt_policy.fused_status()
        if fused["config"]["enabled"]:
            _log(f"TT_FUSED path (default; TT_FUSED=0 = legacy): {fused['config']}")
        else:
            _log("TT_FUSED=0: legacy device path")
        state_dim_default = int(cfg.robot_state_feature.shape[0]) if cfg.robot_state_feature is not None else 8
        _log(
            f"Policy ready: chunk_size={cfg.chunk_size} action_dim={policy.model.dim_action} "
            f"max_state_dim={cfg.max_state_dim} views={cfg.num_image_views} domains={cfg.num_domains} "
            f"dtype={cfg.dtype} steps={cfg.num_denoising_steps} ({time.perf_counter() - t_boot:.0f}s)"
        )

        STATE.update(
            policy=policy,
            device=device,
            device_id=device_id,
            tokenizer=tokenizer,
            resize_with_pad=resize_with_pad,
            weights_repo=weights_repo,
            revision=revision,
            weights_dir=str(weights_dir),
            tokenizer_path=tok_path,
            lang_tokens=lang_tokens,
            default_steps=default_steps,
            chunk_size=int(cfg.chunk_size),
            n_action_steps=int(cfg.n_action_steps),
            action_dim=int(policy.model.dim_action),
            max_state_dim=int(cfg.max_state_dim),
            state_dim_default=state_dim_default,
            num_views=int(cfg.num_image_views or len(VIEW_KEYS)),
            num_domains=int(cfg.num_domains),
            action_mode=str(cfg.action_mode),
        )

        # 4. Warm-up: one chunk on a fixed dummy batch with the exact shapes every request
        #    uses, so the kernel JIT (minutes on a cold /cache) happens before READY.
        if do_warmup:
            _log("Warming up ... (1 action chunk on a synthetic batch; JIT-compiles kernels)")
            t0 = time.perf_counter()
            dummy_png = _dummy_png_b64()
            batch, _ = _build_batch(
                images=[dummy_png] * STATE["num_views"],
                instruction="warm up",
                state=[0.0] * state_dim_default,
                domain_id=0,
            )
            with _LOCK, torch.inference_mode():
                torch.manual_seed(0)
                out = policy.predict_action_chunk(batch)
                policy.reset()
            if not torch.isfinite(out.float()).all():
                raise RuntimeError("warm-up produced non-finite actions")
            _log(
                f"Warmup complete: actions {tuple(out.shape)} in {time.perf_counter() - t0:.1f}s "
                f"(boot {time.perf_counter() - t_boot:.0f}s)"
            )
            # TT_FUSED=1 + TT_FUSED_TRACE=1: READY means "traces captured". The warm-up
            # chunk ran the block stack (eager warm run -> capture -> replay) and the BART encoder
            # the same way; a module that fell back to eager (capture failed) refuses READY so the
            # device pass sees it instead of serving a slower graph silently. TT_FUSED_TRACE=0
            # serves the fused graph eagerly and skips this gate.
            fused = tt_policy.fused_status()
            if fused["config"]["enabled"]:
                for name, mod in fused["modules"].items():
                    _log(f"TT_FUSED module {name}: {mod}")
                if fused["config"]["trace"] and not fused.get("all_traces_captured"):
                    raise RuntimeError(
                        "TT_FUSED=1: a metal trace was not captured during warm-up "
                        f"({fused['modules']}); fix the capture or serve eagerly with TT_FUSED_TRACE=0"
                    )
            STATE["fused"] = fused
        else:
            _log("Warmup skipped (XVLA_WARMUP=0); the first request compiles the kernels")
            STATE["fused"] = tt_policy.fused_status()
        STATE["ready"] = True
        yield
    finally:
        STATE["ready"] = False
        _log("Shutting down: releasing the policy and closing the device")
        STATE.pop("policy", None)
        del policy
        gc.collect()
        dev = tt_policy._TTNN_DEVICE
        tt_policy._TTNN_DEVICE = None
        STATE.clear()
        if dev is not None:
            import ttnn

            ttnn.close_device(dev)
        _log("Device closed")


def _dummy_png_b64() -> str:
    im = Image.fromarray(np.full((256, 256, 3), 127, dtype=np.uint8))
    buf = io.BytesIO()
    im.save(buf, format="PNG")
    return base64.b64encode(buf.getvalue()).decode("ascii")


def _build_batch(
    images: list[str], instruction: str, state: list[float], domain_id: int
) -> tuple[dict[str, torch.Tensor], list[tuple[int, int]]]:
    """Client fields -> the exact batch dict ``XVLAPolicy.predict_action_chunk`` expects,
    plus the original (W, H) of every view."""
    rwp = STATE["resize_with_pad"]
    batch: dict[str, torch.Tensor] = {}
    sizes: list[tuple[int, int]] = []
    for i, (key, b64) in enumerate(zip(VIEW_KEYS, images)):
        t, orig = _prepare_view(b64, i, rwp)
        batch[key] = t
        sizes.append(orig)
    batch[OBS_STATE_KEY] = torch.tensor(state, dtype=torch.float32).view(1, -1)
    batch[OBS_LANGUAGE_TOKENS_KEY] = _tokenize(STATE["tokenizer"], instruction, STATE["lang_tokens"])
    batch["domain_id"] = torch.tensor([int(domain_id)], dtype=torch.long)
    return batch, sizes


app = FastAPI(title="X-VLA (lerobot/xvla-base) on Tenstorrent Blackhole", lifespan=lifespan)


# --------------------------------------------------------------------------------------
# Schemas
# --------------------------------------------------------------------------------------
class PredictRequest(BaseModel):
    """One observation -> one action chunk.

    ``images``: base64 PNG/JPEG camera views. Send exactly 3 (slots ``image``, ``image2``
    = third-person cams trained at 256x256, ``image3`` = wrist cam at 224x224) or exactly 1
    (copied into all three slots -- the single-camera trick from ``eval/README.md``).
    Any resolution; each view is ImageNet-normalised and resize_with_pad'ed to 224x224.
    ``image`` is a legacy alias for a single view.
    """

    images: Optional[list[str]] = None
    image: Optional[str] = None
    instruction: Optional[str] = Field(default=None, description="natural-language task, e.g. 'push the T'")
    task: Optional[str] = Field(default=None, description="alias of instruction (lerobot's key name)")
    state: Optional[list[float]] = Field(
        default=None,
        description="proprio state, 1..20 floats (base checkpoint: 8; zero-padded to 20). Default: 8 zeros.",
    )
    domain_id: int = Field(default=0, ge=0, description="X-VLA domain id (0..num_domains-1, default 0)")
    num_denoising_steps: Optional[int] = Field(
        default=None, ge=1, le=MAX_DENOISING_STEPS,
        description="flow-matching steps; default 1 (validated speed setting), upstream default 10",
    )
    seed: Optional[int] = Field(default=None, description="torch.manual_seed before sampling the flow-matching noise")


# --------------------------------------------------------------------------------------
# Routes
# --------------------------------------------------------------------------------------
@app.get("/health")
def health() -> dict:
    ready = bool(STATE.get("ready"))
    return {
        "status": "ok" if ready else "starting",
        "model": "xvla-base",
        "device": f"Tenstorrent Blackhole p150 (ttnn device id {STATE.get('device_id', os.environ.get('TT_DEVICE_ID', '0'))})",
    }


@app.get("/info")
def info() -> dict:
    return {
        "model": "X-VLA (lerobot/xvla-base): Florence-2 + SoftPromptedTransformer VLA, base checkpoint",
        "task": "vision-language-action: 3 camera views + instruction + proprio state -> 30x20 action chunk",
        "io": {
            "request": {
                "images": "1 or 3 base64 PNG/JPEG views (any size; resize_with_pad to 224x224 server-side)",
                "instruction": f"text, tokenized with facebook/bart-large to a fixed {STATE.get('lang_tokens', 32)} tokens",
                "state": f"1..{STATE.get('max_state_dim', 20)} floats (default: {STATE.get('state_dim_default', 8)} zeros)",
                "domain_id": f"0..{STATE.get('num_domains', 30) - 1} (default 0)",
                "num_denoising_steps": f"1..{MAX_DENOISING_STEPS} (default {STATE.get('default_steps', 1)})",
                "seed": "optional int",
            },
            "response": {
                "actions": f"[{STATE.get('chunk_size', 30)}][{STATE.get('action_dim', 20)}] float32, raw model space ({STATE.get('action_mode', 'ee6d')})",
                "normalized": False,
            },
        },
        "hardware": "Tenstorrent Blackhole p150, single chip, tt-nn (bf16 activations, bfp8_b MLP weights)",
        "on_device": [
            "SoftPromptedTransformer 24 blocks",
            "Florence-2 BART encoder 12 layers",
            "DaViT FFN x24, ChannelAttention x12, WindowAttention x12",
        ],
        "on_cpu": ["DaViT ConvEmbed + depthwise conv", "embedding lookups", "window partition/reverse", "flow-matching loop"],
        "weights": {
            "repo": STATE.get("weights_repo", os.environ.get("HF_MODEL", DEFAULT_WEIGHTS_REPO)),
            "revision": STATE.get("revision", os.environ.get("TT_WEIGHTS_REVISION")),
            "local_dir": STATE.get("weights_dir"),
            "license": "Apache-2.0 (lerobot/xvla-base)",
        },
        "tokenizer": {"name": TOKENIZER_HUB_ID, "path": STATE.get("tokenizer_path"), "max_length": STATE.get("lang_tokens", 32)},
        "source": {"repo": SOURCE_REPO, "commit": SOURCE_COMMIT},
        "fused": STATE.get("fused", {"config": {"enabled": False}}),
        "limits": {
            "image_size": [IMAGE_SIZE, IMAGE_SIZE],
            "views": [1, STATE.get("num_views", 3)],
            "max_state_dim": STATE.get("max_state_dim", 20),
            "batch": 1,
            "chunk_size": STATE.get("chunk_size", 30),
            "action_dim": STATE.get("action_dim", 20),
        },
        "notes": [
            "Base (non-fine-tuned) checkpoint: no dataset stats ship, so actions are raw model-space "
            "ee6d values (xyz, 6-D rotation, gripper, padding) and are not directly usable on a robot.",
            "num_denoising_steps=1 costs <0.05% open-loop PCC vs 10 steps; closed-loop use usually wants 4-10.",
        ],
        "status": "ok" if STATE.get("ready") else "starting",
    }


@app.get("/v1/models")
def v1_models() -> dict:
    return {
        "object": "list",
        "data": [{"id": STATE.get("weights_repo", os.environ.get("HF_MODEL", DEFAULT_WEIGHTS_REPO)), "object": "model", "owned_by": "changh95"}],
    }


@app.post("/reset")
def reset() -> dict:
    policy = STATE.get("policy")
    if policy is None or not STATE.get("ready"):
        raise HTTPException(status_code=503, detail="model is still starting")
    with _LOCK:
        policy.reset()
    return {"status": "reset"}


@app.post("/predict")
def predict(req: PredictRequest) -> dict:
    policy = STATE.get("policy")
    if policy is None or not STATE.get("ready"):
        raise HTTPException(status_code=503, detail="model is still starting")

    # ---- validate ----
    images = list(req.images) if req.images else ([req.image] if req.image else [])
    if len(images) == 1:
        views_used = ["image", "image2", "image3"]
        images = images * STATE["num_views"]
        replicated = True
    elif len(images) == STATE["num_views"]:
        views_used = ["image", "image2", "image3"][: STATE["num_views"]]
        replicated = False
    else:
        raise HTTPException(
            status_code=400,
            detail=f"send exactly 1 or {STATE['num_views']} images (got {len(images)}); 1 view is copied into every slot",
        )
    instruction = (req.instruction or req.task or "").strip()
    if not instruction:
        raise HTTPException(status_code=400, detail="instruction (or task) is required, e.g. 'push the T'")
    state = req.state if req.state is not None else [0.0] * STATE["state_dim_default"]
    if not 1 <= len(state) <= STATE["max_state_dim"]:
        raise HTTPException(status_code=400, detail=f"state must have 1..{STATE['max_state_dim']} floats (got {len(state)})")
    if not all(np.isfinite(state)):
        raise HTTPException(status_code=400, detail="state must be finite")
    if not 0 <= req.domain_id < STATE["num_domains"]:
        raise HTTPException(status_code=400, detail=f"domain_id must be in 0..{STATE['num_domains'] - 1}")
    steps = req.num_denoising_steps or STATE["default_steps"]

    # ---- preprocess (CPU) ----
    t0 = time.perf_counter()
    batch, sizes = _build_batch(images, instruction, [float(v) for v in state], req.domain_id)
    t1 = time.perf_counter()

    # ---- inference (one device, one policy -> serialised) ----
    with _LOCK:
        prev_steps = policy.config.num_denoising_steps
        try:
            policy.config.num_denoising_steps = int(steps)
            if req.seed is not None:
                torch.manual_seed(int(req.seed))
            try:
                with torch.inference_mode():
                    actions = policy.predict_action_chunk(batch)
            except Exception as e:  # noqa: BLE001
                raise HTTPException(status_code=500, detail=f"{type(e).__name__}: {e}") from e
        finally:
            policy.config.num_denoising_steps = prev_steps
    t2 = time.perf_counter()

    out = actions.detach().to(torch.float32).cpu()
    if out.ndim == 3:
        out = out[0]
    if not torch.isfinite(out).all():
        raise HTTPException(status_code=500, detail="model produced non-finite actions")

    return {
        "actions": out.tolist(),
        "chunk_size": int(out.shape[0]),
        "n_action_steps": STATE["n_action_steps"],
        "action_dim": int(out.shape[1]),
        "action_space": STATE["action_mode"],
        "normalized": False,
        "note": (
            "raw model-space actions from the base checkpoint (no dataset stats -> the MEAN_STD "
            "un-normaliser is identity); layout ee6d = xyz(3), rotation6d(6), gripper(1), zero padding"
        ),
        "num_denoising_steps": int(steps),
        "seed": req.seed,
        "domain_id": req.domain_id,
        "instruction": instruction,
        "language_tokens": STATE["lang_tokens"],
        "state_dim": len(state),
        "views_used": views_used,
        "single_view_replicated": replicated,
        "input_size": [IMAGE_SIZE, IMAGE_SIZE],
        "image_sizes": [{"width": w, "height": h} for (w, h) in sizes],
        "timing_ms": {
            "preprocess": round((t1 - t0) * 1000.0, 2),
            "inference": round((t2 - t1) * 1000.0, 2),
            "total": round((t2 - t0) * 1000.0, 2),
        },
    }


if __name__ == "__main__":  # pragma: no cover - convenience for host runs
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "20000")), lifespan="on")
    sys.exit(0)