Add A20 batch-512 trim-v2 step-4000 checkpoint
Browse filesFiles changed (11)
- README.mdAdded+50
- a20-basket-transfer/b512-trimv2/step-004000/SHA256SUMSAdded+9
- a20-basket-transfer/b512-trimv2/step-004000/config.jsonAdded+884
- a20-basket-transfer/b512-trimv2/step-004000/model.ptAdded+3
- a20-basket-transfer/b512-trimv2/step-004000/protocol.jsonAdded+11
- code/hb_baselines_v1/baselines/__init__.pyAdded+8
- code/hb_baselines_v1/baselines/act_nets.pyAdded+615
- code/hb_baselines_v1/baselines/nets.pyAdded+207
- code/hb_baselines_v1/baselines/policies.pyAdded+281
- code/hb_baselines_v1/baselines/requirements.txtAdded+12
- code/hb_baselines_v1/baselines/runtime.pyAdded+123
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950---tags:- robotics- humanoid- imitation-learning- flow-matching---# FM-DiT — Humanoid Benchmark
Flow-matching Diffusion Transformer checkpoints trained on Humanoid Benchmark tasks.The A20 policy uses a ResNet18 image encoder and an AdaLN DiT action backbone(hidden dimension 384, 4 layers, 8 attention heads), with 10 midpoint sampling steps.
## A20 pre-reach trim v2, batch 512, step 4000 (2026-11-17)
Checkpoint: [`a20-basket-transfer/b512-trimv2/step-004000/`](a20-basket-transfer/b512-trimv2/step-004000).
Trained on 100 demonstrations (54,433 frames) from`humanoid-benchmark/a20-basket-transfer-pre-reach-trim-expert-v2`, with batch size 512,4,000 optimizer steps, seed 0, EMA weights (decay 0.9999), and Humanoid Benchmarkaugmentation v2. These weights use the `hb_baselines/1` format.
Inputs: Unitree G1 state44 and separate `ego_view` and `chest` RGB images, resizedto 168 x 224. Output: 16 actions of dimension 76 (64 SONIC motion-token values and6 measured values for each INSPIRE hand). Normalization is stored in the weights.The ResNet18 visual backbone was initialized with ImageNet weights and fine-tuned.
The checkpoint contains `model.pt`, `config.json` and `protocol.json` (weight sizeand SHA-256). `SHA256SUMS` covers the checkpoint and the accompanying inferencesource snapshot. The snapshot is under `code/hb_baselines_v1/`; its requirementsrecord the training environment. Optimizer/resume state is excluded.
After downloading this repository and installing its inference dependencies,load the checkpoint from the repository root:
```pythonimport syssys.path.insert(0, 'code/hb_baselines_v1')from baselines.runtime import BaselinePolicy
policy = BaselinePolicy( 'a20-basket-transfer/b512-trimv2/step-004000', device='cpu', policy='fm_dit', robot='g1',)print(policy.info())```
The saved weights passed SHA-256 verification and strict CPU loading before upload.The offline metrics in `config.json` use training frames; they are not held-outor closed-loop task success rates.123456789636958d8eabe7dc28647a0100c346ef84f489b28da180a85d3386126b499a633 a20-basket-transfer/b512-trimv2/step-004000/config.json4c4ae7d2d53b4f17346dc75adf8c5d47d2cd8e63d099c54022b868499f0b0a4c a20-basket-transfer/b512-trimv2/step-004000/model.pt67840d199f99f3e23b7a7ab031268d5207abb1ceed99219610ee6c1127a1fe51 a20-basket-transfer/b512-trimv2/step-004000/protocol.json0a8ee3ccab6e183804c08066a9e7eb207d9b13ca38c0e596ce5d58c8302d7929 code/hb_baselines_v1/baselines/__init__.py3db95cd8e4e436875e11f1054a99d250ca7d94e0127909090b58730402340f19 code/hb_baselines_v1/baselines/act_nets.py38a66937bb92393a3f1ce0644b249da28d582a4fd03d134b7743e6037abd88b9 code/hb_baselines_v1/baselines/nets.py750d4c6193aabcacc0f53df26c2c51f64b3f836b940b32ccb5c69f5959419afa code/hb_baselines_v1/baselines/policies.pybb211f66038e53efd08ee3ec03e133d8bb206ec36cc608d349b4fad3a61e874b code/hb_baselines_v1/baselines/requirements.txt5d680d59124ca83f9c2088f8e1738395b87ddc58798acf7815e163102738b7ae code/hb_baselines_v1/baselines/runtime.py123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884{ "policy": { "policy": "fm_dit", "n_cameras": 2, "state_dim": 44, "action_dim": 76, "horizon": 16, "backbone": "resnet18", "backbone_weights": "IMAGENET1K_V1", "backbone_norm": "frozen_bn", "hidden_dim": 384, "num_layers": 4, "num_heads": 8, "mlp_ratio": 4.0, "dropout": 0.1, "time_embed_dim": 128, "num_inference_steps": null, "num_train_timesteps": 100, "beta_schedule": "squaredcos_cap_v2", "prediction_type": "epsilon", "clip_sample": true, "act_hidden_dim": 512, "dim_feedforward": 3200, "enc_layers": 4, "dec_layers": 7, "nheads": 8, "latent_dim": 32, "kl_weight": 10.0, "extra": {} }, "contract": { "name": "g1_sonic_dfx6", "robot": "g1", "cameras": [ "ego_view", "chest" ], "state": [ [ "observation.state", 0, 29 ], [ "observation.inspire_left_hand_state", 0, 6 ], [ "observation.inspire_right_hand_state", 0, 6 ], [ "observation.projected_gravity", 0, 3 ] ], "action": [ [ "action.motion_token", 0, 64 ], [ "observation.inspire_left_hand_state", 0, 6 ], [ "observation.inspire_right_hand_state", 0, 6 ] ], "state_dim": 44, "action_dim": 76, "action_space": "sonic_dfx6", "body_dims": 29 }, "image_hw": [ 168, 224 ], "task_text": "Grasp the basket handle with the right hand from the v10 round table, walk while raising it, place and release it on the long desk, then withdraw the open right hand diagonally backward and upward without an additional downward arm return.", "dataset": { "name": "a20-basket-transfer-pre-reach-trim-expert-v2", "root": "/mnt/data0/zuo/Humanoid_benchmark/data/baselines/a20-basket-transfer-pre-reach-trim-expert-v2", "robot_type": null, "fps": 30.0, "episodes": [ 0, 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 ], "train_episodes": [ 0, 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 ], "val_episodes": [], "train_frames": 54433, "git_commit": null }, "training": { "steps": 4000, "batch_size": 512, "lr": 0.0001, "betas": [ 0.95, 0.999 ], "weight_decay": 1e-06, "warmup": 500, "schedule": "linear warm-up + cosine", "backbone_lr_scale": 0.1, "ema": 0.9999, "shift_px": 0, "amp": true, "seed": 0, "augmentation": { "spec": "docs/augmentation_v2.md", "version": "hb-aug-v2-20261109", "implementation": "evaluation/augmentation/hb_aug_v2.py", "visual": { "effects": [ "exposure", "contrast", "saturation", "hue", "gamma", "temperature", "rotation_crop", "noise", "gaussian_blur", "jpeg", "motion_blur", "sharpen", "defocus", "light_shadow", "wb_channel" ], "boosted_per_sample": 1, "boost": 1.5, "pixel_scale": "H / 224", "future_targets": "none (one observation frame)" }, "proprio": { "robot": "g1", "body_dims": 29, "bias_deg": 2.0, "bias_scope": "per_sample", "noise_deg": 0.25, "noise_clip_sigma": 3, "delay_probability": 0.0, "history_drop_probability": 0.0, "velocity": false }, "native_image_augmentation": "off", "evaluation": "off" }, "preflight": { "samples": 64, "state_dim": 44, "body_dims": 29, "images_changed": 64, "body_values_moved": 1.0, "max_body_offset_deg": 2.5853, "actions_bit_identical": true, "non_body_state_bit_identical": true, "eval_items_deterministic": 8 } }, "stats": { "state": { "min": [ -0.6335107088088989, -0.26151371002197266, -0.09143047779798508, 0.13051827251911163, -0.41364213824272156, -0.17374181747436523, -0.5706103444099426, -0.4567093253135681, -0.5945078730583191, 0.07693764567375183, -0.479587197303772, -0.23942920565605164, -0.1249256581068039, -0.061801809817552567, 0.03293042629957199, -0.15965673327445984, 0.12444422394037247, -1.0301204919815063, 0.8110364079475403, -0.42373916506767273, -0.2393926978111267, -0.1671462506055832, -1.8559280633926392, -2.1003689765930176, -0.44611114263534546, -0.86998051404953, -1.5242679119110107, -0.9486506581306458, -0.4465007185935974, 0.9997791647911072, 0.9987788796424866, 0.9989608526229858, 0.9997321963310242, 0.8891316056251526, 0.9935978651046753, 0.3987571895122528, 0.39748135209083557, 0.3998531103134155, 0.47865480184555054, 0.43634313344955444, 0.0, -0.1312161237001419, -0.10554340481758118, -1.0 ], "max": [ 0.18651676177978516, 0.2880381643772125, 0.3991033434867859, 1.1868021488189697, 0.30963531136512756, 0.25351187586784363, 0.13313187658786774, 0.14919418096542358, 0.09004810452461243, 1.1367807388305664, 0.47997909784317017, 0.1897573471069336, 0.12687286734580994, 0.0903186947107315, 0.2110750675201416, 0.1764557808637619, 0.3972950279712677, -0.03375900536775589, 1.248238205909729, 0.5087170004844666, 0.16197925806045532, 0.19902198016643524, 0.7476708292961121, -0.14924407005310059, 1.3937729597091675, 1.4777758121490479, 1.449870228767395, 0.9068933725357056, 1.5030572414398193, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.1443370282649994, 0.07133471965789795, -0.9889927506446838 ], "mean": [ -0.1197492680031697, 0.07687621598947185, 0.13623676943730387, 0.27067508540983654, -0.09364010490166123, -0.029264338937400346, -0.0877177892591824, -0.09172362643767557, -0.21603681153788365, 0.27020221177162185, -0.13314246080400155, 0.01521604484593622, -0.007014541196278249, 0.023597627586334522, 0.1362211304918607, 0.0044590163081436405, 0.24020097902181153, -0.5506130059849405, 0.986759154493458, -0.11353825983460156, -0.09008970046721287, 0.00793797976488734, -0.7956446111257796, -0.6433268364566035, 0.35943391980855405, 0.4128302732079997, -0.6341984046200151, 0.17366417734106818, 0.31817584543570415, 0.9999920738393157, 0.9999916277741105, 0.9999916507452171, 0.9999910946907014, 0.9975380262153739, 0.9997842168412904, 0.7431049855982732, 0.743061001937713, 0.7431612987122399, 0.7812160503121215, 0.7544858488771042, 0.1884228588481359, -0.018600662889153487, -0.001923185563505277, -0.9992875029526394 ], "std": [ 0.1225902736805545, 0.0667315519538753, 0.06966628355722553, 0.1683343132651939, 0.11676670853146011, 0.06393707008498987, 0.14262675997248406, 0.07183651035230894, 0.07077858012951907, 0.1583747884788023, 0.09609718753190293, 0.06937572380392895, 0.038858334068535276, 0.01853271444550659, 0.019156535689633315, 0.04755913941308977, 0.041089601727671066, 0.14354888870689778, 0.053966848435702465, 0.13684428975351073, 0.05453949581291963, 0.06076597347825228, 0.6370602259123855, 0.4013113120474627, 0.24111485368872668, 0.5381053688248473, 0.48085827035516315, 0.1527991524681821, 0.44871163018722837, 1.2824078270394207e-05, 2.1003630589963823e-05, 1.8574155779181667e-05, 1.5382720229173254e-05, 0.0031309164055460465, 0.0001241612656891375, 0.2938442161025196, 0.29381668166139846, 0.29367033348300187, 0.25040401472179635, 0.2708879748387615, 0.3732468841625382, 0.027734659598288042, 0.01745881392269428, 0.0008838855519788744 ] }, "action": { "min": [ -0.125, -0.5, -0.375, -0.375, -0.625, -0.5625, -0.4375, -0.25, -0.375, -0.1875, -0.625, -0.25, -0.25, -0.375, -0.3125, -0.5, -0.1875, -0.25, -0.5, -0.375, -0.4375, -0.5, -0.3125, -0.5, -0.5, 0.0, -0.4375, -0.5, -0.5, -0.375, -0.0625, -0.125, -0.375, -0.1875, 0.0625, -0.6875, -0.1875, -0.5, -0.375, -0.3125, -0.4375, -0.5625, -0.375, -0.125, -0.5625, -0.4375, -0.375, -0.25, -0.1875, -0.5625, -0.375, -0.1875, -0.5, -0.5625, -0.3125, -0.3125, -0.5, -0.125, -0.625, -0.3125, -0.5625, -0.1875, -0.3125, -0.125, 0.9997791647911072, 0.9987788796424866, 0.9989608526229858, 0.9997321963310242, 0.8891316056251526, 0.9935978651046753, 0.3987571895122528, 0.39748135209083557, 0.3998531103134155, 0.47865480184555054, 0.43634313344955444, 0.0 ], "max": [ 0.5625, 0.375, 0.375, 0.4375, 0.25, 0.25, 0.1875, 0.25, 0.3125, 0.1875, 0.125, 0.375, 0.5, 0.25, 0.3125, 0.25, 0.375, 0.5625, 0.1875, 0.25, 0.25, 0.1875, 0.5, 0.3125, 0.0625, 0.5, 0.0, 0.1875, 0.3125, 0.375, 0.6875, 0.5, 0.25, 0.5, 0.375, 0.125, 0.6875, 0.1875, 0.375, 0.25, 0.125, 0.375, 0.1875, 0.5, 0.3125, 0.5, 0.5, 0.4375, 0.5, 0.1875, 0.5, 0.3125, 0.625, 0.125, 0.25, 0.5625, 0.5, 0.3125, 0.125, 0.1875, 0.25, 0.625, 0.4375, 0.6875, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ], "mean": [ 0.28530257380633073, 0.0012216853746808002, 0.02519611265225139, 0.0920742013117043, -0.18735762313302592, -0.18916948358532507, -0.10082578582844966, -0.04547218599011629, 0.009826300222291624, -0.09046442415446512, -0.3906258611504051, 0.07456643947605313, 0.06761982620836625, 0.016528346774934324, 0.02783008469127184, -0.15926115591644774, 0.137793250417945, 0.13872558925651718, -0.17794123050355484, -0.04058314809031286, -0.1081088218543898, -0.27256788161593154, 0.0295489408998218, -0.12704953796410265, -0.2065647217680451, 0.257109657744383, -0.2610296143883306, -0.11359147943343192, -0.08978239303363768, 0.042958775007807766, 0.3583063123472893, 0.2295861425973215, 0.005530882001726894, 0.18030882001726894, 0.22869399077765326, -0.3416688865210442, 0.16757757242849006, -0.24212104789374092, -0.08830580713905167, 0.03962554883985817, -0.24867382837616886, -0.16334300883655137, -0.10593298183087466, 0.29390833685448164, -0.17902857641504236, -0.02676455459004648, -0.010649560009553029, 0.006596412102952253, 0.19015693604982273, -0.28608220197306783, 0.0342829717267099, 0.05214208292763581, 0.2372308617933974, -0.27289282236878365, -0.07418638509727556, 0.21441496886080136, -0.07936362133264747, 0.07053166277809417, -0.2592969797732993, -0.04738279168886521, -0.25777561405764887, 0.3476016387118108, 0.0341980048867415, 0.4095493542520162, 0.9999920738393157, 0.9999916277741105, 0.9999916507452171, 0.9999910946907014, 0.9975380262153739, 0.9997842168412904, 0.7431049855982732, 0.743061001937713, 0.7431612987122399, 0.7812160503121215, 0.7544858488771042, 0.1884228588481359 ], "std": [ 0.13976769962393334, 0.2042750041966315, 0.11249063031363368, 0.11082072512754977, 0.1564752219884858, 0.17244514813212275, 0.10524673666978752, 0.09606056085676273, 0.16248529891535804, 0.06517700714473815, 0.12267993314050843, 0.09188274452085451, 0.1817845505649146, 0.13895894808224718, 0.09471602567899642, 0.143892040083983, 0.13123846053152619, 0.17169478968550717, 0.099377781857111, 0.12335366669054255, 0.09243992450340514, 0.12474594719512408, 0.1211368699762344, 0.17473771543792177, 0.12139112019256279, 0.08058301151688785, 0.08181288643740524, 0.12245444611527911, 0.15642136427791328, 0.16023434329274994, 0.1749952692685118, 0.10352440920325795, 0.07368975064774456, 0.13144910448634894, 0.04419890783153379, 0.18157602689607938, 0.15703202636240324, 0.1308473547559705, 0.10877569321547828, 0.06509046280547963, 0.08347560937172435, 0.19809736217235097, 0.06719381956707862, 0.09127596366580104, 0.13233099033714146, 0.25952623468134783, 0.21598709847307782, 0.10931842674892184, 0.11294459446909082, 0.1403015515249487, 0.10231818070157317, 0.10139944441893624, 0.288021039372521, 0.11780041132456433, 0.11650297357712408, 0.21262101617713844, 0.28703233994958033, 0.09814627765272926, 0.21616444128412057, 0.06262758949048293, 0.1745534315389492, 0.17455467068976818, 0.10468632106020986, 0.18477106893909007, 1.2824078270394207e-05, 2.1003630589963823e-05, 1.8574155779181667e-05, 1.5382720229173254e-05, 0.0031309164055460465, 0.0001241612656891375, 0.2938442161025196, 0.29381668166139846, 0.29367033348300187, 0.25040401472179635, 0.2708879748387615, 0.3732468841625382 ] } }, "code_commit": "028df1bb7024fb1e3d176de7e60c84d3333cd97f", "step": 4000, "weights": "ema", "offline_eval": { "mse": 0.025112804025411606, "mse_row0": 0.025062359869480133, "mse_motion_token": 0.02457592636346817, "mse_inspire_left_hand_state": 0.0052911583334207535, "mse_inspire_right_hand_state": 0.0506611168384552, "samples": 256, "frames": "train" }, "format": "hb_baselines/1"}123version https://git-lfs.github.com/spec/v1oid sha256:4c4ae7d2d53b4f17346dc75adf8c5d47d2cd8e63d099c54022b868499f0b0a4csize 903116371234567891011{ "format": "hb_baselines/1", "step": 4000, "policy": "fm_dit", "files": { "model.pt": { "bytes": 90311637, "sha256": "4c4ae7d2d53b4f17346dc75adf8c5d47d2cd8e63d099c54022b868499f0b0a4c" } }}12345678"""FM-DiT, DP (Diffusion Policy, DDPM-DiT) and ACT visuomotor baselines of the Humanoid Benchmark.
Ported from DextraVerse's imitation-learning core (`dextraverse/algorithms/il/models/{fm_dit,ddpm_dit,act}.py` andtheir networks), torch only. `train.py` trains one on a task's LeRobot v2.1 expert dataset through a robot contract(`data.CONTRACTS`: G1 state44/action76 or H2 state78/action75); `runtime.BaselinePolicy` serves a checkpoint to theG1 evaluation adapters (`evaluation/policy/{FMDiT,DP,ACT}/model.py`, via `adapters.py`) and to the H2 adapter(`debug/newton/h2_policy_adapters/baseline.py`). Usage and the environment: evaluation/README.md#baselines."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615"""ACT (Zhao et al. 2023, "Learning Fine-Grained Bimanual Manipulation with Low-Cost Hardware") network core: theResNet backbone with frozen BatchNorm and sine position embedding, the DETR encoder-decoder transformer and the CVAEaction-chunk decoder.
Ported unchanged from DextraVerse (`dextraverse/algorithms/il/models/nets/act/`), which vendors the ACT repository's`detr/models/{backbone,position_encoding,transformer,detr_vae}.py` (Apache-2.0, (c) Facebook, Inc. and itsaffiliates; see THIRD_PARTY_NOTICES.md) with the NestedTensor/argparse plumbing removed, explicit `qpos_dim` /`action_dim` instead of the ALOHA 14-DoF constants, and one backbone shared by every camera (upstream behaviour).The policy uses `return_intermediate_dec=False`: `Transformer.forward(...)[0]` is the final decoder layer."""from __future__ import annotations
import copyimport mathfrom typing import Optional
import numpy as npimport torchimport torch.nn.functional as Fimport torchvisionfrom torch import Tensor, nnfrom torchvision.models._utils import IntermediateLayerGetter
class PositionEmbeddingSine(nn.Module): """Standard DETR sine embedding over a ``(B, C, H, W)`` feature map."""
def __init__( self, num_pos_feats: int = 64, temperature: int = 10000, normalize: bool = False ) -> None: super().__init__() self.num_pos_feats = num_pos_feats self.temperature = temperature self.normalize = normalize self.scale = 2 * math.pi
def forward(self, x: torch.Tensor) -> torch.Tensor: not_mask = torch.ones((1, x.shape[-2], x.shape[-1]), device=x.device) y_embed = not_mask.cumsum(1, dtype=torch.float32) x_embed = not_mask.cumsum(2, dtype=torch.float32) if self.normalize: eps = 1e-6 y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale
dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
pos_x = x_embed[:, :, :, None] / dim_t pos_y = y_embed[:, :, :, None] / dim_t pos_x = torch.stack( (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4 ).flatten(3) pos_y = torch.stack( (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4 ).flatten(3) return torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
class FrozenBatchNorm2d(nn.Module): """BatchNorm2d with fixed statistics and affine parameters (the DETR/ACT backbone norm)."""
def __init__(self, n: int) -> None: super().__init__() self.register_buffer("weight", torch.ones(n)) self.register_buffer("bias", torch.zeros(n)) self.register_buffer("running_mean", torch.zeros(n)) self.register_buffer("running_var", torch.ones(n))
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, *args): state_dict.pop(prefix + "num_batches_tracked", None) super()._load_from_state_dict(state_dict, prefix, local_metadata, strict, *args)
def forward(self, x: torch.Tensor) -> torch.Tensor: w = self.weight.reshape(1, -1, 1, 1) b = self.bias.reshape(1, -1, 1, 1) rv = self.running_var.reshape(1, -1, 1, 1) rm = self.running_mean.reshape(1, -1, 1, 1) scale = w * (rv + 1e-5).rsqrt() return x * scale + (b - rm * scale)
class Backbone(nn.Module): """ResNet trunk returning the layer4 feature map."""
def __init__(self, name: str = "resnet18", weights: str | None = None) -> None: super().__init__() trunk = getattr(torchvision.models, name)( replace_stride_with_dilation=[False, False, False], weights=weights, norm_layer=FrozenBatchNorm2d, ) self.body = IntermediateLayerGetter(trunk, return_layers={"layer4": "0"}) self.num_channels = 512 if name in ("resnet18", "resnet34") else 2048
def forward(self, x: torch.Tensor) -> dict[str, torch.Tensor]: return self.body(x)
class Joiner(nn.Sequential): """Backbone + position embedding, returning matched feature/position lists."""
def __init__(self, backbone: Backbone, position_embedding: PositionEmbeddingSine) -> None: super().__init__(backbone, position_embedding) self.num_channels = backbone.num_channels
def forward(self, x: torch.Tensor) -> tuple[list[torch.Tensor], list[torch.Tensor]]: features = list(self[0](x).values()) pos = [self[1](f).to(f.dtype) for f in features] return features, pos
def build_backbone( name: str = "resnet18", hidden_dim: int = 512, weights: str | None = None) -> Joiner: """The ACT camera backbone: ResNet + sine embedding sized to the transformer width.""" return Joiner(Backbone(name, weights=weights), PositionEmbeddingSine(hidden_dim // 2))
class Transformer(nn.Module): def __init__( self, d_model=512, nhead=8, num_encoder_layers=6, num_decoder_layers=6, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False, return_intermediate_dec=False, ): super().__init__()
encoder_layer = TransformerEncoderLayer( d_model, nhead, dim_feedforward, dropout, activation, normalize_before ) encoder_norm = nn.LayerNorm(d_model) if normalize_before else None self.encoder = TransformerEncoder(encoder_layer, num_encoder_layers, encoder_norm)
decoder_layer = TransformerDecoderLayer( d_model, nhead, dim_feedforward, dropout, activation, normalize_before ) decoder_norm = nn.LayerNorm(d_model) self.decoder = TransformerDecoder( decoder_layer, num_decoder_layers, decoder_norm, return_intermediate=return_intermediate_dec, )
self._reset_parameters()
self.d_model = d_model self.nhead = nhead
def _reset_parameters(self): for p in self.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p)
def forward( self, src, mask, query_embed, pos_embed, latent_input=None, proprio_input=None, additional_pos_embed=None, ): # TODO flatten only when input has H and W if len(src.shape) == 4: # has H and W # flatten NxCxHxW to HWxNxC bs, c, h, w = src.shape src = src.flatten(2).permute(2, 0, 1) pos_embed = pos_embed.flatten(2).permute(2, 0, 1).repeat(1, bs, 1) query_embed = query_embed.unsqueeze(1).repeat(1, bs, 1) # mask = mask.flatten(1)
additional_pos_embed = additional_pos_embed.unsqueeze(1).repeat( 1, bs, 1 ) # seq, bs, dim pos_embed = torch.cat([additional_pos_embed, pos_embed], axis=0)
addition_input = torch.stack([latent_input, proprio_input], axis=0) src = torch.cat([addition_input, src], axis=0) else: assert len(src.shape) == 3 # flatten NxHWxC to HWxNxC bs, hw, c = src.shape src = src.permute(1, 0, 2) pos_embed = pos_embed.unsqueeze(1).repeat(1, bs, 1) query_embed = query_embed.unsqueeze(1).repeat(1, bs, 1)
tgt = torch.zeros_like(query_embed) memory = self.encoder(src, src_key_padding_mask=mask, pos=pos_embed) hs = self.decoder( tgt, memory, memory_key_padding_mask=mask, pos=pos_embed, query_pos=query_embed ) hs = hs.transpose(1, 2) return hs
class TransformerEncoder(nn.Module): def __init__(self, encoder_layer, num_layers, norm=None): super().__init__() self.layers = _get_clones(encoder_layer, num_layers) self.num_layers = num_layers self.norm = norm
def forward( self, src, mask: Optional[Tensor] = None, src_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, ): output = src
for layer in self.layers: output = layer( output, src_mask=mask, src_key_padding_mask=src_key_padding_mask, pos=pos )
if self.norm is not None: output = self.norm(output)
return output
class TransformerDecoder(nn.Module): def __init__(self, decoder_layer, num_layers, norm=None, return_intermediate=False): super().__init__() self.layers = _get_clones(decoder_layer, num_layers) self.num_layers = num_layers self.norm = norm self.return_intermediate = return_intermediate
def forward( self, tgt, memory, tgt_mask: Optional[Tensor] = None, memory_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, query_pos: Optional[Tensor] = None, ): output = tgt
intermediate = []
for layer in self.layers: output = layer( output, memory, tgt_mask=tgt_mask, memory_mask=memory_mask, tgt_key_padding_mask=tgt_key_padding_mask, memory_key_padding_mask=memory_key_padding_mask, pos=pos, query_pos=query_pos, ) if self.return_intermediate: intermediate.append(self.norm(output))
if self.norm is not None: output = self.norm(output) if self.return_intermediate: intermediate.pop() intermediate.append(output)
if self.return_intermediate: return torch.stack(intermediate)
return output.unsqueeze(0)
class TransformerEncoderLayer(nn.Module): def __init__( self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False, ): super().__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) # Implementation of Feedforward model self.linear1 = nn.Linear(d_model, dim_feedforward) self.dropout = nn.Dropout(dropout) self.linear2 = nn.Linear(dim_feedforward, d_model)
self.norm1 = nn.LayerNorm(d_model) self.norm2 = nn.LayerNorm(d_model) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout)
self.activation = _get_activation_fn(activation) self.normalize_before = normalize_before
def with_pos_embed(self, tensor, pos: Optional[Tensor]): return tensor if pos is None else tensor + pos
def forward_post( self, src, src_mask: Optional[Tensor] = None, src_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, ): q = k = self.with_pos_embed(src, pos) src2 = self.self_attn( q, k, value=src, attn_mask=src_mask, key_padding_mask=src_key_padding_mask )[0] src = src + self.dropout1(src2) src = self.norm1(src) src2 = self.linear2(self.dropout(self.activation(self.linear1(src)))) src = src + self.dropout2(src2) src = self.norm2(src) return src
def forward_pre( self, src, src_mask: Optional[Tensor] = None, src_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, ): src2 = self.norm1(src) q = k = self.with_pos_embed(src2, pos) src2 = self.self_attn( q, k, value=src2, attn_mask=src_mask, key_padding_mask=src_key_padding_mask )[0] src = src + self.dropout1(src2) src2 = self.norm2(src) src2 = self.linear2(self.dropout(self.activation(self.linear1(src2)))) src = src + self.dropout2(src2) return src
def forward( self, src, src_mask: Optional[Tensor] = None, src_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, ): if self.normalize_before: return self.forward_pre(src, src_mask, src_key_padding_mask, pos) return self.forward_post(src, src_mask, src_key_padding_mask, pos)
class TransformerDecoderLayer(nn.Module): def __init__( self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False, ): super().__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) # Implementation of Feedforward model self.linear1 = nn.Linear(d_model, dim_feedforward) self.dropout = nn.Dropout(dropout) self.linear2 = nn.Linear(dim_feedforward, d_model)
self.norm1 = nn.LayerNorm(d_model) self.norm2 = nn.LayerNorm(d_model) self.norm3 = nn.LayerNorm(d_model) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.dropout3 = nn.Dropout(dropout)
self.activation = _get_activation_fn(activation) self.normalize_before = normalize_before
def with_pos_embed(self, tensor, pos: Optional[Tensor]): return tensor if pos is None else tensor + pos
def forward_post( self, tgt, memory, tgt_mask: Optional[Tensor] = None, memory_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, query_pos: Optional[Tensor] = None, ): q = k = self.with_pos_embed(tgt, query_pos) tgt2 = self.self_attn( q, k, value=tgt, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask )[0] tgt = tgt + self.dropout1(tgt2) tgt = self.norm1(tgt) tgt2 = self.multihead_attn( query=self.with_pos_embed(tgt, query_pos), key=self.with_pos_embed(memory, pos), value=memory, attn_mask=memory_mask, key_padding_mask=memory_key_padding_mask, )[0] tgt = tgt + self.dropout2(tgt2) tgt = self.norm2(tgt) tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt)))) tgt = tgt + self.dropout3(tgt2) tgt = self.norm3(tgt) return tgt
def forward_pre( self, tgt, memory, tgt_mask: Optional[Tensor] = None, memory_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, query_pos: Optional[Tensor] = None, ): tgt2 = self.norm1(tgt) q = k = self.with_pos_embed(tgt2, query_pos) tgt2 = self.self_attn( q, k, value=tgt2, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask )[0] tgt = tgt + self.dropout1(tgt2) tgt2 = self.norm2(tgt) tgt2 = self.multihead_attn( query=self.with_pos_embed(tgt2, query_pos), key=self.with_pos_embed(memory, pos), value=memory, attn_mask=memory_mask, key_padding_mask=memory_key_padding_mask, )[0] tgt = tgt + self.dropout2(tgt2) tgt2 = self.norm3(tgt) tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2)))) tgt = tgt + self.dropout3(tgt2) return tgt
def forward( self, tgt, memory, tgt_mask: Optional[Tensor] = None, memory_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, query_pos: Optional[Tensor] = None, ): if self.normalize_before: return self.forward_pre( tgt, memory, tgt_mask, memory_mask, tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos, ) return self.forward_post( tgt, memory, tgt_mask, memory_mask, tgt_key_padding_mask, memory_key_padding_mask, pos, query_pos, )
def _get_clones(module, N): return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
def _get_activation_fn(activation): """Return an activation function given a string.""" if activation == "relu": return F.relu if activation == "gelu": return F.gelu raise RuntimeError(f"activation should be relu/gelu, not {activation}.")
def reparametrize(mu: torch.Tensor, logvar: torch.Tensor) -> torch.Tensor: std = logvar.div(2).exp() return mu + std * torch.randn_like(std)
def get_sinusoid_encoding_table(n_position: int, d_hid: int) -> torch.Tensor: def angle_vec(position: int) -> list[float]: return [position / np.power(10000, 2 * (j // 2) / d_hid) for j in range(d_hid)]
table = np.array([angle_vec(i) for i in range(n_position)]) table[:, 0::2] = np.sin(table[:, 0::2]) table[:, 1::2] = np.cos(table[:, 1::2]) return torch.FloatTensor(table).unsqueeze(0)
def build_style_encoder( hidden_dim: int, nheads: int, dim_feedforward: int, enc_layers: int, dropout: float) -> TransformerEncoder: """The CVAE style encoder (a plain transformer encoder over [CLS, qpos, action seq]).""" layer = TransformerEncoderLayer(hidden_dim, nheads, dim_feedforward, dropout, "relu", False) return TransformerEncoder(layer, enc_layers, norm=None)
class DETRVAE(nn.Module): """CVAE decoder: (qpos, images[, action seq]) → ``num_queries`` future actions."""
def __init__( self, backbone: Joiner, transformer: Transformer, encoder: TransformerEncoder, *, qpos_dim: int, action_dim: int, num_queries: int, latent_dim: int = 32, ) -> None: super().__init__() self.num_queries = num_queries self.transformer = transformer self.encoder = encoder hidden_dim = transformer.d_model self.action_head = nn.Linear(hidden_dim, action_dim) self.query_embed = nn.Embedding(num_queries, hidden_dim) self.backbone = backbone # ONE backbone shared by every camera (upstream behavior) self.input_proj = nn.Conv2d(backbone.num_channels, hidden_dim, kernel_size=1) self.input_proj_robot_state = nn.Linear(qpos_dim, hidden_dim)
# CVAE style encoder inputs self.latent_dim = latent_dim self.cls_embed = nn.Embedding(1, hidden_dim) self.encoder_action_proj = nn.Linear(action_dim, hidden_dim) self.encoder_joint_proj = nn.Linear(qpos_dim, hidden_dim) self.latent_proj = nn.Linear(hidden_dim, latent_dim * 2) self.register_buffer( "pos_table", get_sinusoid_encoding_table(1 + 1 + num_queries, hidden_dim) ) # decoder side self.latent_out_proj = nn.Linear(latent_dim, hidden_dim) self.additional_pos_embed = nn.Embedding(2, hidden_dim) # latent + proprio slots
def forward( self, qpos: torch.Tensor, images: torch.Tensor, actions: torch.Tensor | None = None, is_pad: torch.Tensor | None = None, ) -> tuple[torch.Tensor, tuple[torch.Tensor | None, torch.Tensor | None]]: """``qpos (B, Dq)``, ``images (B, ncam, C, H, W)``; train passes ``actions (B, T, Da)``.""" is_training = actions is not None bs = qpos.shape[0] if is_training: action_embed = self.encoder_action_proj(actions) qpos_embed = self.encoder_joint_proj(qpos).unsqueeze(1) cls_embed = self.cls_embed.weight.unsqueeze(0).repeat(bs, 1, 1) encoder_input = torch.cat([cls_embed, qpos_embed, action_embed], dim=1) encoder_input = encoder_input.permute(1, 0, 2) if is_pad is None: is_pad = torch.zeros(bs, actions.shape[1], dtype=torch.bool, device=qpos.device) cls_joint_is_pad = torch.full((bs, 2), False, device=qpos.device) key_pad = torch.cat([cls_joint_is_pad, is_pad], dim=1) pos_embed = self.pos_table.clone().detach().permute(1, 0, 2) encoder_output = self.encoder( encoder_input, pos=pos_embed, src_key_padding_mask=key_pad )[0] latent_info = self.latent_proj(encoder_output) mu = latent_info[:, : self.latent_dim] logvar = latent_info[:, self.latent_dim :] latent_input = self.latent_out_proj(reparametrize(mu, logvar)) else: mu = logvar = None latent_sample = torch.zeros(bs, self.latent_dim, device=qpos.device) latent_input = self.latent_out_proj(latent_sample)
all_cam_features, all_cam_pos = [], [] for cam_id in range(images.shape[1]): features, pos = self.backbone(images[:, cam_id]) all_cam_features.append(self.input_proj(features[0])) all_cam_pos.append(pos[0]) proprio_input = self.input_proj_robot_state(qpos) src = torch.cat(all_cam_features, dim=3) # cameras fold into the width axis pos = torch.cat(all_cam_pos, dim=3) hs = self.transformer( src, None, self.query_embed.weight, pos, latent_input, proprio_input, self.additional_pos_embed.weight, )[0] return self.action_head(hs), (mu, logvar)
def kl_divergence(mu: torch.Tensor, logvar: torch.Tensor) -> torch.Tensor: """Total KL(q(z|x) || N(0, I)), summed over latent dims, meaned over the batch.""" klds = -0.5 * (1 + logvar - mu.pow(2) - logvar.exp()) return klds.sum(1).mean()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207"""Networks of the FM-DiT and DP (DDPM-DiT) baselines: the AdaLN DiT action backbone and the camera + state encoder.
Ported from DextraVerse's imitation-learning core (`dextraverse/algorithms/il/models/nets/dit.py`, `layers.py`,`positional_embedding.py`, `vision/backbones.py`, `vision/encoder.py`), unchanged in architecture and initialization.Left out: the ROVE improvement embedding, the spatial-softmax / R3M / tactile options and the inpainting path (thebaselines always condition through the global observation feature). Added: the ResNet's normalization choice(`get_resnet`): DextraVerse's GroupNorm for a backbone trained from scratch, or BatchNorm frozen at the pretrainedstatistics (the DETR / ACT practice) for an ImageNet-initialized backbone that is fine-tuned with the policy."""from __future__ import annotations
import math
import torchimport torch.nn as nnimport torch.nn.functional as Fimport torchvision
IMAGENET_MEAN = (0.485, 0.456, 0.406)IMAGENET_STD = (0.229, 0.224, 0.225)
class SinusoidalPosEmb(nn.Module): def __init__(self, dim): super().__init__() self.dim = dim
def forward(self, x): half_dim = self.dim // 2 emb = math.log(10000) / (half_dim - 1) emb = torch.exp(torch.arange(half_dim, device=x.device) * -emb) emb = x[:, None] * emb[None, :] return torch.cat((emb.sin(), emb.cos()), dim=-1)
class RotaryPosEmb(nn.Module): """Rotary position embedding over each attention head's (S, head_dim) slice."""
def __init__(self, dim): super().__init__() self.dim = dim self.register_buffer('inv_freq', 1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim)))
def forward(self, x): # x: (B, heads, S, head_dim) t = torch.arange(x.shape[-2], device=x.device, dtype=self.inv_freq.dtype) freqs = torch.outer(t, self.inv_freq.to(x.device)) emb = torch.cat([freqs, freqs], dim=-1) cos, sin = emb.cos()[None, None], emb.sin()[None, None] x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2:] return x * cos + torch.cat([-x2, x1], dim=-1) * sin
class Mlp(nn.Module): """The ViT MLP (timm.layers.Mlp) as DextraVerse's nets/layers.py."""
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_features) self.act = act_layer() self.drop1 = nn.Dropout(drop) self.norm = nn.Identity() self.fc2 = nn.Linear(hidden_features, out_features) self.drop2 = nn.Dropout(drop)
def forward(self, x): return self.drop2(self.fc2(self.norm(self.drop1(self.act(self.fc1(x))))))
class Attention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=True, attn_drop=0.0, proj_drop=0.0, qk_norm=True): super().__init__() assert dim % num_heads == 0, 'dim should be divisible by num_heads' self.num_heads = num_heads self.head_dim = dim // num_heads self.attn_drop = attn_drop self.proj_drop = nn.Dropout(proj_drop) self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.q_norm = nn.LayerNorm(self.head_dim) if qk_norm else nn.Identity() self.k_norm = nn.LayerNorm(self.head_dim) if qk_norm else nn.Identity() self.proj = nn.Linear(dim, dim) self.rope = RotaryPosEmb(self.head_dim)
def forward(self, x): B, S, C = x.shape qkv = self.qkv(x).reshape(B, S, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0) q, k = self.rope(self.q_norm(q)), self.rope(self.k_norm(k)) x = F.scaled_dot_product_attention(q, k, v, dropout_p=self.attn_drop if self.training else 0.0) return self.proj_drop(self.proj(x.transpose(1, 2).reshape(B, S, C)))
class AdaLNBlock(nn.Module): """Adaptive-LayerNorm transformer block as in DiT (Peebles et al. 2022)."""
def __init__(self, dim, num_heads, mlp_ratio=4.0, dropout=0.0): super().__init__() self.norm1 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6) self.attn = Attention(dim, num_heads=num_heads, attn_drop=dropout, proj_drop=dropout) self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6) self.mlp = Mlp(in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=lambda: nn.GELU(approximate='tanh'), drop=0) self.ada_ln = nn.Sequential(nn.SiLU(), nn.Linear(dim, 6 * dim)) self.dim = dim nn.init.constant_(self.ada_ln[-1].weight, 0) nn.init.constant_(self.ada_ln[-1].bias, 0)
def forward(self, x, t, c): B = x.shape[0] gamma1, gamma2, scale1, scale2, shift1, shift2 = self.ada_ln(F.silu(t + c)).view(B, 6, 1, self.dim).unbind(1) x = x + self.attn(self.norm1(x).mul(scale1.add(1)).add_(shift1)).mul_(gamma1) return x + self.mlp(self.norm2(x).mul(scale2.add(1)).add_(shift2)).mul_(gamma2)
class FlowTransformer(nn.Module): """DiT action backbone: AdaLN blocks over the H action tokens, conditioned on time_embed(t) + cond_embed(obs).
As DextraVerse, the generic Xavier initialization runs after the blocks' zero init of their AdaLN projection, so it is not the full AdaLN-Zero recipe (kept: it is the reference's training behaviour)."""
def __init__(self, input_dim, condition_dim, hidden_dim, output_dim, num_layers, num_heads, mlp_ratio=4.0, dropout=0.1, time_embed_dim=256): super().__init__() self.input_proj = nn.Linear(input_dim, hidden_dim) self.time_embed = nn.Sequential(SinusoidalPosEmb(time_embed_dim), nn.Linear(time_embed_dim, time_embed_dim * 4), nn.Mish(), nn.Linear(time_embed_dim * 4, hidden_dim)) self.cond_embed = nn.Linear(condition_dim, hidden_dim) self.transformer_blocks = nn.ModuleList( [AdaLNBlock(hidden_dim, num_heads, mlp_ratio=mlp_ratio, dropout=dropout) for _ in range(num_layers)]) self.norm = nn.LayerNorm(hidden_dim) self.out_proj = nn.Linear(hidden_dim, output_dim)
def basic_init(module): if isinstance(module, nn.Linear): nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.constant_(module.bias, 0)
self.apply(basic_init) nn.init.normal_(self.time_embed[1].weight, std=0.02) nn.init.normal_(self.time_embed[3].weight, std=0.02)
def forward(self, x, t, global_cond): if not torch.is_tensor(t): t = torch.tensor(t, device=x.device) if t.ndim == 0: t = t.expand(x.shape[0]) x = self.input_proj(x) t = self.time_embed(t) c = self.cond_embed(global_cond) for block in self.transformer_blocks: x = block(x, t, c) return self.out_proj(self.norm(x))
def replace_batchnorm_with_groupnorm(module: nn.Module) -> nn.Module: """DextraVerse's use_group_norm: every BatchNorm2d becomes GroupNorm(num_features // 16 groups).""" for name, child in module.named_children(): if isinstance(child, nn.BatchNorm2d): setattr(module, name, nn.GroupNorm(num_groups=child.num_features // 16, num_channels=child.num_features)) else: replace_batchnorm_with_groupnorm(child) return module
NORMS = ('group', 'frozen_bn')
def get_resnet(name='resnet18', weights=None, norm='group') -> nn.Module: """A torchvision ResNet with its classifier removed: (N, 3, H, W) -> (N, 512) globally pooled.
weights: torchvision weights name (e.g. 'IMAGENET1K_V1') to initialize from, or None (random initialization; a checkpoint load supplies every weight). norm: 'group' replaces every BatchNorm with GroupNorm (DextraVerse's use_group_norm, for training from scratch: pretrained BatchNorm statistics and affine are dropped); 'frozen_bn' keeps BatchNorm frozen at its (pretrained) running statistics and affine, the convolutions fine-tune.""" if norm == 'frozen_bn': from .act_nets import FrozenBatchNorm2d resnet = getattr(torchvision.models, name)(weights=weights, norm_layer=FrozenBatchNorm2d) elif norm == 'group': resnet = replace_batchnorm_with_groupnorm(getattr(torchvision.models, name)(weights=weights)) else: raise ValueError(f'norm must be one of {NORMS}, got {norm!r}') resnet.fc = nn.Identity() return resnet
class ImageStateEncoder(nn.Module): """DextraVerse MultiImageObsEncoder as configured for FM-DiT / DDPM-DiT: one ResNet shared by every camera (share_rgb_model; `get_resnet` weights and norm), ImageNet normalization of the [0, 1] images, the pooled features of each camera in the contract's camera order, then the normalized state. Output (B, n_cameras * 512 + state_dim)."""
def __init__(self, n_cameras, state_dim, backbone='resnet18', weights=None, norm='group'): super().__init__() self.rgb = get_resnet(backbone, weights=weights, norm=norm) self.n_cameras, self.state_dim = int(n_cameras), int(state_dim) self.register_buffer('mean', torch.tensor(IMAGENET_MEAN).view(1, 3, 1, 1), persistent=False) self.register_buffer('std', torch.tensor(IMAGENET_STD).view(1, 3, 1, 1), persistent=False) self.feature_dim = self.n_cameras * (512 if backbone in ('resnet18', 'resnet34') else 2048) + self.state_dim
def forward(self, images, state): """images (B, n_cameras, 3, H, W) in [0, 1]; state (B, state_dim) normalized.""" B = images.shape[0] x = (images.flatten(0, 1) - self.mean) / self.std features = self.rgb(x).reshape(B, -1) # camera features side by side, in camera order return torch.cat([features, state], dim=-1)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281"""The three baseline policies behind one contract, ported from DextraVerse's imitation-learning core:
- `fm_dit`, `FMDiTPolicy` (reference: dextraverse/algorithms/il/models/fm_dit.py + fm_base.py): flow matching, MSE on the velocity `a - noise`; sampled with 10 midpoint steps from noise (20 DiT calls);- `dp`, `DPPolicy` (ddpm_dit.py + ddpm_base.py: Diffusion Policy with a DiT backbone): DDPM epsilon MSE over 100 steps; sampled with the 100 DDPM steps;- `act`, `ACTPolicy` (act.py + nets/act/): L1 + `kl_weight` x KL of the CVAE; decoded from the zero latent in one pass.
Contract (every policy): `compute_loss(images, state, action) -> (loss, metrics)` and`predict(images, state, generator) -> (action, normalized action)`; images (B, n_cameras, 3, H, W) float in [0, 1],state (B, state_dim) and action (B, horizon, action_dim) in physical units. Each policy owns its `Normalizer`(DextraVerse's LinearNormalizer 'limits' mode: state and action to [-1, 1] per dimension, constant dimensions shiftedto 0), saved in its state dict. One observation frame (n_obs_steps 1: the current images and state); the chunk's row 0is the action of the observation's own frame (the LeRobot rows t..t+horizon-1). The configuration that builds apolicy is a plain dict (`PolicyConfig` fields), stored in the checkpoint.
The ResNet18 starts from torchvision's ImageNet-1k weights (`backbone_weights` 'IMAGENET1K_V1', the default since2026-11-16) and is fine-tuned with the policy, its BatchNorm frozen at the pretrained statistics (`backbone_norm`'frozen_bn', as ACT always does); `backbone_weights` None trains from scratch with DextraVerse's GroupNorm encoder(FM-DiT, DP) or ACT's frozen-BatchNorm one. A checkpoint load builds the structure without fetching any weights."""from __future__ import annotations
from dataclasses import asdict, dataclass, field, replace
import torchimport torch.nn as nnimport torch.nn.functional as F
from .act_nets import DETRVAE, Transformer, build_backbone, build_style_encoder, kl_divergencefrom .nets import IMAGENET_MEAN, IMAGENET_STD, FlowTransformer, ImageStateEncoder
@dataclassclass PolicyConfig: """Everything that builds a policy (stored in the checkpoint's config.json). Model defaults are DextraVerse's configs/algorithm/il/model/{fm_dit,ddpm_dit,act}.yaml.""" policy: str n_cameras: int state_dim: int action_dim: int horizon: int = 16 backbone: str = 'resnet18' backbone_weights: str | None = 'IMAGENET1K_V1' # torchvision weights to initialize from; None = from scratch backbone_norm: str | None = None # 'frozen_bn' or 'group'; None: frozen_bn when pretrained or ACT, else group # FM-DiT / DP (DiT backbone) hidden_dim: int = 384 num_layers: int = 4 num_heads: int = 8 mlp_ratio: float = 4.0 dropout: float = 0.1 time_embed_dim: int = 128 num_inference_steps: int | None = None # None: FM-DiT 10 midpoint steps, DP every training timestep (100) # DP noise schedule (diffusers DDPMScheduler) num_train_timesteps: int = 100 beta_schedule: str = 'squaredcos_cap_v2' prediction_type: str = 'epsilon' clip_sample: bool = True # ACT act_hidden_dim: int = 512 dim_feedforward: int = 3200 enc_layers: int = 4 dec_layers: int = 7 nheads: int = 8 latent_dim: int = 32 kl_weight: float = 10.0 extra: dict = field(default_factory=dict)
def __post_init__(self): if self.backbone_norm is None: self.backbone_norm = 'frozen_bn' if self.backbone_weights or self.policy == 'act' else 'group' if self.policy == 'act' and self.backbone_norm != 'frozen_bn': raise ValueError("ACT's backbone keeps frozen BatchNorm (backbone_norm 'frozen_bn')")
@classmethod def from_dict(cls, data: dict) -> PolicyConfig: known = {k: v for k, v in data.items() if k in cls.__dataclass_fields__} return cls(**known)
def to_dict(self) -> dict: return asdict(self)
class Normalizer(nn.Module): """Per-dimension affine map to [-1, 1] from the training data's min/max (DextraVerse LinearNormalizer, mode 'limits', fit_offset, range_eps 1e-4): x_n = x * scale + offset; a dimension whose range is below range_eps gets scale 1 and maps its value to 0."""
def __init__(self, dim: int): super().__init__() self.register_buffer('scale', torch.ones(dim)) self.register_buffer('offset', torch.zeros(dim))
@torch.no_grad() def fit(self, minimum, maximum, range_eps=1e-4): lo = torch.as_tensor(minimum, dtype=torch.float32) hi = torch.as_tensor(maximum, dtype=torch.float32) span = hi - lo ignore = span < range_eps span[ignore] = 2.0 scale = 2.0 / span offset = -1.0 - scale * lo offset[ignore] = -lo[ignore] self.scale.copy_(scale) self.offset.copy_(offset)
def normalize(self, x): return x * self.scale + self.offset
def unnormalize(self, x): return (x - self.offset) / self.scale
class BasePolicy(nn.Module): name = '' backbone_prefix = '' # state-dict prefix of the image backbone (its own learning rate in training)
def __init__(self, cfg: PolicyConfig, init_weights=None): super().__init__() self.cfg = cfg self.state_norm = Normalizer(cfg.state_dim) self.action_norm = Normalizer(cfg.action_dim)
def fit_normalizers(self, stats: dict): self.state_norm.fit(stats['state']['min'], stats['state']['max']) self.action_norm.fit(stats['action']['min'], stats['action']['max'])
@property def sampling_steps(self) -> int: return 1
def compute_loss(self, images, state, action): raise NotImplementedError
def predict(self, images, state, generator=None): raise NotImplementedError
class DiTPolicy(BasePolicy): """Shared by FM-DiT and DP: the shared-ResNet image + state encoder and the AdaLN DiT over the action chunk (global observation conditioning, DextraVerse obs_as_global_cond).""" backbone_prefix = 'obs_encoder.rgb.'
def __init__(self, cfg: PolicyConfig, init_weights=None): super().__init__(cfg) self.obs_encoder = ImageStateEncoder(cfg.n_cameras, cfg.state_dim, backbone=cfg.backbone, weights=init_weights, norm=cfg.backbone_norm) self.model = FlowTransformer(input_dim=cfg.action_dim, condition_dim=self.obs_encoder.feature_dim, hidden_dim=cfg.hidden_dim, output_dim=cfg.action_dim, num_layers=cfg.num_layers, num_heads=cfg.num_heads, mlp_ratio=cfg.mlp_ratio, dropout=cfg.dropout, time_embed_dim=cfg.time_embed_dim)
def condition(self, images, state): return self.obs_encoder(images, self.state_norm.normalize(state))
class FMDiTPolicy(DiTPolicy): """Flow-matching DiT (DextraVerse FlowMatchingDiTImagePolicy): x_t = (1 - t) noise + t a, t ~ U(0, 1), the DiT regresses the velocity a - noise; sampling integrates t = 0 -> 1 with the midpoint rule.""" name = 'fm_dit'
@property def sampling_steps(self) -> int: return int(self.cfg.num_inference_steps or 10)
def compute_loss(self, images, state, action): cond = self.condition(images, state) target = self.action_norm.normalize(action) noise = torch.randn_like(target) t = torch.rand(target.shape[0], device=target.device) te = t.view(-1, 1, 1) x_t = (1 - te) * noise + te * target loss = F.mse_loss(self.model(x_t, t, cond), target - noise) return loss, dict(fm=float(loss.detach()))
@torch.no_grad() def predict(self, images, state, generator=None): cond = self.condition(images, state) B, steps = images.shape[0], self.sampling_steps x = torch.randn((B, self.cfg.horizon, self.cfg.action_dim), device=cond.device, dtype=cond.dtype, generator=generator) times = torch.linspace(0, 1.0, steps + 1, device=cond.device) for i in range(steps): t0 = times[i].view(1).expand(B) t1 = times[i + 1].view(1).expand(B) dt = (t1 - t0).view(-1, 1, 1) x_mid = x + self.model(x, t0, cond) * dt / 2 x = x + dt * self.model(x_mid, t0 + (t1 - t0) / 2, cond) return self.action_norm.unnormalize(x), x
class DPPolicy(DiTPolicy): """Diffusion Policy with the DiT backbone (DextraVerse DiffusionDiTImagePolicy, ddpm_dit.yaml): DDPM with 100 training steps, squaredcos_cap_v2 betas, fixed_small variance, clipped samples, epsilon prediction; sampled with every training step (100 DiT calls).""" name = 'dp'
def __init__(self, cfg: PolicyConfig, init_weights=None): super().__init__(cfg, init_weights) from diffusers.schedulers.scheduling_ddpm import DDPMScheduler self.noise_scheduler = DDPMScheduler(num_train_timesteps=cfg.num_train_timesteps, beta_start=0.0001, beta_end=0.02, beta_schedule=cfg.beta_schedule, variance_type='fixed_small', clip_sample=cfg.clip_sample, prediction_type=cfg.prediction_type)
@property def sampling_steps(self) -> int: return int(self.cfg.num_inference_steps or self.cfg.num_train_timesteps)
def compute_loss(self, images, state, action): cond = self.condition(images, state) target = self.action_norm.normalize(action) noise = torch.randn_like(target) t = torch.randint(0, self.noise_scheduler.config.num_train_timesteps, (target.shape[0],), device=target.device).long() noisy = self.noise_scheduler.add_noise(target, noise, t) pred = self.model(noisy, t, cond) goal = noise if self.cfg.prediction_type == 'epsilon' else target loss = F.mse_loss(pred, goal) return loss, dict(ddpm=float(loss.detach()))
@torch.no_grad() def predict(self, images, state, generator=None): cond = self.condition(images, state) scheduler = self.noise_scheduler x = torch.randn((images.shape[0], self.cfg.horizon, self.cfg.action_dim), device=cond.device, dtype=cond.dtype, generator=generator) scheduler.set_timesteps(self.sampling_steps, device=cond.device) for t in scheduler.timesteps: x = scheduler.step(self.model(x, t.to(cond.device), cond), t, x, generator=generator).prev_sample return self.action_norm.unnormalize(x), x
class ACTPolicy(BasePolicy): """ACT (DextraVerse ACTImagePolicy, act.yaml): ImageNet-normalized cameras through one ResNet with frozen BatchNorm (spatial tokens, no pooling), the normalized state as qpos, a CVAE style encoder over the action chunk in training, the DETR decoder with `horizon` queries; loss L1 + kl_weight x KL; inference decodes from the zero latent (deterministic).""" name = 'act' backbone_prefix = 'model.backbone.'
def __init__(self, cfg: PolicyConfig, init_weights=None): super().__init__(cfg) transformer = Transformer(d_model=cfg.act_hidden_dim, nhead=cfg.nheads, num_encoder_layers=cfg.enc_layers, num_decoder_layers=cfg.dec_layers, dim_feedforward=cfg.dim_feedforward, dropout=cfg.dropout, return_intermediate_dec=False) self.model = DETRVAE(build_backbone(cfg.backbone, hidden_dim=cfg.act_hidden_dim, weights=init_weights), transformer, build_style_encoder(cfg.act_hidden_dim, cfg.nheads, cfg.dim_feedforward, cfg.enc_layers, cfg.dropout), qpos_dim=cfg.state_dim, action_dim=cfg.action_dim, num_queries=cfg.horizon, latent_dim=cfg.latent_dim) self.register_buffer('mean', torch.tensor(IMAGENET_MEAN).view(1, 1, 3, 1, 1), persistent=False) self.register_buffer('std', torch.tensor(IMAGENET_STD).view(1, 1, 3, 1, 1), persistent=False)
def compute_loss(self, images, state, action): target = self.action_norm.normalize(action) a_hat, (mu, logvar) = self.model(self.state_norm.normalize(state), (images - self.mean) / self.std, actions=target) l1 = F.l1_loss(a_hat, target) kl = kl_divergence(mu, logvar) return l1 + self.cfg.kl_weight * kl, dict(l1=float(l1.detach()), kl=float(kl.detach()))
@torch.no_grad() def predict(self, images, state, generator=None): # noqa: ARG002 - deterministic (zero latent) a_hat, _ = self.model(self.state_norm.normalize(state), (images - self.mean) / self.std) return self.action_norm.unnormalize(a_hat), a_hat
POLICIES = {cls.name: cls for cls in (FMDiTPolicy, DPPolicy, ACTPolicy)}LABELS = {'fm_dit': 'FM-DiT', 'dp': 'DP (DDPM-DiT)', 'act': 'ACT'}
def build_policy(cfg: PolicyConfig | dict, pretrained: bool = True) -> BasePolicy: """The policy of `cfg`; pretrained=True initializes the backbone from cfg.backbone_weights (training), False builds the same structure with random weights (a checkpoint load, which must not download anything).""" cfg = cfg if isinstance(cfg, PolicyConfig) else PolicyConfig.from_dict(cfg) if cfg.policy not in POLICIES: raise KeyError(f'unknown baseline {cfg.policy!r}; one of {sorted(POLICIES)}') cfg = replace(cfg) # a copy (resolved backbone_norm) return POLICIES[cfg.policy](cfg, init_weights=cfg.backbone_weights if pretrained else None)123456789101112# Environment of the FM-DiT / DP / ACT baselines (training and the policy server), Python 3.12, CUDA 12.8 wheels:# uv venv <env> --python 3.12# uv pip install --python <env>/bin/python -r evaluation/baselines/requirements.txt \# --extra-index-url https://download.pytorch.org/whl/cu128 --index-strategy unsafe-best-matchtorch==2.9.0+cu128torchvision==0.24.0+cu128diffusers==0.35.1av==15.1.0pyarrow==23.0.1numpy==2.2.6opencv-python-headless==4.11.0.86pytest==8.4.2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123"""Checkpoints and inference of the baselines.
A checkpoint is a directory written by train.py (`<run>/checkpoints/step-NNNNNN/`, `final` links the last one):
- `model.pt`: torch.save of {format, config (the config.json text), state_dict}: the EMA weights (or the raw ones when EMA is off) with the policy's state and action normalizers, loaded strictly with `weights_only=True`;- `config.json`: the policy configuration, the contract (robot, cameras, state and action columns), the image size, the training task text, dataset, episodes, recipe and statistics;- `protocol.json`: model.pt's size and SHA-256.
`BaselinePolicy.predict` takes the live frames of the checkpoint's cameras (any size; resized with data.resize_frame,as the training cache), the physical state of the contract and a seed, and returns the physical (horizon,action_dim) chunk with its normalized form; row 0 is the action of the observation's frame."""from __future__ import annotations
import hashlibimport jsonfrom pathlib import Path
import numpy as np
FORMAT = 'hb_baselines/1'
def sha256(path) -> str: digest = hashlib.sha256() with Path(path).open('rb') as stream: for block in iter(lambda: stream.read(16 << 20), b''): digest.update(block) return digest.hexdigest()
def save_checkpoint(folder, policy, config: dict): """Write model.pt, config.json and protocol.json of `policy` (an nn.Module) into `folder`.""" import torch folder = Path(folder) folder.mkdir(parents=True, exist_ok=True) text = json.dumps(dict(config, format=FORMAT), indent=1) state = {k: v.detach().cpu().contiguous() for k, v in policy.state_dict().items()} torch.save(dict(format=FORMAT, config=text, state_dict=state), folder / 'model.pt.tmp') (folder / 'model.pt.tmp').replace(folder / 'model.pt') (folder / 'config.json').write_text(text) (folder / 'protocol.json').write_text(json.dumps(dict( format=FORMAT, step=config.get('step'), policy=config['policy']['policy'], files={'model.pt': dict(bytes=(folder / 'model.pt').stat().st_size, sha256=sha256(folder / 'model.pt'))}), indent=1))
def load_checkpoint(folder, device='cpu', verify=True): """(policy in eval mode on `device`, config dict) of a checkpoint directory.""" import torch from .policies import build_policy folder = Path(folder) if verify: protocol = json.loads((folder / 'protocol.json').read_text()) entry = protocol['files']['model.pt'] if (folder / 'model.pt').stat().st_size != entry['bytes']: raise ValueError(f'{folder}/model.pt differs from protocol.json') payload = torch.load(folder / 'model.pt', map_location='cpu', weights_only=True) if payload.get('format') != FORMAT: raise ValueError(f"{folder}: format {payload.get('format')!r}, expected {FORMAT}") config = json.loads(payload['config']) if json.loads((folder / 'config.json').read_text()) != config: raise ValueError(f'{folder}: config.json differs from the one inside model.pt') policy = build_policy(config['policy'], pretrained=False) # every weight comes from model.pt policy.load_state_dict(payload['state_dict'], strict=True) return policy.to(device).eval(), config
class BaselinePolicy: """A loaded checkpoint for closed-loop inference (one request at a time)."""
def __init__(self, checkpoint, device='cuda:0', policy: str | None = None, robot: str | None = None): import torch self.torch = torch self.device = torch.device(device) self.model, self.config = load_checkpoint(checkpoint, device=self.device) self.checkpoint = str(Path(checkpoint).resolve()) name, contract = self.config['policy']['policy'], self.config['contract'] if policy is not None and name != policy: raise ValueError(f'{checkpoint} is a {name!r} checkpoint, not {policy!r}') if robot is not None and contract['robot'] != robot: raise ValueError(f"{checkpoint} was trained for {contract['robot']!r} ({contract['name']}), not {robot!r}") self.name, self.contract = name, contract self.cameras = tuple(contract['cameras']) self.image_hw = tuple(self.config['image_hw']) self.horizon = int(self.config['policy']['horizon']) self.state_dim, self.action_dim = int(contract['state_dim']), int(contract['action_dim']) self.sampling_steps = int(self.model.sampling_steps) self.task_text = self.config.get('task_text')
def info(self) -> dict: return dict(model=self.name, checkpoint=self.checkpoint, step=self.config.get('step'), contract=self.contract['name'], views=list(self.cameras), image_hw=list(self.image_hw), action_chunk=self.horizon, action_dim=self.action_dim, state_dim=self.state_dim, sampling_steps=self.sampling_steps, task_text=self.task_text, training_data=self.config.get('dataset', {}).get('name'))
def images_tensor(self, images: dict): from .data import resize_frame missing = [c for c in self.cameras if c not in images] if missing: raise KeyError(f'missing cameras {missing}; the checkpoint reads {list(self.cameras)}') frames = np.stack([resize_frame(np.asarray(images[c]), self.image_hw) for c in self.cameras]) x = self.torch.from_numpy(frames).to(self.device).permute(0, 3, 1, 2).float().div_(255.) return x.unsqueeze(0) # (1, n_cameras, 3, h, w)
def predict(self, images: dict, state, seed: int = 0): """(action (horizon, action_dim) float32 physical, normalized (horizon, action_dim) float32).""" torch = self.torch state = np.asarray(state, np.float32).reshape(-1) if state.shape != (self.state_dim,) or not np.isfinite(state).all(): raise ValueError(f'expected a finite state of {self.state_dim} values, got {state.shape}') generator = torch.Generator(device=self.device) generator.manual_seed(int(seed) % (2 ** 63 - 1)) with torch.inference_mode(): action, raw = self.model.predict(self.images_tensor(images), torch.from_numpy(state)[None].to(self.device), generator=generator) action = action[0].float().cpu().numpy() if action.shape != (self.horizon, self.action_dim) or not np.isfinite(action).all(): raise ValueError(f'invalid prediction {action.shape}') return np.ascontiguousarray(action, np.float32), raw[0].float().cpu().numpy().astype(np.float32)README.mdAdded+50
a20-basket-transfer/b512-trimv2/step-004000/SHA256SUMSAdded+9
a20-basket-transfer/b512-trimv2/step-004000/config.jsonAdded+884
a20-basket-transfer/b512-trimv2/step-004000/model.ptAdded+3
a20-basket-transfer/b512-trimv2/step-004000/protocol.jsonAdded+11
code/hb_baselines_v1/baselines/__init__.pyAdded+8
code/hb_baselines_v1/baselines/act_nets.pyAdded+615
code/hb_baselines_v1/baselines/nets.pyAdded+207
code/hb_baselines_v1/baselines/policies.pyAdded+281
code/hb_baselines_v1/baselines/requirements.txtAdded+12
code/hb_baselines_v1/baselines/runtime.pyAdded+123