"""Publish every completed CF evaluation, archive weights, and retire MP4s. Scores, per-video results, source/config provenance, seed inventories and all videos are uploaded. Deletion requires checksum verification at an immutable Hub revision. Retries reuse existing commits and per-group retirement receipts. """ import csv import io import json import math from pathlib import Path import time from huggingface_hub import CommitOperationAdd from huggingface_hub.hf_api import RepoFile from scripts.causal_baselines_b200.common import ( REPO, ROOT, CAMPAIGN, RESULT_REPO, MODEL_REPO, read, write, sha) from scripts.causal_baselines_b200 import archive from scripts.causal_baselines_b200.eval_common import records from scripts.vbench_b200.upload_hf_step80 import PHYSICS, GROUPING_SOURCE, retry PAYLOAD=CAMPAIGN/'upload/payload' STATUS=CAMPAIGN/'upload/status.json' def commit(api,files,message): return retry(message,lambda:api.create_commit(RESULT_REPO,repo_type='dataset', operations=[CommitOperationAdd(str(p.relative_to(PAYLOAD)),p) for p in files], num_threads=4,commit_message=message)) def portable(value,output,prefix): if isinstance(value,dict): return {k:portable(v,output,prefix) for k,v in value.items()} if isinstance(value,list): return [portable(v,output,prefix) for v in value] if isinstance(value,str) and value.startswith(str(output)+'/'): return prefix+value[len(str(output)):] return value def index(api): summaries=[] for p in sorted((CAMPAIGN/'evaluations').glob('step-*/*/results/summary.json')): result=read(p) assert not result['smoke'] and result['generator_family']=='causal_forcing' scores={k.replace(' ','_'):float(v) for k,v in result['dimensions'].items()} assert len(scores)==16 and all(math.isfinite(x) for x in scores.values()) summaries.append(dict(method=result['method'],step=result['checkpoint_step'], total_score_percent=result['total_score_percent'], physics_mean_percent=sum(scores[d] for d in PHYSICS)*100/5, general_mean_percent=sum(v for d,v in scores.items() if d not in PHYSICS)*100/11, dimension_scores=scores,checkpoint_sha256=result['checkpoint_sha256'])) write(PAYLOAD/'comparison.json',dict(groups=summaries,target_steps=160,checkpoint_interval=40, generator_family='causal_forcing',grouping_source=GROUPING_SOURCE,physics_dimensions=PHYSICS, group_aggregation='unweighted mean of raw scores times 100; separate from official weighted VBench total')) text=io.StringIO() writer=csv.writer(text) writer.writerow(['method','step','vbench_weighted_total_percent','physics_mean_percent','general_mean_percent']) for r in summaries: writer.writerow([r['method'],r['step'],r['total_score_percent'],r['physics_mean_percent'],r['general_mean_percent']]) (PAYLOAD/'comparison.csv').write_text(text.getvalue()) (PAYLOAD/'physics_general.csv').write_text(text.getvalue()) write(PAYLOAD/'physics_general.json',read(PAYLOAD/'comparison.json')) table='\n'.join(f"| {r['method']} | {r['step']} | {r['total_score_percent']:.4f} | {r['physics_mean_percent']:.4f} | {r['general_mean_percent']:.4f} |" for r in summaries) (PAYLOAD/'README.md').write_text(f'''--- pretty_name: Causal-Forcing Astrolabe and AdvDMD full VBench evaluations task_categories: - text-to-video tags: - causal-forcing - astrolabe - advdmd - vbench --- # Causal-Forcing initialization: Astrolabe and AdvDMD Both baselines initialize from the official **chunkwise/causal_forcing.pt** in [zhuhz22/Causal-Forcing](https://huggingface.co/zhuhz22/Causal-Forcing), rather than Self-Forcing DMD. Training uses the same 200 Kling prompts, global batch 24 (2 B200 GPUs, 4 examples per GPU, 3 accumulation microbatches), learning rate 2.5e-6, and 81-frame 480x832 output setting as the previous short-video controls. Training ends at 160 actual generator optimizer updates; checkpoints and evaluations are scheduled at updates **40, 80, 120, 160**. Each full evaluation generates **4,720 videos**: 944 unique raw prompts from the 946 official VBench metadata entries, with seeds 42, 43, 44, 45, 46. Both methods use the shared pinned four-step causal sampler, timestep shift 5, CFG 1, and 16 FPS. Scoring uses all 16 original VBench v1 dimensions and its official weighted total. AdvDMD retains the short-control GRPO warmup of 100 steps; 40/80 are before GRPO and 160 includes 12 GRPO updates. Its accessible score teacher remains Wan2.1-1.3B, as in the Self-Forcing adaptation. | Method | Update | VBench total (%) | Physics mean (%) | General mean (%) | | --- | ---: | ---: | ---: | ---: | {table} Physics is the mean of temporal flickering, motion smoothness, dynamic degree, human action and spatial relationship; General is the mean of the other 11 raw dimensions. This diagnostic grouping follows [AFD]({GROUPING_SOURCE}) and is separate from the official weighted total. `step-NNN/METHOD/` contains scores, per-video results, generated MP4s and provenance. Trained checkpoint bundles are in [{MODEL_REPO}](https://huggingface.co/{MODEL_REPO}) under `short-causal-forcing/`. Local videos and evaluated weight bundles are retired only after immutable-revision remote size and checksum verification. `upload_status.json` distinguishes published scores from completed video uploads. ''') commit(api,[PAYLOAD/n for n in ('README.md','comparison.json','comparison.csv','physics_general.json','physics_general.csv')], 'Update Causal-Forcing evaluation comparison') def publish_group(api,plan,state): method,step=plan['method'],plan['checkpoint_step'] key=f'step-{step:03d}/{method}' item=state['groups'].setdefault(key,{}) if item.get('stage')=='retired': return output=Path(plan['output_dir']) prefix=PAYLOAD/key prefix.mkdir(parents=True,exist_ok=True) if not item.get('inventory'): summary=read(output/'results/summary.json') assert summary['checkpoint_step']==step and summary['generator_family']=='causal_forcing' assert not summary['smoke'] and summary['videos']==4720 and len(summary['dimensions'])==16 selected=read(output/'selected_checkpoint.json') assert selected['sha256']==summary['checkpoint_sha256'] journal={r['video']:r for r in map(json.loads,(output/'generation-rank0.jsonl').read_text().splitlines())} inventory=[] for record in records(plan): p=Path(record['video']) row=journal[str(p)] assert row['checkpoint_sha256']==summary['checkpoint_sha256'] checksum=sha(p) assert row['video_sha256']==checksum and row['bytes']==p.stat().st_size inventory.append(dict(source=str(p),remote=f'{key}/videos/{p.name}', sha256=checksum,bytes=p.stat().st_size,prompt=record['prompt'],seed=record['seed'],replica=record['replica'])) for p in (output/'results').glob('*.json'): write(prefix/'results'/p.name,portable(read(p),output,key)) for name in ('plan.json','selected_checkpoint.json','generation-rank0.json'): write(prefix/'provenance'/name,read(output/name)) run_dir=Path(plan['training_run_dir']) for name in ('manifest.json','config.json','resolved_config.json','budget.json','causal_forcing_provenance.json'): p=run_dir/name if p.exists(): write(prefix/'provenance'/name,read(p)) (prefix/'metadata.jsonl').write_text(''.join(json.dumps({**r,'video':r['remote']},ensure_ascii=False)+'\n' for r in inventory)) item.update(stage='metadata_pending',inventory=inventory,plan=plan) write(STATUS,state) if not item.get('metadata_commit'): files=[p for p in prefix.rglob('*') if p.is_file()] result=commit(api,files,f'Publish {key} VBench scores and provenance') item.update(metadata_commit=result.oid,stage='scores_published') write(STATUS,state) index(api) if not item.get('remote_checksums_verified'): remote={x.path:x for x in api.list_repo_tree(RESULT_REPO,path_in_repo=key, repo_type='dataset',recursive=True) if isinstance(x,RepoFile)} missing=[r for r in item['inventory'] if not archive.remote_matches(remote.get(r['remote']),Path(r['source']),r['sha256'])] for start in range(0,len(missing),64): batch=missing[start:start+64] retry(f'Upload {key} video batch {start//64}',lambda:api.create_commit(RESULT_REPO,repo_type='dataset', operations=[CommitOperationAdd(r['remote'],r['source']) for r in batch],num_threads=4, commit_message=f'Upload {key} videos {start+1}-{start+len(batch)}')) item['uploaded_video_count']=len(item['inventory'])-len(missing)+start+len(batch) write(STATUS,state) revision=api.repo_info(RESULT_REPO,repo_type='dataset').sha remote={x.path:x for x in api.list_repo_tree(RESULT_REPO,path_in_repo=key, repo_type='dataset',revision=revision,recursive=True) if isinstance(x,RepoFile)} for r in item['inventory']: assert archive.remote_matches(remote.get(r['remote']),Path(r['source']),r['sha256']) item.update(remote_checksums_verified=True,verified_revision=revision,stage='verified') write(STATUS,state) # All videos are recoverable at the pinned verified revision before removal. for index_number,r in enumerate(item['inventory']): p=Path(r['source']) if p.exists(): assert p.stat().st_size==r['bytes'] and sha(p)==r['sha256'] p.unlink() r['retired']=True if index_number%64==0: write(STATUS,state) item['videos_retired']=True write(STATUS,state) archive.STATE=CAMPAIGN/'upload/checkpoint_archive.json' weights_state=read(archive.STATE) if archive.STATE.exists() else dict(bundles={},videos={}) selected=read(output/'selected_checkpoint.json') cp=Path(selected['checkpoint']) if method=='astrolabe': directory=cp.parent.parent files=[(str(p.relative_to(directory)),p) for p in directory.rglob('*') if p.is_file()] else: files=[(cp.name,cp)] archive.archive_bundle(api,f'short-causal-forcing/{method}/step-{step:03d}',files, dict(plan=plan,summary=read(output/'results/summary.json')),weights_state) item.update(stage='retired',completed_unix=time.time()) write(STATUS,state) write(prefix/'upload_status.json',{k:v for k,v in item.items() if k not in ('inventory','plan')}) commit(api,[prefix/'upload_status.json'],f'Confirm verified upload and local retirement of {key}') def main(): api=archive.api_client() retry('Create CF results repository',lambda:api.create_repo(RESULT_REPO,repo_type='dataset',exist_ok=True)) retry('Create checkpoint repository',lambda:api.create_repo(MODEL_REPO,repo_type='model',exist_ok=True)) card=b'''--- tags: - text-to-video - self-forcing - causal-forcing - astrolabe - advdmd --- # AFD baseline checkpoint archive Evaluated short-video Astrolabe and AdvDMD checkpoints are stored under `short-self-forcing/METHOD/step-NNN/` and `short-causal-forcing/METHOD/step-NNN/`. Evaluated long-video compact inference exports are under `long-self-forcing/METHOD/step-NNN/`. These exports preserve the original saved format; they are distinct from full restart checkpoints retained by active long-video training. Short Astrolabe bundles include LoRA configuration, LoRA weights and the original optimizer/scaler files. Short AdvDMD files contain the original generator LoRA and discriminator heads. Every bundle includes `archive_provenance.json`: evaluation provenance, original local filenames, per-file byte sizes and SHA256 checksums. Local retirement is authorized only after remote checksum verification at an immutable Hub revision. Original initialization weights remain in their upstream repositories and are not included in this archive. Results and generation/configuration provenance: - https://huggingface.co/datasets/yang29/afd-baselines-vbench-step80-20261109 - https://huggingface.co/datasets/yang29/afd-baselines-vbench-step160-20261110 - https://huggingface.co/datasets/yang29/afd-long-video-vbench-100prompts - https://huggingface.co/datasets/yang29/afd-causal-forcing-baselines-vbench ''' retry('Update checkpoint archive card',lambda:api.create_commit(MODEL_REPO,repo_type='model', operations=[CommitOperationAdd('README.md',card)],commit_message='Document checkpoint formats and verified retirement')) PAYLOAD.mkdir(parents=True,exist_ok=True) state=read(STATUS) if STATUS.exists() else dict(groups={}) source=REPO/'scripts/causal_baselines_b200' for p in source.glob('*'): if p.is_file(): target=PAYLOAD/'code'/p.name target.parent.mkdir(exist_ok=True) target.write_bytes(p.read_bytes()) commit(api,[p for p in (PAYLOAD/'code').iterdir() if p.is_file()],'Record CF training and evaluation implementation') index(api) while True: try: controller=read(CAMPAIGN/'status.json') if (CAMPAIGN/'status.json').exists() else {'evaluations':{}} for task in controller['evaluations'].values(): plan=read(task['plan']) if (Path(plan['output_dir'])/'results/summary.json').exists(): publish_group(api,plan,state) state.pop('error',None) state['updated_unix']=time.time() write(STATUS,state) except Exception as exc: state['error']=f'{type(exc).__name__}: {exc}' write(STATUS,state) print(state['error'],flush=True) time.sleep(60) if __name__=='__main__': main()