File size: 4,869 Bytes
23d1b53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Write the stored CPU-reference output of the shipped sample (no device; ~10 GB of host RAM, about a minute).

    python code/scripts/make_sample_reference.py --weights-dir <lerobot/VLA-JEPA-Pretrain snapshot> \
        [--official <official fp32 golden run_*.pt of the same request>]

The sample (``code/tt_vla_jepa/samples/libero_spatial_ep0_f40``: two PNG cameras and their task) goes through the
fp32 CPU reference of this package (``tt_vla_jepa.reference.pipeline.VLAJEPAReference``: the same host
pre-processing, the full network in fp32, the checkpoint's post-processing) with the default seed 0. The result is
``samples/libero_spatial_ep0_f40/reference.json``, the output gate of ``server/smoke_test.py`` and of
``tests/test_e2e_device.py``. With ``--official`` the official LeRobot 0.7.0 fp32 output of the same request (same
images, task and initial noise) is stored next to it for comparison.
"""
from __future__ import annotations

import argparse
import json
import os
import sys
import time
from pathlib import Path

CODE = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(CODE))


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument("--weights-dir", required=True, help="local snapshot of lerobot/VLA-JEPA-Pretrain")
    ap.add_argument("--tokenizer-dir", default=None, help="default: the packaged Qwen3-VL tokenizer")
    ap.add_argument("--official", default=None, help="official fp32 run of the same request (torch .pt, read with "
                                                     "weights_only=True)")
    ap.add_argument("--out", default=None)
    ap.add_argument("--threads", type=int, default=8)
    a = ap.parse_args()
    import numpy as np
    import torch

    from tt_vla_jepa import io as tio
    from tt_vla_jepa.api import BUCKETS, DEFAULT_SEED, SAMPLE_DIR, VLAJEPA, load_sample, resolve_tokenizer_dir
    from tt_vla_jepa.reference import preprocess as pp
    from tt_vla_jepa.reference.config import CHECKPOINTS
    from tt_vla_jepa.reference.golden import pcc
    from tt_vla_jepa.reference.pipeline import VLAJEPAReference

    torch.set_num_threads(a.threads)
    sample = load_sample()
    images = [tio.load_image(p) for p in sample["images"]]
    noise = VLAJEPA.make_noise(DEFAULT_SEED)
    tok_dir = str(resolve_tokenizer_dir(a.tokenizer_dir))
    t0 = time.perf_counter()
    ref = VLAJEPAReference("pretrain", ckpt_dir=a.weights_dir, qwen_dir=tok_dir)
    out = ref(images, sample["instruction"], None, noise)
    a_norm, a_phys = out["actions_norm"].reshape(7, 7), out["actions"].reshape(7, 7)
    seconds = time.perf_counter() - t0
    grid = torch.tensor([[1, 16, 16]] * 2, dtype=torch.long)
    pre = pp.build_prefix_inputs(ref.tokenizer, sample["instruction"], grid, None, True, ref.cfg, "after_vision",
                                 buckets=BUCKETS)
    body = {
        "model": "vla-jepa-base-p150", "checkpoint": CHECKPOINTS["pretrain"].repo,
        "revision": CHECKPOINTS["pretrain"].revision,
        "source": "fp32 CPU reference of this package (tt_vla_jepa.reference.pipeline.VLAJEPAReference)",
        "request": {"sample": SAMPLE_DIR.name, "images": [Path(p).name for p in sample["images"]],
                    "instruction": sample["instruction"], "seed": DEFAULT_SEED},
        "actions": a_phys.tolist(), "actions_normalized": a_norm.tolist(),
        "normalized": False, "chunk_shape": [7, 7], "prompt_bucket": int(pre.input_ids.numel()),
        "num_tokens": int(pre.valid.sum()), "image_sizes": [list(im.shape[:2]) for im in images],
        "seconds": round(seconds, 1), "torch": torch.__version__, "numpy": np.__version__,
    }
    if a.official:
        g = torch.load(a.official, map_location="cpu", weights_only=True)
        if not torch.equal(g["noise"].reshape(1, 7, 7), noise):
            raise SystemExit("the official run used another initial noise")
        body["official_fp32"] = {
            "source": "LeRobot 0.7.0 VLA-JEPA policy (predict_action_chunk) on CPU in fp32, same images, task and "
                      "initial noise",
            "actions_normalized": g["actions_norm"][0].tolist(), "actions": g["actions"][0].tolist(),
            "pcc_vs_reference": pcc(a_norm, g["actions_norm"][0]),
            "max_abs_vs_reference": float((a_norm - g["actions_norm"][0]).abs().max()),
        }
    path = Path(a.out) if a.out else SAMPLE_DIR / "reference.json"
    path.write_text(json.dumps(body, indent=1) + "\n")
    print(f"wrote {path} in {seconds:.1f} s: bucket {body['prompt_bucket']}, {body['num_tokens']} prompt rows"
          + (f", PCC vs official {body['official_fp32']['pcc_vs_reference']:.8f}" if a.official else ""))
    return 0


if __name__ == "__main__":
    os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
    sys.exit(main())