File size: 19,004 Bytes
3e0cd9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e4b5b9
3e0cd9b
 
 
 
 
 
 
 
 
 
 
 
 
 
9834824
 
 
 
 
 
 
 
 
 
 
3e0cd9b
6e4b5b9
3e0cd9b
 
6e4b5b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e0cd9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fab8d0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e0cd9b
 
 
 
 
 
 
 
 
 
 
0ac324e
 
 
 
 
 
 
6e4b5b9
9834824
 
 
 
 
 
6e4b5b9
 
 
0ac324e
 
fab8d0c
0ac324e
fab8d0c
 
 
43879c9
 
9834824
 
6e4b5b9
 
0ac324e
71ce022
 
 
6e4b5b9
71ce022
 
 
 
6e4b5b9
71ce022
 
 
 
3e0cd9b
 
 
 
 
 
 
 
 
dc19c95
3e0cd9b
 
 
 
6e4b5b9
3e0cd9b
 
 
 
 
 
 
 
 
 
 
 
9834824
3e0cd9b
 
 
 
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
"""Result packaging and publishing. Never uploads local run directories wholesale."""
import argparse,hashlib,json,re,shutil,html
from pathlib import Path
ROOT=Path(__file__).resolve().parent
DATASET='JIAlonglong/gr1-six-task-mini';SPACE='JIAlonglong/gr1-six-task-mini-leaderboard'
def read(p):return json.loads(Path(p).read_text())
def dump(p,obj):
 p=Path(p);p.parent.mkdir(parents=True,exist_ok=True);p.write_text(json.dumps(obj,indent=2,ensure_ascii=False)+'\n')
def validate(folder,benchmark):
 folder=Path(folder);benchmark=Path(benchmark)
 info=read(folder/'submission.json');scenes=read(benchmark/'scenes.json');rows=read(folder/'episodes.json')
 for key in ['model','training_data','deployment','checkpoint_identity']:
  if not info.get(key):raise ValueError('Missing submission metadata: '+key)
 if info['deployment'].get('execute_steps')!=16:raise ValueError('v1 requires execute_steps=16')
 if info['protocol_sha256']!=hashlib.sha256((benchmark/'protocol.json').read_bytes()).hexdigest():raise ValueError('Wrong protocol digest')
 if info['training_track'] not in ['fixed-480-demo','external-data','robot-human-transfer']:raise ValueError('Unknown training track')
 if len(rows)!=120 or {r['scene_id'] for r in rows}!=set(range(120)):raise ValueError('Must contain exactly120 unique scenes')
 tasks=[]
 for row in rows:
  scene=scenes[row['scene_id']]
  for key in ['task_id','task_name','episode_id','demo','seed','initial_state_sha256']:
   if row[key]!=scene[key]:raise ValueError('Scene mismatch: '+key)
  if row['status']!='complete' or type(row['success']) is not bool or type(row['steps']) is not int or not 0<row['steps']<=720:raise ValueError('Only fully completed episodes eligible')
 for task in range(6):
  selected=[r for r in rows if r['task_id']==task]
  if len(selected)!=20:raise ValueError('Task requires20 episodes')
  tasks.append(sum(r['success'] for r in selected)/20)
 for task in range(6):
  video=folder/'videos'/f'task-{task:02d}.mp4'
  if not video.is_file() or video.stat().st_size<100:raise ValueError('Missing fixed-scene video '+str(task))
 diagnostic_files=[folder/'diagnostic-predictions.npz',folder/'diagnostic-metadata.json']
 if any(f.exists() for f in diagnostic_files):
  if not all(f.is_file() for f in diagnostic_files):raise ValueError('Incomplete latent diagnostic artifacts')
  import sys
  sys.path.insert(0,str(benchmark/'tools'))
  from latent_metrics import diagnose
  diagnostic=diagnose(*diagnostic_files,benchmark)
  if diagnostic['metadata']['model']!=info['model'] or diagnostic['metadata']['checkpoint_identity']!=info['checkpoint_identity']:raise ValueError('Latent diagnostics belong to another model/checkpoint')
  # Never trust submitted scalar metrics: recompute from fixed public targets.
  info['latent_diagnostics']=diagnostic
 else:info['latent_diagnostics']={'status':'not_provided'}
 info.update(task_success_rates=tasks,macro_success_rate=sum(tasks)/6,completed=120,verification='self-reported')
 if info['training_track']=='robot-human-transfer':info['transfer_comparison']=validate_transfer(info,benchmark)
 return info

def validate_transfer(info,benchmark):
 t=info.get('human_transfer',{});required=['baseline_submission_id','human_subset_sha256','human_modalities','comparison','recipe_id','human_usage_stage','robot_windows_seen','human_windows_seen']
 if any(k not in t for k in required):raise ValueError('Missing human transfer declaration')
 if t['human_modalities'] not in ['video_only','video_and_hand_pose']:raise ValueError('Human modalities must distinguish video-only from pose supervision')
 if t['comparison'] not in ['equal_gpu_hours','equal_robot_exposure']:raise ValueError('Invalid comparison control')
 if t.get('external_robot_task_weights') is not False:raise ValueError('Fixed human-transfer track excludes external robot task weights')
 for key in ['robot_windows_seen','human_windows_seen']:
  if type(t[key])!=int or t[key]<=0:raise ValueError('Need actual positive sample exposure counts')
 if t['human_subset_sha256']!=read(Path(benchmark)/'human-transfer/protocol.json')['human_subset_sha256']:raise ValueError('Wrong human subset')
 baseline_id=t['baseline_submission_id']
 if not re.fullmatch(r'[a-zA-Z0-9][a-zA-Z0-9_-]{1,79}',baseline_id):raise ValueError('Invalid baseline ID')
 folder=Path(benchmark)/'results'/baseline_id
 if not (folder/'submission.json').is_file():raise ValueError('Download accepted robot baseline into benchmark/results first')
 if read(folder/'submission.json')['training_track']!='fixed-480-demo':raise ValueError('Baseline must be robot-only fixed-480-demo')
 base=validate(folder,benchmark)
 for key in ['backbone_id','training_seed','deployment','protocol_sha256']:
  if key not in info or key not in base or info[key]!=base[key]:raise ValueError('Unmatched baseline field: '+key)
 if base.get('comparison_recipe_id')!=t['recipe_id']:raise ValueError('Baseline comparison recipe differs or undeclared')
 for model in [info,base]:
  c=model.get('compute',{})
  if not c.get('gpu_type') or any(type(c.get(k)) not in [int,float] or not 0<c[k]<100000 for k in ['budget_gpu_hours','actual_gpu_hours']):raise ValueError('Need positive actual and budget GPU hours')
  if c['actual_gpu_hours']>c['budget_gpu_hours']:raise ValueError('Reported run exceeded its budget')
 if base['compute']['gpu_type']!=info['compute']['gpu_type']:raise ValueError('Different GPU types cannot be equal-compute comparison')
 if t['comparison']=='equal_gpu_hours' and base['compute']['budget_gpu_hours']!=info['compute']['budget_gpu_hours']:raise ValueError('Budget caps differ')
 if t['comparison']=='equal_robot_exposure' and base.get('robot_windows_seen')!=t['robot_windows_seen']:raise ValueError('Robot exposure differs')
 return {'baseline_submission_id':baseline_id,'baseline_success_rate':base['macro_success_rate'],'delta_success_rate':info['macro_success_rate']-base['macro_success_rate'],'human_modalities':t['human_modalities'],'comparison':t['comparison'],'actual_gpu_hours':info['compute']['actual_gpu_hours']}

def package(run,out,model,track,benchmark):
 run=Path(run);out=Path(out);benchmark=Path(benchmark)
 if out.exists():raise ValueError('Output already exists')
 protocol=read(run/'protocol.json');expected=read(benchmark/'scenes.json');actual=read(run/'scenes.json')
 if len(actual)!=len(expected):raise ValueError('Scene count mismatch')
 for a,b in zip(actual,expected):
  for key in ['task_id','task_name','episode_id','demo','seed','initial_state_sha256']:
   if a[key]!=b[key]:raise ValueError('Run scene mismatch')
 if protocol['deploy']['max_steps']!=720 or protocol['deploy']['execute_steps']!=16:raise ValueError('Deployment protocol mismatch')
 out.mkdir(parents=True)
 rows=[]
 for i in range(120):
  r=read(run/'evaluation'/f'scene-{i:03d}.json')
  if r.get('horizon')!=720 or r.get('execute_steps')!=16 or r.get('future_demonstration_input') is not False:raise ValueError('Episode protocol mismatch')
  keys=['task_id','task_name','episode_id','demo','seed','initial_state_sha256','status','success','steps','mean_policy_seconds']
  row={k:r[k] for k in keys if k in r};row['scene_id']=i;rows.append(row)
 dump(out/'episodes.json',rows)
 info={'model':model,'training_track':track,'protocol_sha256':hashlib.sha256((benchmark/'protocol.json').read_bytes()).hexdigest(),'deployment':protocol['deploy'],'training_seed':protocol['training_seed'],'training_data':protocol['data'],'checkpoint_identity':'see checkpoint-sha256.json','verification':'self-reported'}
 pointers=read(run/'stage-latest.json');checkpoint=Path(pointers['pretrain'])
 hashes={}
 for p in sorted(checkpoint.glob('*.safetensors')):
  h=hashlib.sha256()
  with p.open('rb') as f:
   for chunk in iter(lambda:f.read(8*1024*1024),b''):h.update(chunk)
  hashes[p.name]=h.hexdigest()
 if not hashes:raise ValueError('No checkpoint weights available for identity')
 dump(out/'checkpoint-sha256.json',hashes);dump(out/'submission.json',info)
 (out/'videos').mkdir()
 for task in range(6):shutil.copy2(run/'evaluation'/f'task-{task:02d}.mp4',out/'videos'/f'task-{task:02d}.mp4')
 info=validate(out,benchmark);dump(out/'submission.json',info);return info

def render_guide(source):
 # Small dependency-free renderer for our trusted Markdown guide; always escape text.
 def inline(text):
  text=html.escape(text)
  text=re.sub(r'`([^`]+)`',r'<code>\1</code>',text)
  return re.sub(r'\[([^\]]+)\]\((https://[^ )]+)\)',r'<a href="\2" target="_blank" rel="noopener">\1</a>',text)
 blocks=[];paragraph=[];code=None
 def flush():
  if paragraph:blocks.append('<p>'+inline(' '.join(paragraph))+'</p>');paragraph.clear()
 for line in source.splitlines():
  if line.startswith('```'):
   flush()
   if code is None:code=[]
   else:blocks.append('<pre><code>'+html.escape('\n'.join(code))+'</code></pre>');code=None
  elif code is not None:code.append(line)
  elif not line.strip():flush()
  elif line.startswith('#'):
   flush();level=min(len(line)-len(line.lstrip('#')),6);blocks.append(f'<h{level}>'+inline(line[level:].strip())+f'</h{level}>')
  else:paragraph.append(line)
 flush()
 if code is not None:raise ValueError('Unclosed guide code fence')
 return '\n'.join(blocks)

def build():
 results=[]
 for folder in sorted((ROOT/'dataset/results').glob('*')):
  info=validate(folder,ROOT/'dataset');info['submission_id']=folder.name;results.append(info)
 results.sort(key=lambda r:(r['training_track'],-r['macro_success_rate']))
 board={'benchmark':'GR1 Six Task Mini','version':'v1','results':results};dump(ROOT/'dataset/leaderboard.json',board)
 cards=[]
 for r in results:
  name=html.escape(r['model']);sid=r['submission_id'];cards.append(f'<section><h2>{name}</h2><p>{html.escape(r["training_track"])} · 自报成绩 · 平均成功率 {r["macro_success_rate"]:.1%}</p><p>各任务:'+ ' / '.join(f'{x:.0%}' for x in r['task_success_rates'])+'</p><div class="videos">'+''.join(f'<figure><video controls preload="none" src="videos/{sid}/task-{t:02d}.mp4"></video><figcaption>任务 {t+1} · 固定场景</figcaption></figure>' for t in range(6))+'</div></section>')
  dest=ROOT/'space/videos'/sid;dest.mkdir(parents=True,exist_ok=True)
  for t in range(6):shutil.copy2(ROOT/'dataset/results'/sid/'videos'/f'task-{t:02d}.mp4',dest/f'task-{t:02d}.mp4')
 titles=[('餐垫 → 碗','定位与抓取,将物体准确放入碗中。','▱','◡'),('盘子 → 盘子','在两个容器间完成稳定的物体转移。','◯','◯'),('砧板 → 篮子','抓取物体,移动并释放到篮子中。','▱','▤'),('托盘 → 分层架','调整放置高度,完成架上摆放。','▱','☷'),('罐子 → 抽屉','放入物体后关闭抽屉,完成连续操作。','▥','⊟'),('牛奶 → 微波炉','放入牛奶后关门,验证多阶段执行。','▯','▣')]
 taskcards=[]
 for i,(title,description,start,end) in enumerate(titles):
  taskcards.append(f'<article class="task"><div class="tasktop"><span class="num">TASK / {i+1:02d}</span><span class="pill">20 SCENES</span></div><div class="icon" aria-hidden="true"><span>{start}</span><span class="arrow">→</span><span>{end}</span></div><h3>{title}</h3><p>{description}</p><small>{"PICK & PLACE" if i<4 else "MULTI-STAGE MANIPULATION"}</small></article>')
 rows=[]
 for r in results:
  track=html.escape(r['training_track'],quote=True)
  track_label={'fixed-480-demo':'固定480条','external-data':'外部数据','robot-human-transfer':'人类迁移'}[r['training_track']]
  d=r.get('latent_diagnostics',{});rmse=coverage=gap='未提供';details=''
  if d.get('status')=='measured':
   rmse=f"{d['reconstruction']['rmse']:.4f}"
   coverage=' / '.join(f"{layer['coverage']:.0%}" for layer in d['codebook'].get('layers',[])) if d['codebook']['status']=='measured' else '不适用'
   g=d['prediction_gap'];gap=f"{g['rmse_delta']:+.4f}" if g['status']=='measured' else ('不适用' if g['status']=='not_applicable' else '未提供')
   details='<br><small>'+html.escape(d['metadata']['execution_path'])+'</small>'
  if r['training_track']=='robot-human-transfer':
   transfer=r['transfer_comparison'];details+='<br><small>'+html.escape(transfer['human_modalities'])+' · ΔSR '+f"{transfer['delta_success_rate']*100:+.1f}pp"+' · '+str(transfer['actual_gpu_hours'])+' GPUh<br>R: '+html.escape(transfer['baseline_submission_id'])+' · '+html.escape(transfer['comparison'])+'</small>'
  rows.append(f'<tr data-track="{track}"><td>{html.escape(r["model"])}{details}</td><td>{track_label}</td><td class="score">{r["macro_success_rate"]:.1%}</td><td>120 / 120</td><td>{rmse}</td><td>{coverage}</td><td>{gap}</td><td>作者自报</td></tr>')
 template=(ROOT/'space-template.html').read_text()
 replacements={'COUNT':str(len(results)),'ROWS':''.join(rows),'EMPTY_HIDDEN':'hidden' if results else '', 'TASKS':''.join(taskcards),'VIDEOS':''.join(cards) if cards else '<div class="videoempty"><div class="play" aria-hidden="true">▷</div><div><h3>真实执行视频,即将随评测结果展示</h3><p>每个模型展示六个固定场景的视频。当前尚无已完成评测,不使用示范视频冒充模型执行。</p></div></div>'}
 replacements['GUIDE']=render_guide((ROOT/'dataset/SUBMISSION_GUIDE.md').read_text())
 for key,value in replacements.items():template=template.replace('{{'+key+'}}',value)
 template=re.sub(r'<a ([^>]*href="https://[^>]+)>',lambda match:'<a '+match.group(1)+(' target="_blank" rel="noopener"' if 'target=' not in match.group(1) else '')+'>',template)
 style=template.split('<style>',1)[1].split('</style>',1)[0]
 (ROOT/'space/guide.html').write_text('<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>GR1 Mini 提交指南</title><style>'+style+'</style><main class="wrap" style="padding-top:32px;padding-bottom:48px"><p><a href="index.html">← 返回榜单</a></p><article class="guide panel">'+replacements['GUIDE']+'</article></main></html>')
 design=render_guide((ROOT/'dataset/BENCHMARK_DESIGN.md').read_text())
 (ROOT/'space/benchmark-design.html').write_text('<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>评测设计与计算预算</title><style>'+style+'</style><main class="wrap" style="padding-top:32px;padding-bottom:48px"><p><a href="index.html">← 返回榜单</a></p><article class="guide panel">'+design+'</article></main></html>')
 latent_guide=render_guide((ROOT/'dataset/LATENT_DIAGNOSTICS.md').read_text())
 (ROOT/'space/latent-diagnostics.html').write_text('<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Latent Action诊断</title><style>'+style+'</style><main class="wrap" style="padding:32px"><p><a href="index.html">← 返回榜单</a></p><article class="guide panel">'+latent_guide+'</article></main></html>')
 human_guide=render_guide((ROOT/'dataset/HUMAN_TRANSFER.md').read_text())
 (ROOT/'space/human-transfer.html').write_text('<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>人类视频迁移组</title><style>'+style+'</style><main class="wrap" style="padding:32px"><p><a href="index.html">← 返回榜单</a></p><article class="guide panel">'+human_guide+'</article></main></html>')
 (ROOT/'space/index.html').write_text(template)
 # Stable evaluation-only ZIP: exclude result videos, checkpoints and the archive itself.
 import zipfile
 archive=ROOT/'dataset/gr1-six-task-mini-v1.zip'
 allowed={'README.md','SUBMISSION_GUIDE.md','protocol.json','scenes.json','training-splits.json','BENCHMARK_DESIGN.md','LATENT_DIAGNOSTICS.md','HUMAN_TRANSFER.md'}
 with zipfile.ZipFile(archive,'w',compression=zipfile.ZIP_DEFLATED) as bundle:
  for f in sorted((ROOT/'dataset').rglob('*')):
   if not f.is_file():continue
   relative=f.relative_to(ROOT/'dataset')
   if relative.name in allowed or (relative.parts[0]=='initial-scenes' and f.suffix in {'.npy','.xml','.json'}) or (relative.parts[0]=='tools' and f.suffix=='.py') or (relative.parts[0]=='human-transfer' and f.suffix=='.json') or (relative.parts[0]=='diagnostics' and f.suffix in {'.npz','.json'}):
    entry=zipfile.ZipInfo('gr1-six-task-mini/'+relative.as_posix(),date_time=(2026,10,29,0,0,0));entry.compress_type=zipfile.ZIP_DEFLATED
    bundle.writestr(entry,f.read_bytes())
 digest=hashlib.sha256(archive.read_bytes()).hexdigest()
 archive.with_suffix('.zip.sha256').write_text(digest+'  '+archive.name+'\n')

def publish():
 from huggingface_hub import HfApi
 api=HfApi();user=api.whoami()['name']
 if user!='JIAlonglong':raise ValueError('Publishing requires owner JIAlonglong')
 for repo,kind,folder in [(DATASET,'dataset','dataset'),(SPACE,'space','space')]:
  kw={'space_sdk':'static'} if kind=='space' else {}
  api.create_repo(repo_id=repo,repo_type=kind,private=False,exist_ok=True,**kw)
  api.update_repo_settings(repo_id=repo,repo_type=kind,private=False)
  api.upload_folder(repo_id=repo,repo_type=kind,folder_path=str(ROOT/folder),ignore_patterns=['**/__pycache__/**','**/*.pyc'],delete_patterns=['tools/__pycache__/*'],commit_message='Publish GR1 six-task pilot protocol and verified-format results')
  print(kind,repo,flush=True)

def main():
 p=argparse.ArgumentParser();sub=p.add_subparsers(dest='command',required=True)
 q=sub.add_parser('package-native');q.add_argument('--run',required=True);q.add_argument('--out',required=True);q.add_argument('--model',required=True);q.add_argument('--track',choices=['fixed-480-demo','external-data','robot-human-transfer'],required=True);q.add_argument('--benchmark',default=str(ROOT/'dataset'))
 for name in ['validate','submit']:
  q=sub.add_parser(name);q.add_argument('--folder',required=True);q.add_argument('--benchmark',default=str(ROOT/'dataset'))
  if name=='submit':q.add_argument('--id',required=True)
 sub.add_parser('build');sub.add_parser('publish');a=p.parse_args()
 if a.command=='package-native':print(package(a.run,a.out,a.model,a.track,a.benchmark))
 elif a.command in ['validate','submit']:
  info=validate(a.folder,a.benchmark);print(json.dumps(info,ensure_ascii=False))
  if a.command=='submit':
   if not re.fullmatch(r'[a-zA-Z0-9][a-zA-Z0-9_-]{1,79}',a.id):raise ValueError('Invalid submission ID')
   from huggingface_hub import HfApi
   api=HfApi();files=api.list_repo_files(DATASET,repo_type='dataset')
   if any(f.startswith('results/'+a.id+'/') for f in files):raise ValueError('Submission ID already exists; choose a new one')
   result=api.upload_folder(repo_id=DATASET,repo_type='dataset',folder_path=a.folder,path_in_repo='results/'+a.id,create_pr=True,allow_patterns=['submission.json','episodes.json','checkpoint-sha256.json','videos/task-*.mp4','diagnostic-predictions.npz','diagnostic-metadata.json','latent_metrics.json'],commit_message='Submit '+a.id)
   print(result.pr_url)
 elif a.command=='build':build()
 elif a.command=='publish':build();publish()
if __name__=='__main__':main()