File size: 34,616 Bytes
99e41a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2ead12
99e41a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bfc70a
99e41a8
6bfc70a
99e41a8
6bfc70a
caa90b0
 
 
 
 
 
 
 
f4fdc38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
caa90b0
 
 
 
99e41a8
 
 
6bfc70a
99e41a8
6bfc70a
99e41a8
 
 
6bfc70a
99e41a8
6bfc70a
99e41a8
6bfc70a
99e41a8
6bfc70a
99e41a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
caa90b0
99e41a8
 
 
 
 
 
 
 
 
 
 
caa90b0
 
 
 
 
99e41a8
 
 
 
 
 
 
 
6bfc70a
 
99e41a8
 
caa90b0
f4fdc38
 
caa90b0
 
 
 
99e41a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4fdc38
caa90b0
 
99e41a8
caa90b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99e41a8
 
6bfc70a
 
 
 
 
caa90b0
 
 
 
 
 
 
 
 
6bfc70a
 
 
 
 
 
 
 
 
caa90b0
f4fdc38
 
caa90b0
 
6bfc70a
caa90b0
6bfc70a
 
 
 
 
 
 
99e41a8
 
 
 
 
 
 
 
 
 
caa90b0
 
99e41a8
6bfc70a
99e41a8
 
 
 
 
 
 
 
654707f
99e41a8
 
 
 
 
 
 
caa90b0
 
b2ead12
caa90b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2ead12
caa90b0
 
 
 
 
 
 
 
 
 
 
 
 
b2ead12
 
 
 
 
 
caa90b0
 
 
 
 
 
 
b2ead12
 
caa90b0
 
 
 
 
 
b2ead12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
caa90b0
 
 
 
 
 
 
 
 
99e41a8
 
caa90b0
 
99e41a8
 
654707f
99e41a8
caa90b0
 
 
 
654707f
 
 
 
 
99e41a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
caa90b0
 
b2ead12
 
caa90b0
99e41a8
 
 
 
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
#!/usr/bin/env python3
"""Publish the full RoboRACE work to Hugging Face (token from the HF_TOKEN environment variable only).

  HF_TOKEN=... python scripts/publish_hf.py [--dry-run]

Creates / updates
  datasets/<owner>/RoboRACE-Bench   everything: code, docs, tests, cached agent outputs, leaderboards,
                                    figures, videos and the 1,100 SO-101 camera renders (image viewer config)
  spaces/<owner>/RoboRACE           static showcase page (hf_space/index.html) with playing videos

Not uploaded: third-party assets (MuJoCo Menagerie meshes, PlotNeuralNet, ERQA / PlanBench source data:
they are public under their own terms; scripts/fetch_assets.sh downloads them), secrets, virtualenvs.
"""
import argparse
import json
import os
import re
import shutil
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
OWNER = "Nabidnur"
DS = f"{OWNER}/RoboRACE-Bench"
SPACE = f"{OWNER}/RoboRACE"
GH = "https://github.com/Hisernberg/robotics"
RES = f"https://huggingface.co/datasets/{DS}/resolve/main"
BLOB = f"https://huggingface.co/datasets/{DS}/blob/main"
STAGE = Path(os.environ.get("HF_STAGE", str(ROOT / ".hf_stage")))

CODE = ["src", "scripts", "tests", "docs", "results", "media", "models", "kaggle", "requirements.txt", "pyproject.toml", ".env.example",
        ".gitattributes"]


def card_yaml():
    return """---
pretty_name: RoboRACE-Bench
license: other
license_name: roborace-mixed
license_link: https://huggingface.co/datasets/Nabidnur/RoboRACE-Bench/blob/main/LICENSES.md
language:
- en
task_categories:
- robotics
- visual-question-answering
- image-classification
tags:
- robotics
- multi-agent
- byzantine-robustness
- truth-inference
- vlm
- llm-agents
- so-101
- mujoco
- erqa
- planbench
- cosmos-reason
size_categories:
- 1K<n<10K
configs:
- config_name: so101_views
  data_files:
  - split: history
    path: viewer/so101_views/history.parquet
  - split: evaluation
    path: viewer/so101_views/evaluation.parquet
- config_name: so101_vlm_scores
  data_files: viewer/so101_vlm_scores/train.parquet
- config_name: panda_views
  data_files:
  - split: history
    path: viewer/panda_views/history.parquet
  - split: evaluation
    path: viewer/panda_views/evaluation.parquet
- config_name: panda_vlm_scores
  data_files: viewer/panda_vlm_scores/train.parquet
- config_name: so101_holdout_views
  data_files:
  - split: history
    path: viewer/so101_holdout_views/history.parquet
  - split: evaluation
    path: viewer/so101_holdout_views/evaluation.parquet
- config_name: so101_holdout_vlm_scores
  data_files: viewer/so101_holdout_vlm_scores/train.parquet
- config_name: panda_holdout_views
  data_files:
  - split: history
    path: viewer/panda_holdout_views/history.parquet
  - split: evaluation
    path: viewer/panda_holdout_views/evaluation.parquet
- config_name: panda_holdout_vlm_scores
  data_files: viewer/panda_holdout_vlm_scores/train.parquet
- config_name: trackD_maze_results
  data_files: viewer/trackD_maze_results/train.parquet
- config_name: maze_llm_agents
  data_files: viewer/maze_llm_agents/train.parquet
- config_name: erqa_cosmos_reason2_2b
  data_files:
  - split: px448
    path: viewer/erqa_cosmos_reason2_2b/px448.parquet
  - split: px768
    path: viewer/erqa_cosmos_reason2_2b/px768.parquet
- config_name: erqa_hosted_agents
  data_files:
  - split: test
    path: viewer/erqa_hosted_agents/test.parquet
- config_name: planbench_agents
  data_files: viewer/planbench_agents/train.parquet
- config_name: trackC_llm_planners
  data_files: viewer/trackC_llm_planners/train.parquet
- config_name: trackA0_procedural_scores
  data_files: viewer/trackA0_procedural_scores/train.parquet
---
"""


def hf_body(readme: str) -> str:
    """GitHub README -> HF card body: absolute URLs, video players, dataset-specific sections."""
    body = readme
    # absolute URLs for media (resolve) and documents (blob)
    body = re.sub(r'(src|href)="(media/[^"]+)"', lambda m: f'{m.group(1)}="{RES}/{m.group(2)}"', body)
    tree = f"https://huggingface.co/datasets/{DS}/tree/main"
    body = re.sub(r'\]\((media/[^)]+)\)',
                  lambda m: f"]({(RES if '.' in m.group(1).rsplit('/', 1)[-1] else tree)}/{m.group(1)})", body)
    body = re.sub(r'(href)="((?:results|docs)/[^"]+)"', lambda m: f'{m.group(1)}="{BLOB}/{m.group(2)}"', body)
    body = re.sub(r'\]\(((?:results|docs)/[^)#]+)(#[^)]*)?\)', lambda m: f"]({BLOB}/{m.group(1)}{m.group(2) or ''})", body)
    # the headline links line: point code links to GitHub, keep the rest
    hf_intro = f"""
> **This is the Hugging Face home of RoboRACE.** It holds the complete, detailed work: code, the cached outputs of every
> agent (VLMs, LLMs, simulated robots), per-cell benchmark results, leaderboards, figures, videos and the 1,100 SO-101
> camera renders for each of two robot arms. Code is mirrored on GitHub: [{GH.replace('https://', '')}]({GH}). Showcase page: [Space · {SPACE}](https://huggingface.co/spaces/{SPACE}) · interactive: [Space · liar playground](https://huggingface.co/spaces/{OWNER}/RoboRACE-Playground) · model: [{OWNER}/RoboRACE-Net](https://huggingface.co/{OWNER}/RoboRACE-Net).

## Videos

<table><tr>
<td width="50%"><video controls muted loop playsinline width="100%" src="{RES}/media/videos/robot_rollouts.mp4"></video><br>
<sub><b>SO-101 camera swarm</b>: three physics rollouts, five Cosmos-Reason2 camera agents, honest swarm vs 3-of-5 liars.</sub></td>
<td width="50%"><video controls muted loop playsinline width="100%" src="{RES}/media/videos/swarm_rendezvous.mp4"></video><br>
<sub><b>Byzantine rendezvous</b>: 12 robots, 4 colluding liars — DeGroot vs W-MSR vs RACE-C + W-MSR.</sub></td>
</tr><tr>
<td width="50%"><video controls muted loop playsinline width="100%" src="{RES}/media/videos/planbench_modulo.mp4"></video><br>
<sub><b>PlanBench LLM-Modulo</b>: a real cached LLM plan is rejected by the exact simulator and repaired.</sub></td>
<td width="50%"><video controls muted loop playsinline width="100%" src="{RES}/media/videos/maze_swarm.mp4"></video><br>
<sub><b>Maze swarm (Track D)</b>: three of six robots invert their map reports — majority map vs RACE map.</sub></td>
</tr><tr>
<td width="50%"><video controls muted loop playsinline width="100%" src="{RES}/media/videos/panda_rollouts.mp4"></video><br>
<sub><b>Franka Panda camera swarm</b>: the cross-embodiment replication.</sub></td>
<td width="50%"><video controls muted loop playsinline width="100%" src="{RES}/media/videos/camera_swarm.mp4"></video><br>
<sub><b>Track A0</b> (first iteration): procedural scenes judged by the same camera swarm.</sub></td>
</tr></table>

## What is in this repository

| path | content |
|---|---|
| `data/so101/{{hist,eval}}/<seed>/<camera>.png` | 220 SO-101 episodes × 5 cameras (448×448), with per-split `metadata.jsonl` |
| `viewer/<config>/*.parquet` | Parquet copies behind the dataset viewer; **`so101_views`** embeds every image with its task, physics label, failure mode and Cosmos score |
| `data/so101/episodes.jsonl` | per-episode metadata: task, family (put / stack), scripted mode, **physics ground truth**, final object pose |
| `results/so101/vlm_scores.jsonl` | Cosmos-Reason2-2B P(success) for every (episode, camera) — config **`so101_vlm_scores`** |
| `data/panda/...`, `results/panda/vlm_scores.jsonl` | the same for the **Franka Panda** replication (220 episodes × 5 cameras) — configs **`panda_views`**, **`panda_vlm_scores`** |
| `data/*_holdout/...`, `results/*_holdout/vlm_scores.jsonl`, `results/holdout/FREEZE.json` | the **hold-out**: 170 new episodes per arm, evaluated only after the recorded freeze commit — configs **`so101_holdout_views`**, **`panda_holdout_views`** and the matching `*_vlm_scores` |
| `models/racenet`, `models/racenet_m` | weights of both models (**RACE-Net-V**, **RACE-Net-M**) and every candidate checkpoint |
| `results/trackD/rows.json` | Track D maze swarm: SPL and success of every fusion rule in every (maze, attack, liar-count) cell — config **`trackD_maze_results`** |
| `results/maze_llm/<agent>.jsonl` | LLM agents on text mazes: every attempt, validator feedback, repair count — config **`maze_llm_agents`** |
| `models/racenet/` | RACE-Net weights (safetensors), config and training log; also at [Nabidnur/RoboRACE-Net](https://huggingface.co/Nabidnur/RoboRACE-Net) |
| `results/kaggle/` | independent replication run on Kaggle CPU (log + comparison) |
| `results/erqa/cosmos_r2_2b*.jsonl` | ERQA: full option distributions for all 400 questions at ≤448² and ≤768² px — config **`erqa_cosmos_reason2_2b`** |
| `results/erqa/<agent>.jsonl` | ERQA answers + raw replies of hosted VLM agents (Gemini, Qwen, Gemma, Gemini Robotics-ER) — config **`erqa_hosted_agents`** |
| `results/planbench/<agent>.jsonl` | PlanBench Blocksworld: every attempt, parsed plan, validator verdict, repair count — config **`planbench_agents`** |
| `results/trackC/answers.jsonl` | Track C: zero-shot / engineered / saboteur answers of 4 LLMs — config **`trackC_llm_planners`** |
| `results/*/rows.json`, `results/leaderboard.json`, `results/LEADERBOARD.md` | per-cell results of every method under every attack and receiver; bootstrap-ranked leaderboards |
| `media/` | figures, architecture diagrams (Raschka style + PlotNeuralNet), videos (MP4 + GIF) |
| `src/`, `scripts/`, `tests/`, `docs/` | the full code base, protocol ([BENCHMARK]({BLOB}/docs/BENCHMARK.md)) and research plan ([PLAN]({BLOB}/docs/PLAN.md)) |

```python
from datasets import load_dataset
views  = load_dataset("{DS}", "so101_views", split="evaluation")      # images + labels
scores = load_dataset("{DS}", "so101_vlm_scores", split="train")      # Cosmos-Reason2 P(success) per camera
erqa   = load_dataset("{DS}", "erqa_cosmos_reason2_2b", split="px448")
plans  = load_dataset("{DS}", "planbench_agents", split="train")
```

Re-run every number on a CPU from this repository:
```bash
huggingface-cli download {DS} --repo-type dataset --local-dir RoboRACE-Bench && cd RoboRACE-Bench
pip install -r requirements.txt && python scripts/run_benchmark.py --reuse-tracks && python scripts/make_figures.py
```
"""
    # insert after the closing </div> of the hero block
    i = body.index("</div>") + len("</div>")
    body = body[:i] + "\n" + hf_intro + body[i:]
    body = body.replace("<sub>This README is generated by <code>scripts/make_readme.py</code>",
                        "<sub>This card is generated by <code>scripts/publish_hf.py</code> from the GitHub README, which is generated by <code>scripts/make_readme.py</code>")
    return body


LICENSES = f"""# Licenses

RoboRACE-Bench mixes original work with third-party material. Each part keeps its own terms.

| component | terms |
|---|---|
| Original code, cached agent outputs, results, figures, videos, SO-101 renders (this repository) | © the repository owner. A formal open-source license has not been chosen yet; until then, use for research and evaluation with attribution to [{GH}]({GH}) and this dataset. |
| `src/robotics/swarm/race.py` (RACE v3.1 port) | MIT, from `Nabidnur/gemma4-race-pack` / `Nabidnur/liars-are-information` |
| SO-101 robot model used to render `data/so101` | MuJoCo Menagerie `robotstudio_so101`, Apache-2.0 (not redistributed here) |
| ERQA questions / images | Gemini Robotics team, via `FlagEval/ERQA`; **not redistributed** — only question ids and model answers are stored |
| PlanBench instances | Valmeekam et al., MIT; **not redistributed** — only instance ids, model plans and verdicts are stored |
| Cosmos-Reason2-2B outputs | produced with `nvidia/Cosmos-Reason2-2B` under the NVIDIA Open Model License |
| Hosted-model outputs (Gemini, Qwen, Gemma, gpt-oss) | produced through the providers' APIs; subject to the respective providers' terms |
"""


ROBOTS = [r for r in ("so101", "panda", "so101_holdout", "panda_holdout") if (ROOT / f"data/{r}/episodes.jsonl").exists() and (ROOT / f"results/{r}/vlm_scores.jsonl").exists()]


def so101_metadata():
    for robot in ROBOTS:
        eps = {e["seed"]: e for e in map(json.loads, open(ROOT / f"data/{robot}/episodes.jsonl"))}
        scores = {}
        for r in map(json.loads, open(ROOT / f"results/{robot}/vlm_scores.jsonl")):
            scores[(r["scene"], r["camera"])] = r["p"]
        for split in ("hist", "eval"):
            with open(STAGE / f"data/{robot}/{split}/metadata.jsonl", "w") as f:
                for seed, e in sorted(eps.items()):
                    if e["split"] != split:
                        continue
                    for cam in ("front", "left", "right", "back", "top"):
                        f.write(json.dumps({"file_name": f"{seed}/{cam}.png", "robot": robot, "seed": seed, "camera": cam,
                                            "task": e["task"], "family": e["family"], "scripted_mode": e["mode"],
                                            "success_physics": e["success"],
                                            "cosmos_p_success": scores.get((seed, cam))}) + "\n")


def viewer_parquet():
    """One loader for every viewer config: Parquet (the `datasets` library infers a single builder per repo,
    so mixing an image folder with JSONL configs breaks the JSONL ones). Originals stay in results/ and data/."""
    from datasets import Dataset, Image, load_dataset
    v = STAGE / "viewer"
    for robot in ROBOTS:
        for split, name in (("hist", "history"), ("eval", "evaluation")):
            rows = [json.loads(line) for line in open(STAGE / f"data/{robot}/{split}/metadata.jsonl")]
            for r in rows:   # embed the PNG bytes (to_parquet would otherwise store local paths)
                fn = r.pop("file_name")
                r["image"] = {"bytes": (STAGE / f"data/{robot}/{split}/{fn}").read_bytes(), "path": fn.replace("/", "_")}
            ds = Dataset.from_list(rows).cast_column("image", Image())
            (v / f"{robot}_views").mkdir(parents=True, exist_ok=True)
            ds.to_parquet(str(v / f"{robot}_views" / f"{name}.parquet"))
    jsonl = {
        "so101_vlm_scores/train": ["results/so101/vlm_scores.jsonl"],
        "erqa_cosmos_reason2_2b/px448": ["results/erqa/cosmos_r2_2b.jsonl"],
        "erqa_cosmos_reason2_2b/px768": ["results/erqa/cosmos_r2_2b_768px.jsonl"],
        "erqa_hosted_agents/test": sorted(str(p.relative_to(STAGE)) for p in (STAGE / "results/erqa").glob("*.jsonl")
                                          if not p.name.startswith("cosmos_r2_2b")),
        "planbench_agents/train": sorted(str(p.relative_to(STAGE)) for p in (STAGE / "results/planbench").glob("*.jsonl")),
        "trackC_llm_planners/train": ["results/trackC/answers.jsonl"],
        "trackA0_procedural_scores/train": ["results/trackA/vlm_scores.jsonl"],
        "panda_vlm_scores/train": ["results/panda/vlm_scores.jsonl"],
        "so101_holdout_vlm_scores/train": ["results/so101_holdout/vlm_scores.jsonl"],
        "panda_holdout_vlm_scores/train": ["results/panda_holdout/vlm_scores.jsonl"],
        "trackD_maze_results/train": ["results/trackD/rows.json"],
        "maze_llm_agents/train": sorted(str(p.relative_to(STAGE)) for p in (STAGE / "results/maze_llm").glob("*.jsonl")),
    }
    jsonl = {k: f for k, f in jsonl.items() if f and all((STAGE / x).exists() for x in f)}
    for key, files in jsonl.items():
        ds = load_dataset("json", data_files=[str(STAGE / f) for f in files], split="train")
        (v / key.split("/")[0]).mkdir(parents=True, exist_ok=True)
        ds.to_parquet(str(v / f"{key}.parquet"))
        print(f"viewer/{key}.parquet  {len(ds)} rows")


def stage():
    if STAGE.exists():
        shutil.rmtree(STAGE)
    STAGE.mkdir(parents=True)
    for item in CODE:
        src = ROOT / item
        if src.is_dir():
            shutil.copytree(src, STAGE / item, ignore=shutil.ignore_patterns("__pycache__", "*.pyc", "*.pal.png"))
        elif src.exists():
            shutil.copy2(src, STAGE / item)
    for robot in ROBOTS:
        shutil.copytree(ROOT / f"data/{robot}", STAGE / f"data/{robot}")
    so101_metadata()
    viewer_parquet()
    (STAGE / "README.md").write_text(card_yaml() + hf_body((ROOT / "README.md").read_text()))
    (STAGE / "LICENSES.md").write_text(LICENSES)
    n = sum(1 for _ in STAGE.rglob("*") if _.is_file())
    size = sum(p.stat().st_size for p in STAGE.rglob("*") if p.is_file()) / 1e6
    print(f"staged {n} files, {size:.1f} MB in {STAGE}")


def publish_space(api, token):
    sys.path.insert(0, str(Path(__file__).resolve().parent))
    from make_space import build
    sp = build(STAGE.parent / (STAGE.name + "_space"))
    api.create_repo(SPACE, repo_type="space", space_sdk="static", exist_ok=True, token=token)
    api.upload_folder(repo_id=SPACE, repo_type="space", folder_path=str(sp), token=token,
                      commit_message="RoboRACE showcase page")


MODEL = f"{OWNER}/RoboRACE-Net"
PLAY = f"{OWNER}/RoboRACE-Playground"
MODEL_M = f"{OWNER}/RoboRACE-Net-M"


sys.path.insert(0, str(Path(__file__).resolve().parent))
import racenet_report  # noqa: E402


def model_card():
    lb = json.loads((ROOT / "results/leaderboard.json").read_text())
    cfg = json.loads((ROOT / "models/racenet/config.json").read_text())
    log = json.loads((ROOT / "models/racenet/training_log.json").read_text())
    net = "race_net (new, learned)"

    def g(track, m, key="mean_acc"):
        r = next((r for r in lb.get(track, []) if r["method"] == m), None)
        return f"{100 * r[key]:.1f}" if r else "–"
    rows = "\n".join(f"| {lab} | {g('A0', m)} | {g('A', m)} | {g('AP', m)} | {g('A', m, 'majority_liars')} | {g('AP', m, 'majority_liars')} |"
                     for lab, m in (("majority vote", "majority"), ("Dawid–Skene (crowd-kit)", "DS (crowd-kit)"), ("receiver alone", "receiver_only"),
                                    ("RACE online (EM)", "race_online (new)"), ("RACE-S online (EM)", "race_s_online (new)"),
                                    ("**RACE-Net (this model)**", net), ("labelled stacker (reference)", "REF stack_lr (labelled)")))
    metrics = "\n".join(f"""  - task: {{type: other, name: Label-free swarm fusion under attack}}
    dataset: {{name: RoboRACE-Bench {nm}, type: {DS}, config: {cfgn}, split: evaluation}}
    metrics:
    - {{type: accuracy, value: {g(tr, net)}, name: mean accuracy over all attack cells}}""" for tr, nm, cfgn in
                        (("A", "Track A SO-101", "so101_vlm_scores"), ("AP", "Track A-Panda", "panda_vlm_scores")) if g(tr, net) != "–")
    return f"""---
license: other
license_name: roborace-mixed
license_link: https://huggingface.co/datasets/{DS}/blob/main/LICENSES.md
library_name: pytorch
pipeline_tag: other
tags: [robotics, multi-agent, byzantine-robustness, truth-inference, set-transformer, in-context-learning, roborace]
datasets: [{DS}]
model-index:
- name: RACE-Net
  results:
{metrics}
---

# RACE-Net — amortized receiver-anchored truth inference

**A {cfg['n_params']:,}-parameter axial set transformer that fuses the reports of a swarm of agents when some of them lie.**
Part of [RoboRACE](https://huggingface.co/datasets/{DS}) · [showcase Space](https://huggingface.co/spaces/{SPACE}) · code: [{GH.replace('https://', '')}]({GH})

<p align="center"><img src="racenet_architecture.png" width="620"></p>

## What it does

A robot (the *receiver*) gets, for each of T recent episodes, a score in [0, 1] from each of J agents (for example P(task succeeded) from
J camera + VLM pairs). Some agents may be inverted, stuck, random, colluding or replicated. RACE-Net reads the whole unlabelled window at once
and returns the log-odds of success for every episode. It assumes only one thing: **the receiver's own column is honest** (the anchor of
[RACE](https://huggingface.co/spaces/Nabidnur/liars-are-information-demo)). Consistent liars are not discarded: their reports are effectively inverted and used.

- **Input:** `P` with shape `[T, J]`, any T and J (the model has no positional encodings; it is permutation-equivariant over episodes and peers).
- **Pre-processing:** per-agent rank → probit within the window (label-free, invariant to any monotone miscalibration).
- **Blocks ({cfg['layers']}×):** attention across agents within an episode → attention across episodes within an agent → MLP (d = {cfg['d']}, {cfg['heads']} heads).
- **Output:** one logit per episode; decide `> 0`.

## Use

```python
import sys, numpy as np
from huggingface_hub import snapshot_download
d = snapshot_download("{MODEL}"); sys.path.insert(0, d)
import racenet

P = np.random.rand(100, 5)                 # [episodes, agents] scores in [0, 1]; column `own` is the receiver
log_odds, thr = racenet.race_net(None, P, own=0, path=d)
success = log_odds > thr
```
Runs on CPU in a few milliseconds per window. Dependencies: `torch`, `numpy`, `safetensors`.

## Training

Synthetic swarms only (`racenet.sample_batch`): heterogeneous agent skill, correlated honest errors, yes-bias, and an attack zoo with up to
J−1 liars. **No benchmark data, labels or agent outputs were used.** {cfg['training']['steps']:,} AdamW steps, batch {cfg['training']['batch']},
one-cycle LR {cfg['training']['lr']}, CPU only. Held-out synthetic accuracy at the end: {100 * log[-1]['val_acc_synthetic']:.1f}%.

## Evaluation (zero-shot on real VLM camera swarms)

Agents are five cameras scored by Cosmos-Reason2-2B; ground truth is the final physics state of a simulated robot arm. Each cell is one
(attack, liar count, liar subset, receiver); numbers are mean accuracy in %.

| method (label-free unless noted) | A0 procedural (development) | SO-101 (test) | Franka Panda (fresh test) | SO-101, liars ≥ 50% | Panda, liars ≥ 50% |
|---|---:|---:|---:|---:|---:|
{rows}

<p align="center"><img src="racenet_results.png" width="900"></p>

{racenet_report.selection_md()}
## Scaling study

{racenet_report.scaling_md("racenet_scaling.png")}
## Limitations

- It matches the EM-based methods but does not beat the best of them (RACE-S online) on the real camera swarms (see the table).
- Trained on a hand-written simulator of swarms. Where real agent errors differ from it, the EM-based RACE-S can be better.
- The receiver must be honest and better than chance; with a very weak receiver and a liar majority no label-free method can identify the truth.
- Fits on the current window (transductive); a sleeper that changes behaviour inside the window is treated as one mixed channel.
- Binary truth only. Evaluated in simulation with one VLM behind all cameras.

## Files
`model.safetensors` · `config.json` · `training_log.json` · `selection.json` + `candidates/` (all three checkpoints) · `racenet.py` (model, synthetic
generators, inference) · `train_racenet.py` · `select_racenet.py` · `racenet_analysis.py` + `analysis.json` (scaling study)
"""


def publish_model(api, token):
    md = STAGE.parent / (STAGE.name + "_model")
    if md.exists():
        shutil.rmtree(md)
    md.mkdir(parents=True)
    for f in ("model.safetensors", "config.json", "training_log.json"):
        shutil.copy2(ROOT / "models/racenet" / f, md / f)
    shutil.copy2(ROOT / "src/robotics/swarm/racenet.py", md / "racenet.py")
    shutil.copy2(ROOT / "scripts/train_racenet.py", md / "train_racenet.py")
    pkg = md / "robotics/swarm"                      # minimal package so that the EM experts can be imported
    pkg.mkdir(parents=True)
    (md / "robotics/__init__.py").write_text("")
    (pkg / "__init__.py").write_text("")
    for f in ("racenet.py", "fusion.py", "race.py"):
        shutil.copy2(ROOT / "src/robotics/swarm" / f, pkg / f)
    shutil.copy2(ROOT / "media/architecture/racenet.png", md / "racenet_architecture.png")
    shutil.copy2(ROOT / "media/figures/racenet.png", md / "racenet_results.png")
    for src, dst in (("models/racenet/selection.json", "selection.json"), ("media/figures/racenet_scaling.png", "racenet_scaling.png"),
                     ("results/racenet/analysis.json", "analysis.json"), ("scripts/racenet_analysis.py", "racenet_analysis.py"),
                     ("scripts/select_racenet.py", "select_racenet.py")):
        if (ROOT / src).exists():
            shutil.copy2(ROOT / src, md / dst)
    if (ROOT / "models/racenet/candidates").exists():
        shutil.copytree(ROOT / "models/racenet/candidates", md / "candidates")
    (md / "README.md").write_text(model_card())
    api.create_repo(MODEL, repo_type="model", exist_ok=True, token=token)
    api.upload_folder(repo_id=MODEL, repo_type="model", folder_path=str(md), token=token, commit_message="RACE-Net weights, card and code")
    print("model:", f"https://huggingface.co/{MODEL}")


def model_card_m():
    lb = json.loads((ROOT / "results/leaderboard.json").read_text())
    cfg = json.loads((ROOT / "models/racenet_m/config.json").read_text())
    log = json.loads((ROOT / "models/racenet_m/training_log.json").read_text())
    D = {r["method"]: r for r in lb.get("D", [])}
    succ = lb.get("D_success", {})
    names = {"race_net_m + reach-repair": "**RACE-Net-M + reachability repair (this model)**", "race_net_m": "**RACE-Net-M (this model)**",
             "race_map": "race_map (hand-written Bayesian rule, ours)", "wmsr_trim": "W-MSR-style trimming (LeBlanc et al. 2013; F known)",
             "reputation": "beta-reputation (Jøsang & Ismail 2002)", "eigentrust": "EigenTrust (Kamvar et al. 2003)",
             "dawid_skene": "Dawid–Skene (1979), unanchored", "solo": "no communication", "trust_all": "naive map merging",
             "majority": "per-cell majority", "REF oracle": "*oracle that knows the liars (reference)*"}
    rows = "\n".join(f"| {('%d' % r['rank']) if 'rank' in r else '–'} | {names.get(m, m)} | {100 * r['mean_acc']:.1f} | {100 * r['clean']:.1f} | "
                     f"{100 * r['minority_liars']:.1f} | {100 * r['majority_liars']:.1f} | {100 * succ.get(m, float('nan')):.1f} |" for m, r in D.items())
    ab = json.loads((ROOT / "results/racenet_m/ablation.json").read_text())
    ab_rows = "\n".join(f"| {r['model']} | {100 * r['val_cell_acc']:.1f} | {100 * r['by_liars']['3'][0]:.1f} | {100 * r['by_liars']['5'][0]:.1f} |" for r in ab["rows"])
    b0 = ab["rows"][0]
    net = D.get("race_net_m + reach-repair", {}).get("mean_acc")
    metrics = f"""  - task: {{type: other, name: Byzantine-robust map fusion}}
    dataset: {{name: RoboRACE-Bench Track D, type: {DS}, config: trackD_maze_results, split: train}}
    metrics:
    - {{type: spl, value: {100 * net:.1f}, name: mean SPL x100 over 500 cells}}""" if net else ""
    return f"""---
license: other
license_name: roborace-mixed
license_link: https://huggingface.co/datasets/{DS}/blob/main/LICENSES.md
library_name: pytorch
pipeline_tag: other
tags: [robotics, multi-agent, byzantine-robustness, map-fusion, truth-inference, set-transformer, roborace]
datasets: [{DS}]
model-index:
- name: RACE-Net-M
  results:
{metrics}
---

# RACE-Net-M — receiver-anchored channel estimation for map fusion

**A {cfg['n_params']:,}-parameter model that fuses the map reports of a robot swarm when some robots lie.**
Part of [RoboRACE](https://huggingface.co/datasets/{DS}) · sibling model for camera swarms: [RACE-Net-V](https://huggingface.co/{MODEL}) ·
[showcase Space](https://huggingface.co/spaces/{SPACE}) · code: [{GH.replace('https://', '')}]({GH})

<p align="center"><img src="racenet_m_architecture.png" width="640"></p>

## What it does

Robots explore an unknown map and broadcast what they sensed (cell is *free* / *wall*). Some robots corrupt their broadcasts: they invert
everything, invent walls or openings, answer at random, turn bad later, or collude. A receiving robot has to decide which cells are walls.
RACE-Net-M returns the log-odds of *wall* for every reported cell. It assumes one thing only: **the receiver's own sensor is right**.

1. **Anchored counts.** Each peer's claims are compared with the cells the receiver sensed itself (claim × truth, recent and old claims apart).
2. **Peer transformer.** A small transformer across peers turns the counts into a channel embedding per peer.
3. **Signed read-out.** Each kind of claim gets a signed evidence value: a reliable peer is trusted, a consistent liar is *inverted and used*,
   a random one is ignored. Reputation systems can only discard a liar.
4. **Refinement ({cfg['rounds']} rounds).** Each peer is also checked against the belief of all the *other* peers on cells the receiver has not
   sensed (leave-one-out), so a robot can verify a peer it never overlapped with through a peer it already trusts.

Peers and cells are sets (no positions): any map size and any swarm size.

## Use

```python
import sys, numpy as np
from huggingface_hub import snapshot_download
d = snapshot_download("{MODEL_M}"); sys.path.insert(0, d)
import racenet_m

# own   [H, W]    the receiver's own observations: -1 unknown, 0 free, 1 wall
# claims [n, H, W] latest broadcast of every robot (same coding); stamp [n, H, W] time of that broadcast
log_odds = racenet_m.wall_logodds(own, claims, stamp, i=0, t=now, path=d)   # i = index of the receiver
wall = log_odds > 2.0                                                        # threshold chosen on development mazes
```
About 2 ms per call on one CPU core. Dependencies: `torch`, `numpy`, `safetensors`.

## Training

{cfg['training']['snapshots']:,} snapshots from simulated maze swarms (maze seeds {cfg['training']['train_seeds'][0]}–{cfg['training']['train_seeds'][1]}) in which liars follow
**random two-coin channels with an optional change point** (`racenet_m.sample_channels`). The benchmark's attack names never appear in training,
and the colluding ring attack is outside that family. {cfg['training']['steps']:,} AdamW steps on a CPU ({log[-1]['minutes']:.0f} min including the
simulation). Benchmark mazes (seeds 1000–1019) and tuning mazes (seeds 0–39) are disjoint from training and validation mazes.

## Evaluation: RoboRACE Track D

Six robots, 20 fresh mazes × 25 conditions (6 attacks × 1–4 liars, plus the clean case) = 500 cells. Score = SPL ×100 (success weighted by path
length) of the honest robots. Ranks are medians over 2,000 bootstrap resamples of cells.

| rank | fusion rule | mean SPL | no liars | liars < 50% | liars ≥ 50% | goal reached % |
|---:|---|---:|---:|---:|---:|---:|
{rows}

<p align="center"><img src="trackD_vs_liars.png" width="900"></p>

Belief quality on held-out mazes (accuracy on cells a peer reported and the receiver has not sensed):

| model | all | 3 of 5 peers lie | 5 of 5 peers lie |
|---|---:|---:|---:|
| race_map (hand-written Bayesian rule) | {100 * b0['val_cell_acc_bma']:.1f} | {100 * b0['by_liars']['3'][1]:.1f} | {100 * b0['by_liars']['5'][1]:.1f} |
{ab_rows}

## Limitations

- **Collusion on a few cells.** A bloc that is honest everywhere except around the goal looks reliable until a robot gets there; the
  reachability repair recovers part of the loss, the oracle is still better.
- One simulator (grid mazes, exact 8-neighbour sensing, six robots). Not tested on real robots or noisy sensors.
- Claims are assumed conditionally independent given the truth; the model has no notion of where a peer was when it made a claim.

## Files
`model.safetensors` · `config.json` · `training_log.json` · `ablation.json` · `racenet_m.py` (model, training distribution, inference) ·
`train_racenet_m.py` · `trackD.py` (the benchmark, baselines and planner)
"""


def publish_model_m(api, token):
    md = STAGE.parent / (STAGE.name + "_model_m")
    if md.exists():
        shutil.rmtree(md)
    md.mkdir(parents=True)
    for f in ("model.safetensors", "config.json", "training_log.json"):
        shutil.copy2(ROOT / "models/racenet_m" / f, md / f)
    for src, dst in (("src/robotics/swarm/racenet_m.py", "racenet_m.py"), ("scripts/train_racenet_m.py", "train_racenet_m.py"),
                     ("src/robotics/bench/trackD.py", "trackD.py"), ("results/racenet_m/ablation.json", "ablation.json"),
                     ("media/architecture/racenet_m.png", "racenet_m_architecture.png"), ("media/figures/trackD_vs_liars.png", "trackD_vs_liars.png")):
        shutil.copy2(ROOT / src, md / dst)
    (md / "README.md").write_text(model_card_m())
    api.create_repo(MODEL_M, repo_type="model", exist_ok=True, token=token)
    api.upload_folder(repo_id=MODEL_M, repo_type="model", folder_path=str(md), token=token, commit_message="RACE-Net-M weights, card and code")
    print("model:", f"https://huggingface.co/{MODEL_M}")


def publish_playground(api, token):
    sys.path.insert(0, str(Path(__file__).resolve().parent))
    from make_playground import build
    sp = build(STAGE.parent / (STAGE.name + "_play"))
    api.create_repo(PLAY, repo_type="space", space_sdk="static", exist_ok=True, token=token)
    api.upload_folder(repo_id=PLAY, repo_type="space", folder_path=str(sp), token=token, commit_message="RoboRACE liar playground")
    print("playground:", f"https://huggingface.co/spaces/{PLAY}")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--model-only", action="store_true")
    ap.add_argument("--playground-only", action="store_true")
    ap.add_argument("--dry-run", action="store_true")
    ap.add_argument("--skip-space", action="store_true")
    ap.add_argument("--space-only", action="store_true")
    a = ap.parse_args()
    if a.model_only or a.playground_only:
        from huggingface_hub import HfApi
        (publish_model if a.model_only else publish_playground)(HfApi(), os.environ["HF_TOKEN"])
        return
    if a.space_only:
        from huggingface_hub import HfApi
        publish_space(HfApi(), os.environ["HF_TOKEN"])
        print("space:", f"https://huggingface.co/spaces/{SPACE}")
        return
    stage()
    if a.dry_run:
        return
    token = os.environ.get("HF_TOKEN")
    if not token:
        sys.exit("set HF_TOKEN")
    from huggingface_hub import HfApi
    api = HfApi()
    api.create_repo(DS, repo_type="dataset", exist_ok=True, token=token)
    api.upload_folder(repo_id=DS, repo_type="dataset", folder_path=str(STAGE), token=token,
                      commit_message="RoboRACE: code, cached agent outputs, results, media, SO-101 renders")
    print("dataset:", f"https://huggingface.co/datasets/{DS}")
    if not a.skip_space:
        publish_space(api, token)
        print("space:", f"https://huggingface.co/spaces/{SPACE}")
        if (ROOT / "models/racenet/model.safetensors").exists():
            publish_model(api, token)
        if (ROOT / "models/racenet_m/model.safetensors").exists():
            publish_model_m(api, token)
        publish_playground(api, token)


if __name__ == "__main__":
    main()