faraway00 commited on
Commit
630f877
·
verified ·
1 Parent(s): 4560921

Refresh verified six-GPU manifest: 506 tuples

Browse files
README.md CHANGED
@@ -32,7 +32,7 @@ dataset_info:
32
 
33
  Tuples: original video, original-video depth, style video, and the unchanged editing instruction.
34
 
35
- Current verified tuples: **197**. Target: 8,400 accepted tuples; processing is ongoing.
36
 
37
  Source: [QingyanBai/Ditto-1M](https://huggingface.co/datasets/QingyanBai/Ditto-1M), revision `aac1417418d8f7e77d4e257d5620c36b2c3a00e8`. Attribution: Qingyan Bai et al., *Ditto: Scaling Instruction-Based Video Editing with a High-Quality Synthetic Dataset*. Source license CC BY-NC-SA 4.0 is retained for this derivative dataset. The original media are unmodified. Depth was estimated using [depth-anything/DA3-LARGE](https://huggingface.co/depth-anything/DA3-LARGE).
38
 
 
32
 
33
  Tuples: original video, original-video depth, style video, and the unchanged editing instruction.
34
 
35
+ Current verified tuples: **506**. Target: 8,400 accepted tuples; processing is ongoing.
36
 
37
  Source: [QingyanBai/Ditto-1M](https://huggingface.co/datasets/QingyanBai/Ditto-1M), revision `aac1417418d8f7e77d4e257d5620c36b2c3a00e8`. Attribution: Qingyan Bai et al., *Ditto: Scaling Instruction-Based Video Editing with a High-Quality Synthetic Dataset*. Source license CC BY-NC-SA 4.0 is retained for this derivative dataset. The original media are unmodified. Depth was estimated using [depth-anything/DA3-LARGE](https://huggingface.co/depth-anything/DA3-LARGE).
38
 
metadata.jsonl CHANGED
The diff for this file is too large to render. See raw diff
 
pipeline/batch_upload.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Durable shared upload queue, one commit for many fully verified samples."""
2
+ import fcntl
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import re
7
+ import time
8
+ from email.utils import parsedate_to_datetime
9
+
10
+ from common import REPO,REV,atomic,sha
11
+
12
+ DEFAULT_ROOT=Path('/opt/styleedit-root-20261025/batch-upload')
13
+ FILES=['source.mp4','edited.mp4','depth.mp4','depth.json','filter.json']
14
+
15
+
16
+ class CommitDeferred(Exception):
17
+ def __init__(self,until):
18
+ self.until=until
19
+ super().__init__('HF commit deferred until '+time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime(until)))
20
+
21
+
22
+ def retry_delay(error,now):
23
+ response=getattr(error,'response',None)
24
+ if getattr(response,'status_code',None)!=429:return None
25
+ headers=getattr(response,'headers',{})
26
+ retry=headers.get('Retry-After') or headers.get('retry-after')
27
+ if retry:
28
+ try:return max(1,float(retry))
29
+ except ValueError:
30
+ try:return max(1,parsedate_to_datetime(retry).timestamp()-now)
31
+ except (ValueError,TypeError):pass
32
+ match=re.search(r'in (?:about )?(\d+)\s*(second|minute|hour)',str(error),re.I)
33
+ if match:return int(match[1])*{'second':1,'minute':60,'hour':3600}[match[2].lower()]
34
+ return 3600
35
+
36
+
37
+ def guarded_commit(root,action,clock=time.time):
38
+ """Media and metadata publishers share a durable 60-second commit budget."""
39
+ root=Path(root);root.mkdir(parents=True,exist_ok=True)
40
+ with (root/'commit.lock').open('a') as lock:
41
+ try:fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
42
+ except BlockingIOError:raise CommitDeferred(clock()+5)
43
+ path=root/'commit-gate.json';state=json.loads(path.read_text()) if path.exists() else {}
44
+ now=clock();until=state.get('not_before',0)
45
+ if now<until:raise CommitDeferred(until)
46
+ atomic(path,{'not_before':now+60,'last_attempt_at':now})
47
+ try:return action()
48
+ except Exception as error:
49
+ delay=retry_delay(error,now)
50
+ if delay is None:raise
51
+ atomic(path,{'not_before':clock()+delay,'last_attempt_at':now,'reason':'HF HTTP 429'})
52
+ raise CommitDeferred(clock()+delay) from None
53
+
54
+
55
+ def enqueue(root,row,directory,filtered,depth,repo):
56
+ root=Path(root);directory=Path(directory).resolve();(root/'pending').mkdir(parents=True,exist_ok=True)
57
+ prefix='data/'+row['style_id']+'/'+row['id']
58
+ hashes={name:{'sha256':sha(directory/name),'bytes':(directory/name).stat().st_size} for name in FILES}
59
+ record={k:row[k] for k in ['id','style_id','style_label','instruction','source_path','edited_path']}
60
+ record.update(source_repo=REPO,source_revision=REV,source_video=prefix+'/source.mp4',source_depth_video=prefix+'/depth.mp4',style_video=prefix+'/edited.mp4',depth_metadata=prefix+'/depth.json',filter_metadata=prefix+'/filter.json',files=dict(hashes),filter_version='core-v1',distance=filtered['distance'],depth=depth)
61
+ atomic(directory/'record.json',record)
62
+ hashes['record.json']={'sha256':sha(directory/'record.json'),'bytes':(directory/'record.json').stat().st_size}
63
+ record['files']=hashes
64
+ job={'row':row,'record':record,'files':hashes,'directory':str(directory),'prefix':prefix,'repo':repo,'queued_at':time.time()}
65
+ done=root/'done'/(row['id']+'.json')
66
+ if not done.exists():atomic(root/'pending'/(row['id']+'.json'),job)
67
+ return job
68
+
69
+
70
+ def load_recovery(row,directory):
71
+ """Reuse completed outputs only after checking their persisted checksums."""
72
+ directory=Path(directory)
73
+ if not all((directory/name).exists() for name in FILES+['record.json']):return None
74
+ record=json.loads((directory/'record.json').read_text())
75
+ for key in ['id','style_id','source_path','edited_path','instruction']:
76
+ if record[key]!=row[key]:raise ValueError('Retained sample identity mismatch: '+row['id'])
77
+ for name in FILES:
78
+ expected=record['files'][name]
79
+ if (directory/name).stat().st_size!=expected['bytes'] or sha(directory/name)!=expected['sha256']:
80
+ raise ValueError('Retained sample checksum mismatch: '+row['id']+'/'+name)
81
+ filtered=json.loads((directory/'filter.json').read_text());depth=json.loads((directory/'depth.json').read_text())
82
+ if filtered.get('status')!='keep':raise ValueError('Retained sample was not accepted')
83
+ return filtered,depth
84
+
85
+
86
+ def wait_receipt(root,jid):
87
+ path=Path(root)/'done'/(jid+'.json')
88
+ while not path.exists():time.sleep(1)
89
+ return json.loads(path.read_text())
90
+
91
+
92
+ class BatchUploader:
93
+ def __init__(self,root,api,clock=time.time,operation_factory=None,fetch_small=None):
94
+ self.root=Path(root);self.api=api;self.clock=clock;self.fetch_small=fetch_small
95
+ self.root.mkdir(parents=True,exist_ok=True)
96
+ for name in ['pending','done']:(self.root/name).mkdir(exist_ok=True)
97
+ if operation_factory is None:
98
+ from huggingface_hub import CommitOperationAdd
99
+ operation_factory=CommitOperationAdd
100
+ self.operation_factory=operation_factory
101
+
102
+ def run_once(self,force=False):
103
+ journal=self.root/'inflight.json'
104
+ if journal.exists():batch=json.loads(journal.read_text());jobs=batch['jobs']
105
+ else:
106
+ jobs=[]
107
+ for path in (self.root/'pending').glob('*.json'):
108
+ if (self.root/'done'/path.name).exists():path.unlink();continue
109
+ jobs.append(json.loads(path.read_text()))
110
+ jobs.sort(key=lambda job:job['queued_at']);jobs=jobs[:32]
111
+ if not jobs or (not force and len(jobs)<32 and self.clock()-jobs[0]['queued_at']<60):return 0
112
+ gate=self.root/'commit-gate.json'
113
+ if gate.exists():
114
+ until=json.loads(gate.read_text()).get('not_before',0)
115
+ if self.clock()<until:raise CommitDeferred(until)
116
+ repo=jobs[0]['repo']
117
+ if any(job['repo']!=repo for job in jobs):raise ValueError('Mixed destination repositories')
118
+ operations=[]
119
+ for job in jobs:
120
+ for name,expected in job['files'].items():
121
+ path=Path(job['directory'])/name
122
+ if path.stat().st_size!=expected['bytes'] or sha(path)!=expected['sha256']:
123
+ raise ValueError('Queued local file changed: '+job['row']['id']+'/'+name)
124
+ operations.append(self.operation_factory(path_in_repo=job['prefix']+'/'+name,path_or_fileobj=str(path)))
125
+ print('BATCH_COMMIT_START','samples',len(jobs),'files',len(operations),flush=True)
126
+ commit=guarded_commit(self.root,lambda:self.api.create_commit(repo_id=repo,repo_type='dataset',operations=operations,commit_message=f'Add verified Ditto + DA3 batch: {len(jobs)} tuples'),clock=self.clock)
127
+ batch={'commit':commit.oid,'jobs':jobs,'committed_at':self.clock()};atomic(journal,batch)
128
+ # Persist the returned commit before verification. A restart reuses it.
129
+ all_paths=[job['prefix']+'/'+name for job in jobs for name in job['files']]
130
+ infos={info.path:info for info in self.api.get_paths_info(jobs[0]['repo'],all_paths,repo_type='dataset',revision=batch['commit'])}
131
+ for job in jobs:
132
+ for name,expected in job['files'].items():
133
+ path=job['prefix']+'/'+name;info=infos[path]
134
+ if info.size!=expected['bytes']:raise ValueError('Batch remote size mismatch: '+path)
135
+ lfs=getattr(info,'lfs',None)
136
+ if lfs:digest=lfs.sha256 if hasattr(lfs,'sha256') else lfs['sha256']
137
+ elif self.fetch_small:digest=self.fetch_small(job['repo'],path,batch['commit'])
138
+ else:
139
+ import requests
140
+ from huggingface_hub import hf_hub_url,get_token
141
+ response=requests.get(hf_hub_url(job['repo'],path,repo_type='dataset',revision=batch['commit']),headers={'Authorization':'Bearer '+get_token()},timeout=120);response.raise_for_status()
142
+ digest=__import__('hashlib').sha256(response.content).hexdigest()
143
+ if digest!=expected['sha256']:raise ValueError('Batch remote SHA256 mismatch: '+path)
144
+ # No receipt is emitted until every file in the batch passes verification.
145
+ for job in jobs:
146
+ receipt={'commit':batch['commit'],'verification':'all file sizes and SHA256 at immutable batch commit','record':job['record'],'seconds':self.clock()-job['queued_at'],'batch_samples':len(jobs)}
147
+ atomic(self.root/'done'/(job['row']['id']+'.json'),receipt)
148
+ (self.root/'pending'/(job['row']['id']+'.json')).unlink(missing_ok=True)
149
+ journal.unlink();print('BATCH_VERIFIED',len(jobs),batch['commit'],flush=True)
150
+ return len(jobs)
151
+
152
+
153
+ def main():
154
+ from huggingface_hub import HfApi
155
+ root=Path(os.environ.get('STYLEEDIT_BATCH_ROOT',str(DEFAULT_ROOT)));root.mkdir(parents=True,exist_ok=True)
156
+ lock=(root/'uploader.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
157
+ atomic(root/'process.json',{'pid':os.getpid()})
158
+ uploader=BatchUploader(root,HfApi())
159
+ while True:
160
+ delay=5;state={'utc':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'state':'running'}
161
+ try:state['new_verified']=uploader.run_once()
162
+ except CommitDeferred as deferred:
163
+ state.update(state='waiting_for_commit_budget',retry_at=deferred.until);delay=min(30,max(1,deferred.until-time.time()))
164
+ except Exception as error:
165
+ state.update(state='retrying_retained_batch',error=type(error).__name__+': '+str(error)[:240]);delay=30
166
+ print('BATCH_RETRY',state['error'],flush=True)
167
+ state['pending']=len(list((root/'pending').glob('*.json')));state['verified_receipts']=len(list((root/'done').glob('*.json')))
168
+ atomic(root/'status.json',state);time.sleep(delay)
169
+
170
+
171
+ if __name__=='__main__':main()
pipeline/pipeline.py CHANGED
@@ -54,50 +54,40 @@ class Run:
54
  used=sum(p.stat().st_size for p in self.scratch.rglob('*') if p.is_file());free=shutil.disk_usage(self.scratch).free
55
  headroom=self.a.window*2*200*1024**2+2*1024**3
56
  return used+headroom<self.a.scratch_gib*1024**3 and free>self.a.reserve_gib*1024**3+headroom
 
 
 
 
 
 
57
  def ship(self,row,d,filtered,depth):
58
- from huggingface_hub import HfApi,CommitOperationAdd
59
- t=time.monotonic();prefix='data/'+row['style_id']+'/'+row['id'];files=['source.mp4','edited.mp4','depth.mp4','depth.json','filter.json']
60
- hashes={name:{'sha256':sha(d/name),'bytes':(d/name).stat().st_size} for name in files}
61
- record={k:row[k] for k in ['id','style_id','style_label','instruction','source_path','edited_path']}
62
- record.update(source_repo=REPO,source_revision=REV,source_video=prefix+'/source.mp4',source_depth_video=prefix+'/depth.mp4',style_video=prefix+'/edited.mp4',depth_metadata=prefix+'/depth.json',filter_metadata=prefix+'/filter.json',files=hashes,filter_version='core-v1',distance=filtered['distance'],depth=depth)
63
- atomic(d/'record.json',record);files.append('record.json');hashes['record.json']={'sha256':sha(d/'record.json'),'bytes':(d/'record.json').stat().st_size}
64
- # A complete sample is added by one commit. Retrying replaces the same paths.
65
- api=HfApi()
66
- for attempt in range(5):
67
- try:
68
- print('UPLOAD_START',row['id'],'attempt',attempt+1,flush=True)
69
- commit=api.create_commit(repo_id=self.a.repo,repo_type='dataset',operations=[CommitOperationAdd(path_in_repo=prefix+'/'+name,path_or_fileobj=str(d/name)) for name in files],commit_message='Add verified Ditto + DA3 tuple '+row['id'])
70
- infos=api.get_paths_info(self.a.repo,[prefix+'/'+name for name in files],repo_type='dataset',revision=commit.oid)
71
- byname={v.path:v for v in infos}
72
- for name in files:
73
- info=byname[prefix+'/'+name];expected=hashes[name]
74
- if info.size!=expected['bytes']:raise ValueError('Remote size mismatch: '+name)
75
- lfs=getattr(info,'lfs',None)
76
- if lfs:
77
- digest=lfs.sha256 if hasattr(lfs,'sha256') else lfs['sha256']
78
- if digest!=expected['sha256']:raise ValueError('Remote LFS SHA mismatch: '+name)
79
- else:
80
- # Git blob IDs are not SHA256; verify the actual small remote bytes.
81
- import requests
82
- from huggingface_hub import hf_hub_url,get_token
83
- r=requests.get(hf_hub_url(self.a.repo,prefix+'/'+name,repo_type='dataset',revision=commit.oid),headers={'Authorization':'Bearer '+get_token()},timeout=120);r.raise_for_status()
84
- if hashlib.sha256(r.content).hexdigest()!=expected['sha256']:raise ValueError('Remote small-file SHA mismatch')
85
- receipt={'commit':commit.oid,'verification':'all file sizes and SHA256, LFS SHA256 or actual bytes','seconds':time.monotonic()-t,'record':record}
86
- atomic(self.state/'receipts'/(row['id']+'.json'),receipt);self.record(row,'verified',receipt,time.time());self.metrics['upload'].append(receipt['seconds']);print('UPLOAD_VERIFIED',row['id'],round(receipt['seconds'],2),flush=True);return receipt
87
- except Exception as exc:
88
- print('UPLOAD_RETRY',row['id'],type(exc).__name__,getattr(getattr(exc,'response',None),'status_code',None),flush=True)
89
- if attempt==4:raise
90
- time.sleep(min(30,2**attempt))
91
  def process_depth(self,row,d,filtered,worker):
92
  try:
93
  dep=worker.call({'row':row,'dir':str(d)});self.metrics['depth'].append(dep);print('DEPTH',row['id'],round(dep['total_seconds'],2),flush=True)
94
- self.record(row,'uploading');future=self.upload.submit(self.ship,row,d,filtered,dep);self.uploads.append(future)
95
  return True
96
  except Exception as e:
97
  err={'id':row['id'],'error':str(e),'traceback':traceback.format_exc()};self.metrics['errors'].append(err);self.record(row,'error',err);print('JOB_ERROR',row['id'],str(e)[:300],flush=True)
98
  return False
99
  def run(self):
100
  a=self.a;allrows=json.loads(Path(a.plan).read_text());existing=self.counts();done_sources=set()
 
 
 
 
 
 
 
 
 
 
 
101
  if not self.space():raise RuntimeError('Insufficient scratch capacity/free space for a bounded download window')
102
  with self.db_lock:
103
  for sid,src in self.db.execute("SELECT style_id,source FROM jobs WHERE status='verified'"):done_sources.add((sid,src))
 
54
  used=sum(p.stat().st_size for p in self.scratch.rglob('*') if p.is_file());free=shutil.disk_usage(self.scratch).free
55
  headroom=self.a.window*2*200*1024**2+2*1024**3
56
  return used+headroom<self.a.scratch_gib*1024**3 and free>self.a.reserve_gib*1024**3+headroom
57
+ def queue_upload(self,row,d,filtered,depth):
58
+ from batch_upload import DEFAULT_ROOT,enqueue
59
+ self.record(row,'uploading')
60
+ enqueue(os.environ.get('STYLEEDIT_BATCH_ROOT',str(DEFAULT_ROOT)),row,d,filtered,depth,self.a.repo)
61
+ future=self.upload.submit(self.ship,row,d,filtered,depth);self.uploads.append(future)
62
+ return future
63
  def ship(self,row,d,filtered,depth):
64
+ from batch_upload import DEFAULT_ROOT,wait_receipt
65
+ receipt=wait_receipt(os.environ.get('STYLEEDIT_BATCH_ROOT',str(DEFAULT_ROOT)),row['id'])
66
+ atomic(self.state/'receipts'/(row['id']+'.json'),receipt)
67
+ self.record(row,'verified',receipt,time.time());self.metrics['upload'].append(receipt['seconds'])
68
+ print('UPLOAD_VERIFIED',row['id'],round(receipt['seconds'],2),'batch_samples',receipt['batch_samples'],flush=True)
69
+ return receipt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  def process_depth(self,row,d,filtered,worker):
71
  try:
72
  dep=worker.call({'row':row,'dir':str(d)});self.metrics['depth'].append(dep);print('DEPTH',row['id'],round(dep['total_seconds'],2),flush=True)
73
+ self.queue_upload(row,d,filtered,dep)
74
  return True
75
  except Exception as e:
76
  err={'id':row['id'],'error':str(e),'traceback':traceback.format_exc()};self.metrics['errors'].append(err);self.record(row,'error',err);print('JOB_ERROR',row['id'],str(e)[:300],flush=True)
77
  return False
78
  def run(self):
79
  a=self.a;allrows=json.loads(Path(a.plan).read_text());existing=self.counts();done_sources=set()
80
+ # Recover completed local depth outputs before scheduling any GPU work.
81
+ from batch_upload import load_recovery
82
+ lookup={r['id']:r for r in allrows}
83
+ with self.db_lock:unfinished=list(self.db.execute("SELECT id FROM jobs WHERE status NOT IN ('verified','reject')"))
84
+ for (jid,) in unfinished:
85
+ row=lookup.get(jid)
86
+ if row is None:continue
87
+ d=self.scratch/jid;retained=load_recovery(row,d)
88
+ if retained is not None:
89
+ self.queue_upload(row,d,*retained);done_sources.add((row['style_id'],row['source_path']))
90
+ print('REUSED_DEPTH_OUTPUT',jid,flush=True)
91
  if not self.space():raise RuntimeError('Insufficient scratch capacity/free space for a bounded download window')
92
  with self.db_lock:
93
  for sid,src in self.db.execute("SELECT style_id,source FROM jobs WHERE status='verified'"):done_sources.add((sid,src))
pipeline/root_supervisor.py CHANGED
@@ -15,6 +15,8 @@ STATE=Path('/opt/styleedit-sixgpu-recovered')
15
  PERSIST=Path('/workspace/styleedit-streaming-20261024/root-disk-20261025')
16
  DOWNLOADER=None
17
  DOWNLOAD_RETRIES=0
 
 
18
  os.environ.update(HF_TOKEN_PATH='/root/.styleedit-hf-token',PYTHONPATH='/opt/depth-anything-3-code/src',HF_HUB_DISABLE_PROGRESS_BARS='1',OMP_NUM_THREADS='4',OPENBLAS_NUM_THREADS='2')
19
  sys.path.insert(0,str(APP))
20
 
@@ -23,7 +25,10 @@ def atomic(path,value):
23
  temp=path.with_name(path.name+'.tmp');temp.write_text(json.dumps(value,indent=2));os.replace(temp,path)
24
 
25
  def status(stage,children):
26
- global DOWNLOADER,DOWNLOAD_RETRIES
 
 
 
27
  if DOWNLOADER is not None and DOWNLOADER.poll() not in (None,0):
28
  if DOWNLOAD_RETRIES>=3: raise RuntimeError('Archive download/extraction failed repeatedly; see download.log')
29
  DOWNLOAD_RETRIES+=1;DOWNLOADER=start_download()
@@ -35,6 +40,8 @@ def status(stage,children):
35
  counts.update(dict(db.execute("SELECT style_id,count(*) FROM jobs WHERE status='verified' GROUP BY style_id")))
36
  states.update(dict(db.execute('SELECT status,count(*) FROM jobs GROUP BY status')))
37
  result={'utc':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'stage':stage,'verified':sum(counts.values()),'counts':dict(counts),'statuses':dict(states),'root_free_bytes':__import__('shutil').disk_usage(ROOT).free,'archives_extracted':[c for c in ['source','global_style1','global_style2'] if (ROOT/(c+'.extracted.json')).exists()],'processes':{str(k):{'pid':v.pid,'returncode':v.poll()} for k,v in children.items()}}
 
 
38
  with sqlite3.connect(ROOT/'downloads.sqlite',timeout=30) as db:
39
  result['archive_download_bytes']=db.execute('SELECT coalesce(sum(size),0) FROM chunks').fetchone()[0]
40
  atomic(ROOT/'status.json',result);atomic(STATE/'status.json',result)
@@ -42,22 +49,39 @@ def status(stage,children):
42
  except OSError as error: print('DURABLE_STATUS_RETRY',type(error).__name__,flush=True)
43
  return result
44
 
 
 
 
 
 
 
45
  def start_download():
 
 
 
 
 
46
  with (ROOT/'download.log').open('a') as log:
47
  child=subprocess.Popen([sys.executable,'-u',str(APP/'local_media.py')],stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
48
  atomic(ROOT/'download-process.json',{'pid':child.pid})
49
  return child
50
 
 
 
 
 
51
  def start(gpu,stage):
52
  env=dict(os.environ,CUDA_VISIBLE_DEVICES=str(gpu),STYLEEDIT_GPU_LOCK=f'/opt/styleedit-gpu-{gpu}.lock')
53
- args=[sys.executable,'-u',str(APP/'pipeline.py'),'--local-media-root',str(ROOT/'media'),'--plan',str(ROOT/f'{stage}-gpu{gpu}.json'),'--state',str(STATE/f'gpu{gpu}'),'--scratch',f'/opt/styleedit-sixgpu-scratch/gpu{gpu}','--limit','0','--per-style','100','--window','6','--download-workers','4','--upload-workers','1','--scratch-gib','60','--reserve-gib','50']
54
  with (ROOT/f'{stage}-gpu{gpu}.log').open('a') as log:
55
  return subprocess.Popen(args,env=env,stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
56
 
57
  def main():
58
- global DOWNLOADER
59
  ROOT.mkdir(exist_ok=True)
60
  lock=(ROOT/'supervisor.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
 
 
61
  DOWNLOADER=start_download()
62
  while not (ROOT/'RESTORED').exists():
63
  status('restoring_runtime',{});time.sleep(20)
@@ -65,6 +89,7 @@ def main():
65
  api=HfApi();print('AUTH_OK',api.whoami()['name'],flush=True);api.auth_check('faraway00/StyleEdit',repo_type='dataset')
66
  from reconcile_remote import reconcile
67
  reconcile()
 
68
  rows=json.loads((APP/'candidates.json').read_text());assignment={s:i%6 for i,s in enumerate(sorted({r['style_id'] for r in rows}))}
69
  for gpu in range(6):
70
  with sqlite3.connect(STATE/f'gpu{gpu}'/'jobs.sqlite') as db:
@@ -75,26 +100,32 @@ def main():
75
  atomic(ROOT/f'all-gpu{gpu}.json',shard)
76
  atomic(ROOT/f'global_style1-gpu{gpu}.json',[r for r in shard if r['edited_path'].startswith('global_style1/')])
77
  import sixgpu_publish
78
- last_publish=0
79
  for stage,required in [('global_style1',['source','global_style1']),('all',['source','global_style1','global_style2'])]:
80
  while not all((ROOT/(c+'.extracted.json')).exists() for c in required):
81
  status('downloading_extracting_'+stage,{})
82
- if time.monotonic()-last_publish>300:
83
  try: sixgpu_publish.publish();last_publish=time.monotonic()
84
  except Exception as error:print('MANIFEST_RETRY',type(error).__name__,str(error)[:200],flush=True)
85
  time.sleep(30)
86
  children={g:start(g,stage) for g in range(6)}
87
  while any(p.poll() is None for p in children.values()):
88
  status('processing_'+stage,children)
89
- if time.monotonic()-last_publish>300:
90
  try: sixgpu_publish.publish();last_publish=time.monotonic()
91
  except Exception as error:print('MANIFEST_RETRY',type(error).__name__,str(error)[:200],flush=True)
92
  time.sleep(30)
93
  for gpu,child in children.items():
94
  summary=json.loads((STATE/f'gpu{gpu}'/'summary.json').read_text())
95
  if summary['errors'] or child.returncode not in (0,2):raise RuntimeError(f'GPU {gpu} failed; outputs preserved, inspect {stage}-gpu{gpu}.log')
96
- sixgpu_publish.publish()
 
97
  complete=all(json.loads((STATE/f'gpu{g}'/'quota-report.json').read_text())['complete'] for g in range(6))
 
 
 
 
 
98
  status('complete' if complete else 'candidate_pool_exhausted',{})
99
  print('ROOT_PIPELINE_FINISHED',complete,flush=True)
100
 
 
15
  PERSIST=Path('/workspace/styleedit-streaming-20261024/root-disk-20261025')
16
  DOWNLOADER=None
17
  DOWNLOAD_RETRIES=0
18
+ UPLOADER=None
19
+ UPLOAD_RETRIES=0
20
  os.environ.update(HF_TOKEN_PATH='/root/.styleedit-hf-token',PYTHONPATH='/opt/depth-anything-3-code/src',HF_HUB_DISABLE_PROGRESS_BARS='1',OMP_NUM_THREADS='4',OPENBLAS_NUM_THREADS='2')
21
  sys.path.insert(0,str(APP))
22
 
 
25
  temp=path.with_name(path.name+'.tmp');temp.write_text(json.dumps(value,indent=2));os.replace(temp,path)
26
 
27
  def status(stage,children):
28
+ global DOWNLOADER,DOWNLOAD_RETRIES,UPLOADER,UPLOAD_RETRIES
29
+ if UPLOADER is not None and UPLOADER.poll() is not None:
30
+ if UPLOAD_RETRIES>=3:raise RuntimeError('Batch uploader repeatedly exited; queue and media preserved')
31
+ UPLOAD_RETRIES+=1;UPLOADER=start_uploader()
32
  if DOWNLOADER is not None and DOWNLOADER.poll() not in (None,0):
33
  if DOWNLOAD_RETRIES>=3: raise RuntimeError('Archive download/extraction failed repeatedly; see download.log')
34
  DOWNLOAD_RETRIES+=1;DOWNLOADER=start_download()
 
40
  counts.update(dict(db.execute("SELECT style_id,count(*) FROM jobs WHERE status='verified' GROUP BY style_id")))
41
  states.update(dict(db.execute('SELECT status,count(*) FROM jobs GROUP BY status')))
42
  result={'utc':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'stage':stage,'verified':sum(counts.values()),'counts':dict(counts),'statuses':dict(states),'root_free_bytes':__import__('shutil').disk_usage(ROOT).free,'archives_extracted':[c for c in ['source','global_style1','global_style2'] if (ROOT/(c+'.extracted.json')).exists()],'processes':{str(k):{'pid':v.pid,'returncode':v.poll()} for k,v in children.items()}}
43
+ upload_status=ROOT/'batch-upload/status.json'
44
+ if upload_status.exists():result['batch_upload']=json.loads(upload_status.read_text())
45
  with sqlite3.connect(ROOT/'downloads.sqlite',timeout=30) as db:
46
  result['archive_download_bytes']=db.execute('SELECT coalesce(sum(size),0) FROM chunks').fetchone()[0]
47
  atomic(ROOT/'status.json',result);atomic(STATE/'status.json',result)
 
49
  except OSError as error: print('DURABLE_STATUS_RETRY',type(error).__name__,flush=True)
50
  return result
51
 
52
+ class ExistingDownloader:
53
+ def __init__(self,pid):self.pid=pid
54
+ def poll(self):
55
+ try:return None if b'local_media.py' in Path(f'/proc/{self.pid}/cmdline').read_bytes() else 1
56
+ except OSError:return 1
57
+
58
  def start_download():
59
+ marker=ROOT/'download-process.json'
60
+ if marker.exists():
61
+ existing=ExistingDownloader(json.loads(marker.read_text())['pid'])
62
+ if existing.poll() is None:
63
+ print('DOWNLOAD_ADOPTED',existing.pid,flush=True);return existing
64
  with (ROOT/'download.log').open('a') as log:
65
  child=subprocess.Popen([sys.executable,'-u',str(APP/'local_media.py')],stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
66
  atomic(ROOT/'download-process.json',{'pid':child.pid})
67
  return child
68
 
69
+ def start_uploader():
70
+ with (ROOT/'batch-upload.log').open('a') as log:
71
+ return subprocess.Popen([sys.executable,'-u',str(APP/'batch_upload.py')],stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
72
+
73
  def start(gpu,stage):
74
  env=dict(os.environ,CUDA_VISIBLE_DEVICES=str(gpu),STYLEEDIT_GPU_LOCK=f'/opt/styleedit-gpu-{gpu}.lock')
75
+ args=[sys.executable,'-u',str(APP/'pipeline.py'),'--local-media-root',str(ROOT/'media'),'--plan',str(ROOT/f'{stage}-gpu{gpu}.json'),'--state',str(STATE/f'gpu{gpu}'),'--scratch',f'/opt/styleedit-sixgpu-scratch/gpu{gpu}','--limit','0','--per-style','100','--window','6','--download-workers','4','--upload-workers','8','--scratch-gib','60','--reserve-gib','50']
76
  with (ROOT/f'{stage}-gpu{gpu}.log').open('a') as log:
77
  return subprocess.Popen(args,env=env,stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
78
 
79
  def main():
80
+ global DOWNLOADER,UPLOADER
81
  ROOT.mkdir(exist_ok=True)
82
  lock=(ROOT/'supervisor.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
83
+ failure=ROOT/'failure.json'
84
+ if failure.exists():os.replace(failure,ROOT/f'failure-before-{int(time.time())}.json')
85
  DOWNLOADER=start_download()
86
  while not (ROOT/'RESTORED').exists():
87
  status('restoring_runtime',{});time.sleep(20)
 
89
  api=HfApi();print('AUTH_OK',api.whoami()['name'],flush=True);api.auth_check('faraway00/StyleEdit',repo_type='dataset')
90
  from reconcile_remote import reconcile
91
  reconcile()
92
+ UPLOADER=start_uploader()
93
  rows=json.loads((APP/'candidates.json').read_text());assignment={s:i%6 for i,s in enumerate(sorted({r['style_id'] for r in rows}))}
94
  for gpu in range(6):
95
  with sqlite3.connect(STATE/f'gpu{gpu}'/'jobs.sqlite') as db:
 
100
  atomic(ROOT/f'all-gpu{gpu}.json',shard)
101
  atomic(ROOT/f'global_style1-gpu{gpu}.json',[r for r in shard if r['edited_path'].startswith('global_style1/')])
102
  import sixgpu_publish
103
+ last_publish=time.monotonic()
104
  for stage,required in [('global_style1',['source','global_style1']),('all',['source','global_style1','global_style2'])]:
105
  while not all((ROOT/(c+'.extracted.json')).exists() for c in required):
106
  status('downloading_extracting_'+stage,{})
107
+ if time.monotonic()-last_publish>600:
108
  try: sixgpu_publish.publish();last_publish=time.monotonic()
109
  except Exception as error:print('MANIFEST_RETRY',type(error).__name__,str(error)[:200],flush=True)
110
  time.sleep(30)
111
  children={g:start(g,stage) for g in range(6)}
112
  while any(p.poll() is None for p in children.values()):
113
  status('processing_'+stage,children)
114
+ if time.monotonic()-last_publish>600:
115
  try: sixgpu_publish.publish();last_publish=time.monotonic()
116
  except Exception as error:print('MANIFEST_RETRY',type(error).__name__,str(error)[:200],flush=True)
117
  time.sleep(30)
118
  for gpu,child in children.items():
119
  summary=json.loads((STATE/f'gpu{gpu}'/'summary.json').read_text())
120
  if summary['errors'] or child.returncode not in (0,2):raise RuntimeError(f'GPU {gpu} failed; outputs preserved, inspect {stage}-gpu{gpu}.log')
121
+ try:sixgpu_publish.publish()
122
+ except Exception as error:print('MANIFEST_RETRY',type(error).__name__,str(error)[:200],flush=True)
123
  complete=all(json.loads((STATE/f'gpu{g}'/'quota-report.json').read_text())['complete'] for g in range(6))
124
+ from batch_upload import CommitDeferred
125
+ while True:
126
+ try:sixgpu_publish.publish();break
127
+ except CommitDeferred as deferred:
128
+ status('awaiting_final_manifest',{});time.sleep(min(30,max(1,deferred.until-time.time())))
129
  status('complete' if complete else 'candidate_pool_exhausted',{})
130
  print('ROOT_PIPELINE_FINISHED',complete,flush=True)
131
 
pipeline/sixgpu_publish.py CHANGED
@@ -33,14 +33,15 @@ def publish():
33
  ops=[CommitOperationAdd(path_in_repo='metadata.jsonl',path_or_fileobj=str(out))]
34
  status=ROOT/'status.json'
35
  if status.exists():ops.append(CommitOperationAdd(path_in_repo='progress/sixgpu-status.json',path_or_fileobj=str(status)))
36
- for name in ['sixgpu_run.py','sixgpu_publish.py','workers.py','pipeline.py','local_media.py','root_supervisor.py','reconcile_remote.py','manifest_guard.py']:
37
  ops.append(CommitOperationAdd(path_in_repo='pipeline/'+name,path_or_fileobj=str(APP/name)))
38
  template=Path('/opt/styleedit-root-20261025/dataset-card-template.md')
39
  if template.exists():
40
  card=template.read_text().replace('{{verified_tuples}}',str(len(manifest)))
41
  ops.append(CommitOperationAdd(path_in_repo='README.md',path_or_fileobj=card.encode()))
42
- c=HfApi().create_commit(repo_id='faraway00/StyleEdit',repo_type='dataset',operations=ops,
43
- commit_message=f'Refresh verified six-GPU manifest: {len(manifest)} tuples')
 
44
  (ROOT/'manifest-published.json').write_text(json.dumps({'commit':c.oid,'tuples':len(manifest),'time':time.time()}))
45
  print('MANIFEST_VERIFIED_ONLY',len(manifest),c.oid,flush=True)
46
 
 
33
  ops=[CommitOperationAdd(path_in_repo='metadata.jsonl',path_or_fileobj=str(out))]
34
  status=ROOT/'status.json'
35
  if status.exists():ops.append(CommitOperationAdd(path_in_repo='progress/sixgpu-status.json',path_or_fileobj=str(status)))
36
+ for name in ['sixgpu_run.py','sixgpu_publish.py','workers.py','pipeline.py','local_media.py','root_supervisor.py','reconcile_remote.py','manifest_guard.py','batch_upload.py']:
37
  ops.append(CommitOperationAdd(path_in_repo='pipeline/'+name,path_or_fileobj=str(APP/name)))
38
  template=Path('/opt/styleedit-root-20261025/dataset-card-template.md')
39
  if template.exists():
40
  card=template.read_text().replace('{{verified_tuples}}',str(len(manifest)))
41
  ops.append(CommitOperationAdd(path_in_repo='README.md',path_or_fileobj=card.encode()))
42
+ from batch_upload import DEFAULT_ROOT,guarded_commit
43
+ c=guarded_commit(os.environ.get('STYLEEDIT_BATCH_ROOT',str(DEFAULT_ROOT)),lambda:HfApi().create_commit(repo_id='faraway00/StyleEdit',repo_type='dataset',operations=ops,
44
+ commit_message=f'Refresh verified six-GPU manifest: {len(manifest)} tuples'))
45
  (ROOT/'manifest-published.json').write_text(json.dumps({'commit':c.oid,'tuples':len(manifest),'time':time.time()}))
46
  print('MANIFEST_VERIFIED_ONLY',len(manifest),c.oid,flush=True)
47
 
progress/sixgpu-status.json CHANGED
@@ -1,113 +1,132 @@
1
  {
2
- "utc": "2026-10-25T06:50:19Z",
3
  "stage": "processing_global_style1",
4
- "verified": 197,
5
  "counts": {
6
- "00e5f0752aae": 1,
7
  "10ae00528692": 2,
8
- "26b03a8ae47d": 3,
9
- "4744afcbd909": 5,
10
- "5501b7377488": 6,
11
- "6ea8adbc0823": 4,
12
- "817d0d364240": 1,
13
- "baf401925b12": 3,
14
- "d2bef4453db8": 3,
15
- "ef610916460f": 3,
16
- "0423a6080620": 3,
17
- "2cb8a9c29e3c": 3,
18
- "3ac416bb5d5d": 3,
19
- "4d36d1bce511": 2,
20
- "6f448a5d5b0b": 1,
21
- "81b0039d0562": 4,
22
- "9b955dbb5c1b": 5,
23
- "aceae18cfd54": 5,
24
- "c3c090430cbb": 2,
25
- "f67cd2014f0f": 4,
26
- "09229cb3538e": 4,
27
- "2f7f947cf39e": 3,
28
- "3ec4685a5ca4": 1,
29
- "593b6d061243": 4,
30
- "9fd740550a13": 2,
31
- "b4b7ccdb3223": 1,
32
- "c44e535bbe8e": 7,
33
- "da3f08c0ab94": 1,
34
- "e4157f8b450b": 7,
35
- "f67ebc7f1288": 2,
36
- "0972e1eed1b3": 4,
37
- "182ecc60160c": 3,
38
- "305681c6a53f": 4,
39
- "43ab900339a0": 1,
40
- "522b61489406": 1,
41
- "5b56e37c1ba9": 1,
42
- "a55078c730d6": 1,
43
- "b4c4c14310ba": 3,
44
- "cace0fd21b19": 1,
45
- "dbcc16915464": 1,
 
 
 
 
 
 
 
 
 
46
  "ec2035ada05d": 1,
47
  "f990050311bc": 13,
48
- "0bee0e7e6dc5": 2,
49
- "18af27ddab58": 1,
50
- "33286a1a191b": 1,
51
- "43f4c40b9086": 1,
52
- "52545659e5cb": 2,
53
- "5dff93f3a267": 3,
54
- "7ac8d62ccfb2": 3,
55
- "85246a0d9ced": 6,
56
- "a56ad3f24408": 1,
57
- "b5c8be681334": 2,
58
  "ce16eed69d0e": 12,
59
- "0fee9b184beb": 1,
60
- "194290896821": 6,
61
- "36f7a34ae77c": 1,
62
- "453daa7e1ef3": 2,
 
 
63
  "526f7f26e7a6": 2,
64
- "649bb29ad7f9": 2,
65
- "810c3bcf0812": 1,
66
- "8f84dd32762c": 4,
67
- "a78ae8b77085": 4,
68
- "b7eb902e7b22": 1,
69
- "cfdb284d6b07": 3,
70
- "ee3d28fd4cc8": 5,
71
- "ff3dbf0e95b5": 2
72
  },
73
  "statuses": {
74
- "downloading": 9,
75
- "filtering": 5,
76
- "reject": 9,
77
- "verified": 197,
78
- "uploading": 1,
79
- "depth": 3
80
  },
81
- "root_free_bytes": 1229618855936,
82
  "archives_extracted": [
83
  "source",
84
- "global_style1"
 
85
  ],
86
  "processes": {
87
  "0": {
88
- "pid": 11135,
89
  "returncode": null
90
  },
91
  "1": {
92
- "pid": 11136,
93
  "returncode": null
94
  },
95
  "2": {
96
- "pid": 11137,
97
  "returncode": null
98
  },
99
  "3": {
100
- "pid": 11138,
101
  "returncode": null
102
  },
103
  "4": {
104
- "pid": 11139,
105
  "returncode": null
106
  },
107
  "5": {
108
- "pid": 11140,
109
  "returncode": null
110
  }
111
  },
112
- "archive_download_bytes": 462584238675
 
 
 
 
 
 
 
113
  }
 
1
  {
2
+ "utc": "2026-10-25T08:30:13Z",
3
  "stage": "processing_global_style1",
4
+ "verified": 506,
5
  "counts": {
6
+ "00e5f0752aae": 6,
7
  "10ae00528692": 2,
8
+ "26b03a8ae47d": 8,
9
+ "389150a97721": 2,
10
+ "4744afcbd909": 9,
11
+ "5501b7377488": 9,
12
+ "6ea8adbc0823": 8,
13
+ "817d0d364240": 4,
14
+ "baf401925b12": 6,
15
+ "d2bef4453db8": 5,
16
+ "e212a26e5c9c": 2,
17
+ "ef610916460f": 11,
18
+ "0423a6080620": 8,
19
+ "128131ec4461": 2,
20
+ "2cb8a9c29e3c": 9,
21
+ "3ac416bb5d5d": 8,
22
+ "4d36d1bce511": 6,
23
+ "5918de0a576d": 5,
24
+ "6f448a5d5b0b": 10,
25
+ "81b0039d0562": 6,
26
+ "9b955dbb5c1b": 11,
27
+ "aceae18cfd54": 10,
28
+ "c3c090430cbb": 3,
29
+ "f67cd2014f0f": 7,
30
+ "09229cb3538e": 8,
31
+ "15f81c9f4fec": 1,
32
+ "2f7f947cf39e": 7,
33
+ "3ec4685a5ca4": 5,
34
+ "51431cad2ac6": 2,
35
+ "593b6d061243": 9,
36
+ "78c809cc2d9d": 1,
37
+ "9fd740550a13": 4,
38
+ "b4b7ccdb3223": 3,
39
+ "c44e535bbe8e": 16,
40
+ "da3f08c0ab94": 5,
41
+ "e4157f8b450b": 11,
42
+ "f67ebc7f1288": 10,
43
+ "0972e1eed1b3": 11,
44
+ "182ecc60160c": 5,
45
+ "305681c6a53f": 14,
46
+ "43ab900339a0": 9,
47
+ "522b61489406": 4,
48
+ "5b56e37c1ba9": 6,
49
+ "7a7dc432f5ae": 1,
50
+ "84d6668b53d8": 9,
51
+ "a55078c730d6": 2,
52
+ "b4c4c14310ba": 4,
53
+ "cace0fd21b19": 6,
54
+ "dbcc16915464": 7,
55
  "ec2035ada05d": 1,
56
  "f990050311bc": 13,
57
+ "0bee0e7e6dc5": 8,
58
+ "18af27ddab58": 3,
59
+ "33286a1a191b": 3,
60
+ "43f4c40b9086": 2,
61
+ "52545659e5cb": 9,
62
+ "5dff93f3a267": 7,
63
+ "7ac8d62ccfb2": 10,
64
+ "85246a0d9ced": 11,
65
+ "a56ad3f24408": 8,
66
+ "b5c8be681334": 8,
67
  "ce16eed69d0e": 12,
68
+ "ece6b74cb9be": 1,
69
+ "fa41fc883487": 4,
70
+ "0fee9b184beb": 4,
71
+ "194290896821": 10,
72
+ "36f7a34ae77c": 11,
73
+ "453daa7e1ef3": 3,
74
  "526f7f26e7a6": 2,
75
+ "649bb29ad7f9": 7,
76
+ "810c3bcf0812": 2,
77
+ "8f84dd32762c": 7,
78
+ "a78ae8b77085": 9,
79
+ "b7eb902e7b22": 6,
80
+ "cfdb284d6b07": 10,
81
+ "ee3d28fd4cc8": 9,
82
+ "ff3dbf0e95b5": 9
83
  },
84
  "statuses": {
85
+ "depth": 5,
86
+ "downloading": 13,
87
+ "filtering": 6,
88
+ "reject": 385,
89
+ "uploading": 1907,
90
+ "verified": 506
91
  },
92
+ "root_free_bytes": 984420581376,
93
  "archives_extracted": [
94
  "source",
95
+ "global_style1",
96
+ "global_style2"
97
  ],
98
  "processes": {
99
  "0": {
100
+ "pid": 45060,
101
  "returncode": null
102
  },
103
  "1": {
104
+ "pid": 45061,
105
  "returncode": null
106
  },
107
  "2": {
108
+ "pid": 45062,
109
  "returncode": null
110
  },
111
  "3": {
112
+ "pid": 45063,
113
  "returncode": null
114
  },
115
  "4": {
116
+ "pid": 45064,
117
  "returncode": null
118
  },
119
  "5": {
120
+ "pid": 45065,
121
  "returncode": null
122
  }
123
  },
124
+ "batch_upload": {
125
+ "utc": "2026-10-25T08:29:44Z",
126
+ "state": "waiting_for_commit_budget",
127
+ "retry_at": 1792917013.6169364,
128
+ "pending": 1896,
129
+ "verified_receipts": 247
130
+ },
131
+ "archive_download_bytes": 574104526178
132
  }