cocogni4d / code /tools /stage.py
VEHwang's picture
Upload CoCogni4D-Bench (questions, media, scripts, render records, code) (part 7)
7ff74f6 verified
Raw History Blame Contribute Delete
17.2 kB
#!/usr/bin/env python3
"""Stage the CoCogni4D-Bench HuggingFace upload tree (v0.2 + ent400 + assets + code) without copying data.
Usage: python3 -I stage.py (re-run from scratch: remove both stage roots first)
Every large file is HARD-LINKED from where it already lives; only small new text files (items/truth with relative
paths, READMEs, tables) are written. A hard link must stay on the source file system, so the repo tree is split
over two local roots that together form the repo layout:
DISK = runs/hf-release-20261120/stage everything whose source is on the disk, plus all new text files
SHM = ${LOCAL}/shm/ent400/hf-release-20261120/stage ent400 media / render metadata (sources are in ${LOCAL}/shm)
No relative path exists in both roots (checked). Upload = both roots into the same repo paths.
Item files keep the exact rows of the evaluated packs; only file paths change (relative to the items file).
"""
import collections as C, csv, hashlib, json, os, re, shutil, sys
from pathlib import Path
RUNS = Path('${LOCAL}/simulation-workspace/runs')
WS = Path('${LOCAL}/simulation-workspace')
AJ = Path('${LOCAL}/agent-jobs')
V2PKG = AJ / 'W59-release/np-bench-v0.2/post/316f62b9-choice-k3/3-package'
E4PKG = AJ / 'W59-release/np-bench-v0.2/ent400'
DISK = RUNS / 'hf-release-20261120/stage'
SHM = Path('${LOCAL}/shm/ent400/hf-release-20261120/stage')
G = ['g1', 'g2', 'g3', 'g4', 'g5']
SHM_DEV = os.stat('${LOCAL}/shm').st_dev
def jl(p):
return [json.loads(l) for l in open(p, encoding='utf-8') if l.strip()]
def wjl(p, rows):
p.parent.mkdir(parents=True, exist_ok=True)
with open(p, 'w', encoding='utf-8') as f:
for r in rows:
f.write(json.dumps(r, ensure_ascii=False) + '\n')
def write(rel, text):
p = DISK / rel; p.parent.mkdir(parents=True, exist_ok=True); p.write_text(text, encoding='utf-8')
def root_for(src):
return SHM if os.stat(src).st_dev == SHM_DEV else DISK
LINKED = {} # repo rel -> (dev, ino)
def link(src, rel):
"""Hard-link src (resolved) to repo path rel in the root on src's file system. Returns rel."""
src = os.path.realpath(src); st = os.stat(src)
key = (st.st_dev, st.st_ino)
if rel in LINKED:
if LINKED[rel] != key:
raise RuntimeError(f'{rel}: two different source files')
return rel
dst = root_for(src) / rel
dst.parent.mkdir(parents=True, exist_ok=True)
os.link(src, dst)
LINKED[rel] = key
return rel
def link_tree(src_dir, rel_dir, skip=lambda p: False):
n = 0
src_dir = Path(os.path.realpath(src_dir))
for dp, dns, fns in os.walk(src_dir, followlinks=True):
dns[:] = [d for d in dns if d not in ('__pycache__', '.git', 'node_modules')]
for fn in fns:
p = Path(dp) / fn
if fn.endswith('.pyc') or skip(p):
continue
link(p, f'{rel_dir}/{p.relative_to(src_dir)}'); n += 1
return n
class Media:
"""Canonical media names inside one part: videos/<seg>/<file>, clips/<seg>/<file>, gemini/<seg>/<file>.
Two different files that want the same name (only happens for a few v0.2 Gemini re-encodes made twice from
the same recording) get a content-hash suffix."""
def __init__(self, part):
self.part = part; self.by_name = {}; self.by_ino = {}
def add(self, src, kind, name_from=None):
src = os.path.realpath(src); st = os.stat(src); ino = (st.st_dev, st.st_ino)
if ino in self.by_ino:
return self.by_ino[ino]
m = re.search(r'/(p\d_H\d\d-[^/]+)/(?:(?:observation|\.partial)/videos/|)([^/]+\.mp4)$', os.path.realpath(name_from or src))
if not m:
raise ValueError(src)
name = f'{self.part}/media/{kind}/{m[1]}/{m[2]}'
if name in self.by_name and self.by_name[name] != ino:
h = hashlib.sha256(open(src, 'rb').read()).hexdigest()[:8]
name = name[:-4] + f'__{h}.mp4'
self.by_name[name] = ino; self.by_ino[ino] = name
link(src, name)
return name
class Maps:
def __init__(self, part):
self.part = part; self.by_name = {}
def add(self, src):
src = os.path.realpath(src)
tail = src.split('/maps/', 1)[1]
name = f'{self.part}/maps/{tail}'
if name in self.by_name:
if self.by_name[name] == src or open(self.by_name[name], 'rb').read() == open(src, 'rb').read():
return name
h = hashlib.sha256(open(src, 'rb').read()).hexdigest()[:8]
name = name[:-4] + f'__{h}.png'
self.by_name[name] = src
link(src, name)
return name
def resolve(p, base):
return Path(p) if str(p).startswith('/') else Path(base) / p
def rewrite(row, pack_items_dir, out_dir_rel, media, maps, gemini=None):
"""Copy of an item row with video / clip source / image paths placed in the part and made relative to out_dir.
gemini: (primary row, its items dir) -- the Gemini re-encode of each view is named after the primary view's file."""
r = json.loads(json.dumps(row))
prim = [resolve(v['path'], gemini[1]) for v in gemini[0]['videos']] if gemini else None
if prim is not None:
assert len(prim) == len(r['videos'])
for j, v in enumerate(r['videos']):
src = resolve(v['path'], pack_items_dir)
is_clip = bool(v.get('clip'))
kind = 'gemini' if gemini else ('clips' if is_clip else 'videos')
v['path'] = os.path.relpath(media.add(src, kind, prim[j] if prim else None), out_dir_rel)
if is_clip:
v['clip']['source'] = os.path.relpath(media.add(v['clip']['source'], 'videos'), out_dir_rel)
for im in r.get('images') or []:
im['path'] = os.path.relpath(maps.add(resolve(im['path'], pack_items_dir)), out_dir_rel)
return r
def truth_of(pack):
return {t['item_id']: t for t in jl(Path(pack) / 'items/truth.jsonl')}
def emit(out_rel, entries, media, maps):
"""entries: [(item_id, pack_dir)] in output order. Writes items.jsonl, gemini-items.jsonl, truth.jsonl."""
cache = {}
def pack(p):
if p not in cache:
cache[p] = ({r['item_id']: r for r in jl(Path(p) / 'items/items.jsonl')},
{r['item_id']: r for r in jl(Path(p) / 'gemini-items/items.jsonl')}, truth_of(p))
return cache[p]
items, gem, tru = [], [], []
for iid, p in entries:
I, GM, T = pack(p)
items.append(rewrite(I[iid], Path(p) / 'items', out_rel, media, maps))
gem.append(rewrite(GM[iid], Path(p) / 'gemini-items', out_rel, media, maps, gemini=(I[iid], Path(p) / 'items')))
tru.append(T[iid])
assert len({x['item_id'] for x in items}) == len(items)
wjl(DISK / out_rel / 'items.jsonl', items)
wjl(DISK / out_rel / 'gemini-items.jsonl', gem)
wjl(DISK / out_rel / 'truth.jsonl', tru)
return len(items)
def alt_entries(pack, override=None):
rows = list(csv.DictReader(open(Path(pack) / 'alt_ids.tsv'), delimiter='\t'))
ov = set()
if override:
ov = {r['item_id'] for r in jl(Path(override) / 'items/items.jsonl')}
return [(r['alt_item_id'], override if r['alt_item_id'] in ov else pack) for r in rows], rows
def scripts_and_render(part, segs, ren):
"""segs: {(group, seg)}. Generated scripts (gen + facts) and Isaac render records (no videos here)."""
n = 0
for g, s in sorted(segs):
n += link_tree(RUNS / ren / g / 'scripts' / s, f'{part}/scripts/{s}')
rd = Path(os.path.realpath(RUNS / ren / g / 'renders' / s))
for sub in ('observation', '.partial', ''):
d = rd / sub if sub else rd
for fn in ('artifact.json', 'checks.json', 'identities.json', 'provenance.json', 'readback-summary.json', 'samples.json',
'failure.json', 'state-replay-failure.json', 'attempt-failure.json', 'viewport-edge-summary.json', 'stages.jsonl'):
if (d / fn).is_file():
link(d / fn, f'{part}/render/{s}/{sub.lstrip(".") + "/" if sub else ""}{fn}'.replace('//', '/'))
fx = RUNS / ren / g / 'fixtures' / s / 'spec.json'
if fx.is_file():
link(fx, f'{part}/render/{s}/render-spec.json')
for g in G:
link(RUNS / ren / g / 'status.json', f'{part}/render/status-{g}.json')
link(RUNS / ren / g / 'jobs.json', f'{part}/render/jobs-{g}.json')
return n
def main():
for r in (DISK, SHM):
if r.exists():
sys.exit(f'{r} exists; remove it first')
summary = C.OrderedDict()
# ------------------------------------------------------------------ v0.2
P = 'v0.2'; med, mp = Media(P), Maps(P)
ent = []
for g in G:
ids = (RUNS / f'v02-h30-select/half3600-k3/{g}/item_ids.txt').read_text().split()
where = {}
for pk in ('fixA', 'fixB', 'k3supp', 'redraw'): # later wins: merge rule redraw > k3supp > fixA / fixB
for r in jl(RUNS / f'eval-v02-{pk}-{g}/items/items.jsonl'):
where[r['item_id']] = str(RUNS / f'eval-v02-{pk}-{g}')
ent += [(i, where[i]) for i in ids]
for fn in ('item_ids.txt', 'selected.jsonl', 'unchanged.txt', 'image_added.txt', 'swapped_in.txt'):
link(RUNS / f'v02-h30-select/half3600-k3/{g}/{fn}', f'{P}/core3600/selection/{g}/{fn}')
src_count = C.Counter(Path(p).name.split('-')[2] for _, p in ent)
summary['v0.2/core3600'] = dict(items=emit(f'{P}/core3600', ent, med, mp), from_pack=dict(src_count))
e1, rows1 = alt_entries(RUNS / 'eval-v02-altform720-k3', RUNS / 'eval-v02-altform-supp1')
summary['v0.2/altform/b1-720'] = dict(items=emit(f'{P}/altform/b1-720', e1, med, mp), from_supp1=sum('supp1' in str(p) for _, p in e1))
link(RUNS / 'eval-v02-altform720-k3/alt_ids.tsv', f'{P}/altform/b1-720/alt_ids.tsv')
link(RUNS / 'eval-v02-altform-supp1/alt_ids.tsv', f'{P}/altform/b1-720/supp1-replaced.tsv')
for b, pack, sel in (('b2-1440', 'eval-v02-altform1440', 'v02-h30-select/altform1440'), ('b3-rest978', 'eval-v02-altform978', 'v02-h30-select/altform978')):
e, _ = alt_entries(RUNS / pack)
summary[f'v0.2/altform/{b}'] = dict(items=emit(f'{P}/altform/{b}', e, med, mp))
link(RUNS / pack / 'alt_ids.tsv', f'{P}/altform/{b}/alt_ids.tsv')
for fn in ('selected.json', 'summary.md'):
link(RUNS / sel / fn, f'{P}/altform/{b}/selection/{fn}')
for fn in ('selected.json', 'summary.md'):
link(RUNS / 'v02-h30-select/altform720-k3' / fn, f'{P}/altform/b1-720/selection/{fn}')
segs = set()
for g in G:
segs |= {(g, r['_segment']) for r in jl(RUNS / f'v02-h30-select/half3600-k3/{g}/selected.jsonl')}
for sel in ('altform720-k3', 'altform1440', 'altform978'):
segs |= {(x['g'], x['seg']) for x in json.load(open(RUNS / 'v02-h30-select' / sel / 'selected.json'))}
summary['v0.2/scripts'] = dict(segments=len(segs), files=scripts_and_render(P, segs, 'v02-isaac-render'))
summary['v0.2/media'] = dict(videos=sum(1 for n in med.by_name if '/videos/' in n), clips=sum(1 for n in med.by_name if '/clips/' in n),
gemini=sum(1 for n in med.by_name if '/gemini/' in n), maps=len(mp.by_name))
for f in ('PROVENANCE.json', 'CHANGELOG.md', 'changes/summary.json', 'changes/removed.jsonl'):
if (V2PKG / f).is_file():
link(V2PKG / f, f'{P}/upstream/{f}')
# ------------------------------------------------------------------ ent400
P = 'ent400'; med, mp = Media(P), Maps(P)
for h, tag in (('half1', 'half1'), ('half2', 'half2-reserve')):
ent = []
for g in G:
pk = RUNS / f'eval-ent400-k3-{h}-{g}'
ids = (RUNS / f'ent400-select/halves-k3/{g}/{h}/item_ids.txt').read_text().split()
got = [r['item_id'] for r in jl(pk / 'items/items.jsonl')]
assert sorted(got) == sorted(ids), (h, g)
ent += [(i, str(pk)) for i in ids]
for fn in ('item_ids.txt', 'selected.jsonl', 'selection.json'):
link(RUNS / f'ent400-select/halves-k3/{g}/{h}/{fn}', f'{P}/{tag}/core3600/selection/{g}/{fn}')
summary[f'ent400/{tag}/core3600'] = dict(items=emit(f'{P}/{tag}/core3600', ent, med, mp))
for b, pack, sel in (('b1-720', 'eval-ent400-altform720-half1', 'ent400-select/altform720-half1'),
('b2-1440', 'eval-ent400-altform1440-half1', 'ent400-select/altform1440-half1'),
('b3-rest990', 'eval-ent400-altform990-half1', 'ent400-select/altform990-half1')):
e, _ = alt_entries(RUNS / pack)
summary[f'ent400/half1/altform/{b}'] = dict(items=emit(f'{P}/half1/altform/{b}', e, med, mp))
link(RUNS / pack / 'alt_ids.tsv', f'{P}/half1/altform/{b}/alt_ids.tsv')
for fn in ('selected.json', 'summary.md'):
link(RUNS / sel / fn, f'{P}/half1/altform/{b}/selection/{fn}')
segs = set()
for g in G:
for h in ('half1', 'half2'):
segs |= {(g, r['_segment']) for r in jl(RUNS / f'ent400-select/halves-k3/{g}/{h}/selected.jsonl')}
for sel in ('altform720-half1', 'altform1440-half1', 'altform990-half1'):
segs |= {(x['g'], x['seg']) for x in json.load(open(RUNS / 'ent400-select' / sel / 'selected.json'))}
summary['ent400/scripts'] = dict(segments=len(segs), files=scripts_and_render(P, segs, 'ent400-isaac-render'))
summary['ent400/media'] = dict(videos=sum(1 for n in med.by_name if '/videos/' in n), clips=sum(1 for n in med.by_name if '/clips/' in n),
gemini=sum(1 for n in med.by_name if '/gemini/' in n), maps=len(mp.by_name))
for f in ('PROVENANCE.json', 'README.md'):
if (E4PKG / f).is_file():
link(E4PKG / f, f'{P}/upstream/{f}')
# ------------------------------------------------------------------ assets (25 houses, actors)
plan = json.load(open(RUNS / 'v02-h30-select/groups-plan.json'))
hs = json.load(open(RUNS / 'v02-h30-select/paper-stats.json'))['houses']
houses = []
for g in G:
for h in plan[g]:
m = hs[h]; world = m['scene']; short = world.split('_')[0]
n1 = link_tree(RUNS / f'isaac-scenes-20261110/scenes-approved/scene-{short}-fixmat-v2', f'assets/isaac-scenes/{world}')
n2 = link_tree(AJ / 'P1/capability-new' / world, f'assets/capability/{world}')
n3 = link_tree(WS / f'assets/scenes/hssd-{world}-v1', f'assets/hssd-source/{world}')
houses.append(dict(house=h, list_group=g, world=world, indoor_area_m2=m['indoor_area_m2'], walkable_area_m2=m['walkable_area_m2'],
rooms_indoor=m['rooms_indoor'], rooms_walkable=m['rooms_walkable'], isaac_files=n1, capability_files=n2, hssd_files=n3))
write('assets/houses.json', json.dumps(houses, ensure_ascii=False, indent=1))
na = {}
for src, rel in ((RUNS / 'isaac-backend-20261023/actors-v2', 'assets/actors/isaac/humanoids-v2'),
(RUNS / 'isaac-backend-20261023/quadruped-v2', 'assets/actors/isaac/laikago-v2'),
(RUNS / 'ent400-isaac-render/quadruped-red-v1', 'assets/actors/isaac/laikago-red-v1'),
(WS / 'assets/actors/habitat-humanoid-textured-v2', 'assets/actors/source/habitat-humanoid-textured-v2'),
(WS / 'assets/actors/laikago-bullet-3.2.7-v2', 'assets/actors/source/laikago-bullet-3.2.7-v2'),
(WS / 'assets/actors/laikago-red-bullet-3.2.7-v1', 'assets/actors/source/laikago-red-bullet-3.2.7-v1')):
na[rel] = link_tree(src, rel)
for d in ('laikago-bullet-3.2.7-v2', 'laikago-red-bullet-3.2.7-v1'): # Laikago URDF terms travel with each copy
if f'assets/actors/source/{d}/license.txt' not in LINKED:
link(WS / 'assets/actors/laikago-bullet-3.2.7-v1/license.txt', f'assets/actors/source/{d}/license.txt')
for f in ('hssd-scenes.json', 'habitat-humanoids.json', 'actors-fetch-laikago.json'):
link(WS / 'assets/manifests' / f, f'assets/manifests/{f}')
summary['assets'] = dict(houses=len(houses), actors=na)
# ------------------------------------------------------------------ code
for name, src in (('v0.2-0c2690ae', V2PKG / 'evaluation-code'), ('ent400-a06a1576', E4PKG / 'evaluation-code')):
summary[f'code/evaluation-code/{name}'] = link_tree(src, f'code/evaluation-code/{name}')
for f in Path(RUNS / 'eval-v02-supp-bundle/bundle/settings').iterdir():
link(f, f'code/settings/{f.name}')
link(Path(__file__).resolve(), 'code/tools/stage.py') if os.stat(__file__).st_dev != SHM_DEV else None
# ------------------------------------------------------------------ check & summary
a = {str(p.relative_to(DISK)) for p in DISK.rglob('*') if p.is_file()}
b = {str(p.relative_to(SHM)) for p in SHM.rglob('*') if p.is_file()} if SHM.exists() else set()
assert not a & b, sorted(a & b)[:5]
summary['files'] = dict(disk_root=len(a), shm_root=len(b), total=len(a) + len(b))
write('stage-summary.json', json.dumps(summary, ensure_ascii=False, indent=1))
print(json.dumps(summary, ensure_ascii=False, indent=1))
if __name__ == '__main__':
main()