Record CF training and evaluation implementation
Browse files- code/archive.py +52 -38
- code/forever.sh +18 -0
- code/generate.py +6 -1
- code/prepare.py +3 -4
- code/train.py +24 -4
code/archive.py
CHANGED
|
@@ -12,6 +12,7 @@ import time
|
|
| 12 |
from huggingface_hub import HfApi, CommitOperationAdd
|
| 13 |
from huggingface_hub.hf_api import RepoFile
|
| 14 |
from scripts.causal_baselines_b200.common import REPO, ROOT, LONG, MODEL_REPO, read, write, sha
|
|
|
|
| 15 |
|
| 16 |
STATE = REPO / 'reports/storage-archive-20261116/status.json'
|
| 17 |
|
|
@@ -34,37 +35,41 @@ def api_client():
|
|
| 34 |
def archive_bundle(api, key, files, context, state):
|
| 35 |
if state['bundles'].get(key, {}).get('stage') == 'retired':
|
| 36 |
return
|
| 37 |
-
|
| 38 |
-
if not
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
| 57 |
for row in inventory:
|
| 58 |
p = Path(row['source'])
|
| 59 |
# Recheck against the verified inventory immediately before removing.
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
row['deleted'] = True
|
| 64 |
write(STATE, state)
|
| 65 |
item['stage'] = 'retired'
|
|
|
|
| 66 |
write(STATE, state)
|
| 67 |
-
print({'archived': key, 'bytes_reclaimed': item['retired_bytes'], 'commit':
|
| 68 |
|
| 69 |
|
| 70 |
def old_short(api, state):
|
|
@@ -121,22 +126,30 @@ def old_videos(api, state):
|
|
| 121 |
directory = Path(plan['output_dir']) / 'videos'
|
| 122 |
remote = {x.path: x for x in api.list_repo_tree(repo_id, repo_type='dataset', revision=revision,
|
| 123 |
path_in_repo=f'data/{method}/videos', recursive=True) if isinstance(x, RepoFile)}
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
for row in files:
|
| 135 |
p = Path(row['source'])
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
item['stage'] = 'retired'
|
|
|
|
| 140 |
write(STATE, state)
|
| 141 |
print({'retired_videos':key, 'bytes_reclaimed':item['retired_bytes']}, flush=True)
|
| 142 |
|
|
@@ -151,9 +164,10 @@ def main():
|
|
| 151 |
if args.checkpoints:
|
| 152 |
api.create_repo(MODEL_REPO, repo_type='model', exist_ok=True)
|
| 153 |
old_short(api,state)
|
| 154 |
-
old_long(api,state)
|
| 155 |
if args.videos:
|
| 156 |
old_videos(api,state)
|
|
|
|
|
|
|
| 157 |
state['updated_unix'] = time.time()
|
| 158 |
write(STATE,state)
|
| 159 |
|
|
|
|
| 12 |
from huggingface_hub import HfApi, CommitOperationAdd
|
| 13 |
from huggingface_hub.hf_api import RepoFile
|
| 14 |
from scripts.causal_baselines_b200.common import REPO, ROOT, LONG, MODEL_REPO, read, write, sha
|
| 15 |
+
from scripts.vbench_b200.upload_hf_step80 import retry
|
| 16 |
|
| 17 |
STATE = REPO / 'reports/storage-archive-20261116/status.json'
|
| 18 |
|
|
|
|
| 35 |
def archive_bundle(api, key, files, context, state):
|
| 36 |
if state['bundles'].get(key, {}).get('stage') == 'retired':
|
| 37 |
return
|
| 38 |
+
item = state['bundles'].get(key)
|
| 39 |
+
if not item or item.get('stage') != 'verified':
|
| 40 |
+
available = [(name, Path(path)) for name, path in files if Path(path).is_file()]
|
| 41 |
+
if not available:
|
| 42 |
+
return
|
| 43 |
+
inventory = [{'source': str(p), 'remote': f'{key}/{name}', 'bytes': p.stat().st_size,
|
| 44 |
+
'sha256': sha(p)} for name, p in available]
|
| 45 |
+
operations = [CommitOperationAdd(r['remote'], r['source']) for r in inventory]
|
| 46 |
+
import json
|
| 47 |
+
operations.append(CommitOperationAdd(f'{key}/archive_provenance.json',
|
| 48 |
+
json.dumps(dict(context=context, files=inventory), indent=2).encode()))
|
| 49 |
+
commit = retry(f'Archive {key}', lambda: api.create_commit(MODEL_REPO, repo_type='model', operations=operations,
|
| 50 |
+
commit_message=f'Archive evaluated {key}', num_threads=4))
|
| 51 |
+
remote = {x.path: x for x in api.list_repo_tree(MODEL_REPO, path_in_repo=key,
|
| 52 |
+
repo_type='model', revision=commit.oid, recursive=True) if isinstance(x, RepoFile)}
|
| 53 |
+
for row in inventory:
|
| 54 |
+
p = Path(row['source'])
|
| 55 |
+
assert sha(p) == row['sha256'] and remote_matches(remote.get(row['remote']), p, row['sha256'])
|
| 56 |
+
item = dict(stage='verified', repo_id=MODEL_REPO, revision=commit.oid,
|
| 57 |
+
files=inventory, context=context, retired_bytes=0)
|
| 58 |
+
state['bundles'][key] = item
|
| 59 |
+
write(STATE, state)
|
| 60 |
+
inventory = item['files']
|
| 61 |
for row in inventory:
|
| 62 |
p = Path(row['source'])
|
| 63 |
# Recheck against the verified inventory immediately before removing.
|
| 64 |
+
if p.exists():
|
| 65 |
+
assert p.stat().st_size == row['bytes'] and sha(p) == row['sha256']
|
| 66 |
+
p.unlink()
|
| 67 |
row['deleted'] = True
|
| 68 |
write(STATE, state)
|
| 69 |
item['stage'] = 'retired'
|
| 70 |
+
item['retired_bytes'] = sum(r['bytes'] for r in inventory)
|
| 71 |
write(STATE, state)
|
| 72 |
+
print({'archived': key, 'bytes_reclaimed': item['retired_bytes'], 'commit': item['revision']}, flush=True)
|
| 73 |
|
| 74 |
|
| 75 |
def old_short(api, state):
|
|
|
|
| 126 |
directory = Path(plan['output_dir']) / 'videos'
|
| 127 |
remote = {x.path: x for x in api.list_repo_tree(repo_id, repo_type='dataset', revision=revision,
|
| 128 |
path_in_repo=f'data/{method}/videos', recursive=True) if isinstance(x, RepoFile)}
|
| 129 |
+
item=state['videos'].get(key)
|
| 130 |
+
if not item or item.get('stage')!='verified':
|
| 131 |
+
from scripts.vbench_b200.common import records
|
| 132 |
+
files = []
|
| 133 |
+
for record in records(plan):
|
| 134 |
+
p=Path(record['video'])
|
| 135 |
+
if not p.exists():
|
| 136 |
+
continue
|
| 137 |
+
name = f'data/{method}/videos/{p.name}'
|
| 138 |
+
digest = sha(p)
|
| 139 |
+
assert remote_matches(remote.get(name), p, digest), f'Remote mismatch: {p}'
|
| 140 |
+
files.append(dict(source=str(p), remote=name, sha256=digest, bytes=p.stat().st_size))
|
| 141 |
+
item = dict(stage='verified', repo_id=repo_id, revision=revision, files=files,
|
| 142 |
+
retired_bytes=0, expected_videos=plan['expected_videos'])
|
| 143 |
+
state['videos'][key] = item
|
| 144 |
+
write(STATE, state)
|
| 145 |
+
files=item['files']
|
| 146 |
for row in files:
|
| 147 |
p = Path(row['source'])
|
| 148 |
+
if p.exists():
|
| 149 |
+
assert sha(p) == row['sha256'] and p.stat().st_size == row['bytes']
|
| 150 |
+
p.unlink()
|
| 151 |
item['stage'] = 'retired'
|
| 152 |
+
item['retired_bytes']=sum(r['bytes'] for r in files)
|
| 153 |
write(STATE, state)
|
| 154 |
print({'retired_videos':key, 'bytes_reclaimed':item['retired_bytes']}, flush=True)
|
| 155 |
|
|
|
|
| 164 |
if args.checkpoints:
|
| 165 |
api.create_repo(MODEL_REPO, repo_type='model', exist_ok=True)
|
| 166 |
old_short(api,state)
|
|
|
|
| 167 |
if args.videos:
|
| 168 |
old_videos(api,state)
|
| 169 |
+
if args.checkpoints:
|
| 170 |
+
old_long(api,state)
|
| 171 |
state['updated_unix'] = time.time()
|
| 172 |
write(STATE,state)
|
| 173 |
|
code/forever.sh
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -uo pipefail
|
| 3 |
+
cd /nfs/home/svu/e0833524/AFD
|
| 4 |
+
mode="${1:?controller, publish or archive}"
|
| 5 |
+
exec 9>"reports/causal-$mode.lock"
|
| 6 |
+
flock -n 9 || exit 0
|
| 7 |
+
trap 'exit 0' INT TERM
|
| 8 |
+
while true; do
|
| 9 |
+
case "$mode" in
|
| 10 |
+
controller) python3 -u -m scripts.causal_baselines_b200.controller ;;
|
| 11 |
+
publish) bash scripts/causal_baselines_b200/hub.sh -u -m scripts.causal_baselines_b200.publish ;;
|
| 12 |
+
archive) bash scripts/causal_baselines_b200/hub.sh -u -m scripts.causal_baselines_b200.archive --checkpoints --videos ;;
|
| 13 |
+
*) exit 2 ;;
|
| 14 |
+
esac
|
| 15 |
+
result=$?
|
| 16 |
+
printf '%s process exited %s; restarting independently of the terminal\n' "$mode" "$result"
|
| 17 |
+
if [[ "$mode" == archive && "$result" == 0 ]]; then sleep 600; else sleep 30; fi
|
| 18 |
+
done
|
code/generate.py
CHANGED
|
@@ -16,6 +16,8 @@ def build_pipeline(plan, checkpoint, device):
|
|
| 16 |
from omegaconf import OmegaConf
|
| 17 |
from peft import LoraConfig, get_peft_model, get_peft_model_state_dict, set_peft_model_state_dict
|
| 18 |
from baselines.astrolabe.bootstrap import install_short_video_pipeline
|
|
|
|
|
|
|
| 19 |
source = Path(plan["upstream_dir"])
|
| 20 |
sys.path.insert(0, str(source))
|
| 21 |
os.chdir(plan["pipeline_cwd"])
|
|
@@ -104,6 +106,7 @@ def main():
|
|
| 104 |
assigned = records(plan)[rank::world]
|
| 105 |
journal = output / f"generation-rank{rank}.jsonl"
|
| 106 |
completed = set()
|
|
|
|
| 107 |
if journal.exists():
|
| 108 |
for line in journal.read_text().splitlines():
|
| 109 |
try:
|
|
@@ -113,8 +116,10 @@ def main():
|
|
| 113 |
if item.get("checkpoint_sha256") != fingerprint:
|
| 114 |
raise ValueError("Existing generation belongs to a different checkpoint")
|
| 115 |
completed.add((item["prompt"], item["replica"]))
|
|
|
|
| 116 |
pending = [item for item in assigned if (item["prompt"], item["replica"]) not in completed
|
| 117 |
-
or not Path(item["video"]).is_file() or Path(item["video"]).stat().st_size == 0
|
|
|
|
| 118 |
print(json.dumps({"method": plan["method"], "rank": rank, "assigned": len(assigned),
|
| 119 |
"pending": len(pending), "checkpoint": str(checkpoint)}), flush=True)
|
| 120 |
started = time.monotonic()
|
|
|
|
| 16 |
from omegaconf import OmegaConf
|
| 17 |
from peft import LoraConfig, get_peft_model, get_peft_model_state_dict, set_peft_model_state_dict
|
| 18 |
from baselines.astrolabe.bootstrap import install_short_video_pipeline
|
| 19 |
+
if sha256(plan['student_checkpoint']) != plan['student_checkpoint_sha256']:
|
| 20 |
+
raise ValueError('Official Causal-Forcing checkpoint changed after preparation')
|
| 21 |
source = Path(plan["upstream_dir"])
|
| 22 |
sys.path.insert(0, str(source))
|
| 23 |
os.chdir(plan["pipeline_cwd"])
|
|
|
|
| 106 |
assigned = records(plan)[rank::world]
|
| 107 |
journal = output / f"generation-rank{rank}.jsonl"
|
| 108 |
completed = set()
|
| 109 |
+
receipts = {}
|
| 110 |
if journal.exists():
|
| 111 |
for line in journal.read_text().splitlines():
|
| 112 |
try:
|
|
|
|
| 116 |
if item.get("checkpoint_sha256") != fingerprint:
|
| 117 |
raise ValueError("Existing generation belongs to a different checkpoint")
|
| 118 |
completed.add((item["prompt"], item["replica"]))
|
| 119 |
+
receipts[(item['prompt'],item['replica'])]=item
|
| 120 |
pending = [item for item in assigned if (item["prompt"], item["replica"]) not in completed
|
| 121 |
+
or not Path(item["video"]).is_file() or Path(item["video"]).stat().st_size == 0
|
| 122 |
+
or sha256(item['video']) != receipts[(item['prompt'],item['replica'])].get('video_sha256')]
|
| 123 |
print(json.dumps({"method": plan["method"], "rank": rank, "assigned": len(assigned),
|
| 124 |
"pending": len(pending), "checkpoint": str(checkpoint)}), flush=True)
|
| 125 |
started = time.monotonic()
|
code/prepare.py
CHANGED
|
@@ -16,7 +16,7 @@ def prepare(method, directory, smoke=False):
|
|
| 16 |
assert sha(cf['checkpoint']) == cf['sha256']
|
| 17 |
cfgdir = directory.parent / (directory.name + '-inputs')
|
| 18 |
cfgdir.mkdir(parents=True, exist_ok=True)
|
| 19 |
-
afd = read(REPO / 'configs/b200/afd.
|
| 20 |
afd['models']['student']['checkpoint_path'] = cf['checkpoint']
|
| 21 |
# The official CF chunkwise schedule is identical to the SF four-step control.
|
| 22 |
student = astro.load_mapping(Path(afd['models']['student']['config_path']))
|
|
@@ -28,8 +28,7 @@ def prepare(method, directory, smoke=False):
|
|
| 28 |
afd_path, baseline_path = cfgdir/'afd.json', cfgdir/'baseline.json'
|
| 29 |
write(afd_path, afd)
|
| 30 |
if method == 'astrolabe':
|
| 31 |
-
|
| 32 |
-
cfg = copy.deepcopy(previous['baseline'])
|
| 33 |
cfg.update(student_family='causal_forcing', epochs=1 if smoke else 10,
|
| 34 |
save_every=1000000, eval_every=1000000, checkpoint_every_optimizer_steps=1 if smoke else 40)
|
| 35 |
if smoke:
|
|
@@ -43,7 +42,7 @@ def prepare(method, directory, smoke=False):
|
|
| 43 |
assert budget['effective_global_batch']==24
|
| 44 |
assert budget['total_optimizer_steps']==(1 if smoke else 160)
|
| 45 |
else:
|
| 46 |
-
cfg=read(REPO/'
|
| 47 |
cfg.update(student_family='causal_forcing',max_steps=160,save_every=40)
|
| 48 |
write(baseline_path,cfg)
|
| 49 |
adv.prepare(argparse.Namespace(afd_config=afd_path,baseline_config=baseline_path,
|
|
|
|
| 16 |
assert sha(cf['checkpoint']) == cf['sha256']
|
| 17 |
cfgdir = directory.parent / (directory.name + '-inputs')
|
| 18 |
cfgdir.mkdir(parents=True, exist_ok=True)
|
| 19 |
+
afd = read(REPO / 'configs/b200/afd.causal_forcing.json')
|
| 20 |
afd['models']['student']['checkpoint_path'] = cf['checkpoint']
|
| 21 |
# The official CF chunkwise schedule is identical to the SF four-step control.
|
| 22 |
student = astro.load_mapping(Path(afd['models']['student']['config_path']))
|
|
|
|
| 28 |
afd_path, baseline_path = cfgdir/'afd.json', cfgdir/'baseline.json'
|
| 29 |
write(afd_path, afd)
|
| 30 |
if method == 'astrolabe':
|
| 31 |
+
cfg = read(REPO/'configs/b200/astrolabe.causal_forcing.json')
|
|
|
|
| 32 |
cfg.update(student_family='causal_forcing', epochs=1 if smoke else 10,
|
| 33 |
save_every=1000000, eval_every=1000000, checkpoint_every_optimizer_steps=1 if smoke else 40)
|
| 34 |
if smoke:
|
|
|
|
| 42 |
assert budget['effective_global_batch']==24
|
| 43 |
assert budget['total_optimizer_steps']==(1 if smoke else 160)
|
| 44 |
else:
|
| 45 |
+
cfg=read(REPO/'configs/b200/advdmd.causal_forcing.json')
|
| 46 |
cfg.update(student_family='causal_forcing',max_steps=160,save_every=40)
|
| 47 |
write(baseline_path,cfg)
|
| 48 |
adv.prepare(argparse.Namespace(afd_config=afd_path,baseline_config=baseline_path,
|
code/train.py
CHANGED
|
@@ -1,5 +1,7 @@
|
|
| 1 |
"""Launch the existing baseline implementations with CF-scoped workers."""
|
| 2 |
import argparse
|
|
|
|
|
|
|
| 3 |
import os
|
| 4 |
from pathlib import Path
|
| 5 |
import subprocess
|
|
@@ -8,6 +10,26 @@ import sys
|
|
| 8 |
from scripts.causal_baselines_b200.common import REPO, read, write
|
| 9 |
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
def main():
|
| 12 |
parser=argparse.ArgumentParser(description=__doc__)
|
| 13 |
parser.add_argument('--method',required=True,choices=['astrolabe','advdmd'])
|
|
@@ -19,8 +41,7 @@ def main():
|
|
| 19 |
from baselines.advdmd.run import launch
|
| 20 |
launch(argparse.Namespace(run_dir=directory,nproc_per_node=2,nnodes=1,node_rank=0,
|
| 21 |
master_addr='127.0.0.1',master_port=port,dry_run=False))
|
| 22 |
-
|
| 23 |
-
target_steps=read(directory/'config.json')['max_steps']))
|
| 24 |
return
|
| 25 |
from baselines.astrolabe.run import launch
|
| 26 |
launch(argparse.Namespace(run_dir=directory,nproc_per_node=2,nnodes=1,node_rank=0,
|
|
@@ -32,8 +53,7 @@ def main():
|
|
| 32 |
subprocess.run([sys.executable,'-m','torch.distributed.run','--nproc_per_node=2',
|
| 33 |
f'--master_port={port}',str(REPO/'scripts/causal_baselines_b200/worker.py'),
|
| 34 |
f'--config={directory / "config.py"}'],cwd=directory,env=env,check=True)
|
| 35 |
-
|
| 36 |
-
target_steps=read(directory/'budget.json')['total_optimizer_steps']))
|
| 37 |
|
| 38 |
|
| 39 |
if __name__=='__main__':
|
|
|
|
| 1 |
"""Launch the existing baseline implementations with CF-scoped workers."""
|
| 2 |
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
import os
|
| 6 |
from pathlib import Path
|
| 7 |
import subprocess
|
|
|
|
| 10 |
from scripts.causal_baselines_b200.common import REPO, read, write
|
| 11 |
|
| 12 |
|
| 13 |
+
def finish(directory, method):
|
| 14 |
+
if method == 'advdmd':
|
| 15 |
+
expected=read(directory/'config.json')['max_steps']
|
| 16 |
+
files=[directory/'metrics.jsonl']
|
| 17 |
+
checkpoint=directory/f'checkpoints/step-{expected}.pt'
|
| 18 |
+
else:
|
| 19 |
+
expected=read(directory/'budget.json')['total_optimizer_steps']
|
| 20 |
+
files=list((directory/'logs').rglob('metrics.jsonl'))
|
| 21 |
+
matches=list(directory.glob(f'checkpoints_*/checkpoints/checkpoint-{expected}/ready.json'))
|
| 22 |
+
assert len(matches)==1, 'Final Astrolabe checkpoint is incomplete'
|
| 23 |
+
checkpoint=matches[0]
|
| 24 |
+
rows=[json.loads(line) for p in files for line in p.read_text().splitlines()]
|
| 25 |
+
assert len(rows)==expected and max(r['step'] for r in rows)==expected
|
| 26 |
+
assert {r['step'] for r in rows}==set(range(1,expected+1))
|
| 27 |
+
assert all(math.isfinite(v) for r in rows for v in r.values() if isinstance(v,(int,float)))
|
| 28 |
+
assert checkpoint.is_file() and checkpoint.stat().st_size>0
|
| 29 |
+
write(directory/'training_complete.json',dict(passed=True,method=method,target_steps=expected,
|
| 30 |
+
observed_optimizer_steps=len(rows),final_checkpoint=str(checkpoint)))
|
| 31 |
+
|
| 32 |
+
|
| 33 |
def main():
|
| 34 |
parser=argparse.ArgumentParser(description=__doc__)
|
| 35 |
parser.add_argument('--method',required=True,choices=['astrolabe','advdmd'])
|
|
|
|
| 41 |
from baselines.advdmd.run import launch
|
| 42 |
launch(argparse.Namespace(run_dir=directory,nproc_per_node=2,nnodes=1,node_rank=0,
|
| 43 |
master_addr='127.0.0.1',master_port=port,dry_run=False))
|
| 44 |
+
finish(directory,args.method)
|
|
|
|
| 45 |
return
|
| 46 |
from baselines.astrolabe.run import launch
|
| 47 |
launch(argparse.Namespace(run_dir=directory,nproc_per_node=2,nnodes=1,node_rank=0,
|
|
|
|
| 53 |
subprocess.run([sys.executable,'-m','torch.distributed.run','--nproc_per_node=2',
|
| 54 |
f'--master_port={port}',str(REPO/'scripts/causal_baselines_b200/worker.py'),
|
| 55 |
f'--config={directory / "config.py"}'],cwd=directory,env=env,check=True)
|
| 56 |
+
finish(directory,args.method)
|
|
|
|
| 57 |
|
| 58 |
|
| 59 |
if __name__=='__main__':
|