faraway00 commited on
Commit
ca47166
·
verified ·
1 Parent(s): ea5ea77

Overlap CPU decode and encoding with exclusive GPU forwards; default download16 upload4; paired ten-clip benchmark

Browse files
overlap-benchmark.json ADDED
The diff for this file is too large to render. See raw diff
 
pipeline/README.md CHANGED
@@ -13,7 +13,7 @@
13
 
14
  ## 流程
15
 
16
- 异步 Range 下载(8 workers)→ 有界窗口(最多 30 候选)→ 全帧 core-v1 清洗 → 整段 DA3-LARGE 深度 → 异步上传(2 workers)→ 按提交 SHA 检查所有远端文件大小和 SHA256 → verified → 每 60 秒清理媒体。退出也清理一次。清洗拒绝的临时输入可立即删除,保留拒绝原因;上传失败保留临时数据并停止后续下载,重跑可重试。GPU 推理有进程文件锁,在单张 A40 上互斥。CPU 编码也在当前串行任务中完成;性能报告没有假称全部阶段均并行。
17
 
18
  scratch 默认上限 60 GiB,保留 25 GiB 系统余量,还为一个最坏情况窗口预留空间。支持 1 TB 磁盘但不依赖其全部可用。输入单视频上限 200 MiB,DA3 joint 上限 160 帧,RGB 解码上限 2 GiB。原始 Ditto 通常 101 帧。VFR/超限/异常样本记 error,不静默截断、补帧或改变帧率。上传故障不会以“清理”为由丢数据;需要排查后原命令重试。
19
 
@@ -60,7 +60,7 @@ $PY "$APP" --limit 0 --per-style 100 \
60
  --state /workspace/styleedit-streaming-20261024/state
61
  ```
62
 
63
- 生成 HF `metadata.jsonl` / dataset card / 风格清单 / 实测 benchmark / 脚本,以及只引用 HF 媒体的本地 `index.html` 对照页面。HF 元数据使用样本不可变 commit URL,三段视频分别有 Video 特征;原始数值用 NPZ。所有已上传媒体清理后,页面仍能从 HF 播放。后续新增样本完成后重跑 publish 刷新完整清单。
64
 
65
  ## 环境恢复
66
 
@@ -71,3 +71,11 @@ $PY "$APP" --limit 0 --per-style 100 \
71
  深度仅保存 depth.mp4:整段统一反深度映射、8 位量化、H.264 CRF 16 有损编码;不生成或上传 NPZ。
72
 
73
  编码默认 libx264 / veryfast / 8 线程 / CRF 16。真实首批样本(101 帧、1280×720、无 NPZ)两轮独立编码对比:旧 fast/2 线程后处理 3.50–3.65 秒,新 veryfast/8 线程 1.52–1.62 秒,NVENC p4/QP16 为 1.96–2.20 秒。后处理包含灰度转换、编码及帧时间戳验证;非全流程吞吐测试。新旧解码灰度相对编码前 8 bit 图像 MAE 为 0.282/0.253(0–255 尺度),仍是有损编码。详见 encoding-benchmark.json;当前记录细分各阶段耗时。
 
 
 
 
 
 
 
 
 
13
 
14
  ## 流程
15
 
16
+ 异步 Range 下载(16 workers)→ 有界窗口(最多 30 候选)→ 全帧 core-v1 清洗 → 整段 DA3-LARGE 深度 → 异步上传(4 workers)→ 按提交 SHA 检查所有远端文件大小和 SHA256 → verified → 每 60 秒清理媒体。退出也清理一次。清洗拒绝的临时输入可立即删除,保留拒绝原因;上传失败保留临时数据并停止后续下载,重跑可重试。GPU 推理有进程文件锁,在单张 A40 上互斥。默认启用 overlap-v1:清洗逐批预取下一批 CPU 解码/曝光检查;当前样本进入深度阶段后,开始清洗下一条。仅 GPU 前向计算持锁,CPU 解码、灰度转换、编码可与另一阶段交错。深度队列最多 2 条,上传/深度中的样本一起预占风格配额。加 `--serial-gpu-stages` 可恢复串行调度用于诊断。
17
 
18
  scratch 默认上限 60 GiB,保留 25 GiB 系统余量,还为一个最坏情况窗口预留空间。支持 1 TB 磁盘但不依赖其全部可用。输入单视频上限 200 MiB,DA3 joint 上限 160 帧,RGB 解码上限 2 GiB。原始 Ditto 通常 101 帧。VFR/超限/异常样本记 error,不静默截断、补帧或改变帧率。上传故障不会以“清理”为由丢数据;需要排查后原命令重试。
19
 
 
60
  --state /workspace/styleedit-streaming-20261024/state
61
  ```
62
 
63
+ 生成 HF `metadata.jsonl` / dataset card / 风格清单 / 实测 benchmark / 脚本,以及只引用 HF 媒体的本地 `index.html` 对照页面。HF 元数据使用样本不可变 commit URL,三段视频分别有 Video 特征;深度仅保存映射后的 depth.mp4,不保存 NPZ。所有已上传媒体清理后,页面仍能从 HF 播放。后续新增样本完成后重跑 publish 刷新完整清单。
64
 
65
  ## 环境恢复
66
 
 
71
  深度仅保存 depth.mp4:整段统一反深度映射、8 位量化、H.264 CRF 16 有损编码;不生成或上传 NPZ。
72
 
73
  编码默认 libx264 / veryfast / 8 线程 / CRF 16。真实首批样本(101 帧、1280×720、无 NPZ)两轮独立编码对比:旧 fast/2 线程后处理 3.50–3.65 秒,新 veryfast/8 线程 1.52–1.62 秒,NVENC p4/QP16 为 1.96–2.20 秒。后处理包含灰度转换、编码及帧时间戳验证;非全流程吞吐测试。新旧解码灰度相对编码前 8 bit 图像 MAE 为 0.282/0.253(0–255 尺度),仍是有损编码。详见 encoding-benchmark.json;当前记录细分各阶段耗时。
74
+
75
+ ## 流水线优化验证
76
+
77
+ `benchmark_overlap.py` 使用同一批 10 条已验证输入,重新运行清洗、DA3、编码、调度和本地输出校验,对比串行与默认 overlap-v1;两次都不复用评分结果。输入先从 HF 下载并核对 SHA256,计时不含下载;上传用本地完整文件/解码校验代替,因此结果是计算吞吐,不能直接作为含 HF 网络的全流程时间。报告为 overlap-benchmark.json。校验两版筛选决定、全帧曝光结果、帧数、逐帧 DINO 距离和解码深度视频摘要。`verify_overlap.py` 检查风格配额预占、异步失败保留文件、只清理 verified 数据。
78
+
79
+ 网络默认下载并发 16、上传并发 4,可用 `--download-workers` / `--upload-workers` 覆盖。有界预取窗口仍为 30,磁盘容量和校验清理规则不变。上传并发设置控制同时处理样本的线程数;底层 HF 客户端可能另有文件分片请求并发。当前吞吐基准固定使用 8/2 且不含 HF 网络,因此不用于宣称网络并发的实测收益。
80
+
81
+ 2026-10-24 单张 A40 同 10 条实测:串行总耗时 193.43 秒、overlap-v1 153.75 秒(含模型启动/本地输出校验,不含网络),缩短 20.5%,吞吐提高 25.8%;排除模型启动后的处理时间 181.20 → 140.31 秒,吞吐提高 29.1%。全部筛选决定、全帧曝光、逐帧 DINO 分数完全相同,深度视频解码 SHA256 也全部一致。仅一次成对整批测试;网络并发改动没有包含在该收益中。
pipeline/benchmark_overlap.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Paired ten-clip serial/overlapped benchmark using the real Run scheduler.
2
+ Fresh HF media fetched once, verified against receipts. No HF sample changes.
3
+ Temporary inputs/outputs deleted on exit; reports only persist. No NPZ output.
4
+ """
5
+ import concurrent.futures as cf,copy,json,os,shutil,subprocess,tempfile,threading,time
6
+ from pathlib import Path
7
+ from types import SimpleNamespace
8
+ import requests
9
+ import pipeline
10
+ from common import *
11
+
12
+ def main():
13
+ scratch=Path(tempfile.mkdtemp(prefix='styleedit-throughput-',dir='/opt'));reportpath=BASE/'overlap-benchmark.json'
14
+ db=pipeline.sqlite3.connect('/workspace/styleedit-streaming-20261024/state/jobs.sqlite')
15
+ receipts=[json.loads(s) for (s,) in db.execute("SELECT record FROM jobs WHERE status='verified' ORDER BY id LIMIT 10")];db.close()
16
+ assert len(receipts)==10
17
+ try:
18
+ media=scratch/'inputs';media.mkdir();rows=[]
19
+ def download(item):
20
+ v,side=item;r=v['record'];name={'source':'source.mp4','edited':'edited.mp4'}[side];p=media/(r['id']+'-'+name)
21
+ response=requests.get(f"https://huggingface.co/datasets/{DEST}/resolve/{v['commit']}/data/{r['style_id']}/{r['id']}/{name}",timeout=120);response.raise_for_status();p.write_bytes(response.content)
22
+ assert sha(p)==r['files'][name]['sha256'];return p
23
+ with cf.ThreadPoolExecutor(8) as pool:list(pool.map(download,[(v,s) for v in receipts for s in ['source','edited']]))
24
+ for v in receipts:
25
+ r=v['record'];rows.append({k:r[k] for k in ['id','style_id','style_label','instruction','source_path','edited_path']}|{'expected_sha256':{s:r['files'][n]['sha256'] for s,n in [('source','source.mp4'),('edited','edited.mp4')]}})
26
+ plan=scratch/'plan.json';atomic(plan,rows)
27
+ def local_download(row,side,dst,index):shutil.copyfile(media/(row['id']+'-'+side+'.mp4'),dst)
28
+ pipeline.indexed_download=local_download
29
+ reports=[]
30
+ class TimedWorker(pipeline.Worker):
31
+ def __init__(self,mode,logdir,overlap=True):super().__init__(mode,logdir,overlap);self.mode=mode
32
+ def call(self,job):
33
+ t=time.monotonic();value=super().call(job);events.append({'mode':self.mode,'id':job['row']['id'],'started':t-clock,'ended':time.monotonic()-clock})
34
+ if self.mode=='filter':filter_results[job['row']['id']]=value
35
+ return value
36
+ pipeline.Worker=TimedWorker
37
+ for serial in [True,False]:
38
+ name='serial' if serial else 'overlap';state=scratch/(name+'-state');work=scratch/(name+'-work');events=[];filter_results={};decoded_hashes={};samples=[];done=threading.Event()
39
+ a=SimpleNamespace(state=str(state),scratch=str(work),plan=str(plan),repo=DEST,limit=10,per_style=100,seed_ranges=False,window=10,download_workers=8,upload_workers=2,cleanup_seconds=60,scratch_gib=60,reserve_gib=25,index_state='',serial_gpu_stages=serial)
40
+ run=pipeline.Run(a)
41
+ def local_ship(row,d,filtered,depth):
42
+ assert not any(d.glob('*.npz'))
43
+ for filename in ['source.mp4','edited.mp4','depth.mp4','depth.json','filter.json']:assert (d/filename).is_file()
44
+ check=ffprobe(d/'depth.mp4');assert check['frames']==depth['joint_frames']
45
+ # Stream a decoded checksum rather than retaining depth arrays or videos.
46
+ digest=subprocess.check_output(['ffmpeg','-v','error','-threads','2','-i',str(d/'depth.mp4'),'-f','hash','-hash','sha256','-'],text=True).strip()
47
+ decoded_hashes[row['id']]=digest
48
+ receipt={'record':{'id':row['id']},'verification':'LOCAL BENCHMARK ONLY; no HF commit'}
49
+ atomic(state/'receipts'/(row['id']+'.json'),receipt);run.record(row,'verified',receipt,time.time());return receipt
50
+ run.ship=local_ship
51
+ def monitor():
52
+ while not done.is_set():
53
+ try:
54
+ fields=subprocess.check_output(['nvidia-smi','--query-gpu=memory.used,utilization.gpu','--format=csv,noheader,nounits'],text=True).strip().split(',');samples.append({'seconds':time.monotonic()-clock,'memory_mib':int(fields[0]),'gpu_util_percent':int(fields[1])})
55
+ except Exception:pass
56
+ done.wait(1)
57
+ clock=time.monotonic();thread=threading.Thread(target=monitor);thread.start()
58
+ try:rc=run.run()
59
+ finally:done.set();thread.join()
60
+ assert rc==0,run.metrics['errors'];run.db.close();run.lock.close()
61
+ first=min(e['started'] for e in events);last=max(e['ended'] for e in events)
62
+ item={'mode':name,'wall_seconds':run.metrics['wall_seconds'],'active_processing_seconds':last-first,'events':events,'filter_results':filter_results,'depth_results':run.metrics['depth'],'decoded_depth_sha256':decoded_hashes,'gpu_samples':samples,'metrics':run.metrics}
63
+ reports.append(item);atomic(reportpath,{'scope':'same ten fresh-HF verified input pairs; compute/scheduler/cleanup benchmark; downloads excluded, HF uploads replaced by local file/checksum validation; no metric caches','runs':reports});print('BENCH_STAGE_COMPLETE',name,item['wall_seconds'],last-first,flush=True)
64
+ base,opt=reports;comparison={'same_status':True,'same_exposure':True,'same_frame_counts':True,'max_per_frame_distance_difference':0.,'depth_video_decoded_exact_match':base['decoded_depth_sha256']==opt['decoded_depth_sha256']}
65
+ for jid,a in base['filter_results'].items():
66
+ b=opt['filter_results'][jid];comparison['same_status']&=a['status']==b['status'];comparison['same_exposure']&=a['exposure']==b['exposure'];comparison['same_frame_counts']&=a['decoded_frames']==b['decoded_frames'];comparison['max_per_frame_distance_difference']=max(comparison['max_per_frame_distance_difference'],max(abs(x-y) for x,y in zip(a['per_frame_distance'],b['per_frame_distance'])))
67
+ comparison['active_speedup']=base['active_processing_seconds']/opt['active_processing_seconds'];comparison['wall_speedup']=base['wall_seconds']/opt['wall_seconds']
68
+ report=json.loads(reportpath.read_text());report['comparison']=comparison;atomic(reportpath,report);assert comparison['same_status'] and comparison['same_exposure'] and comparison['same_frame_counts'] and comparison['max_per_frame_distance_difference']<=1e-5
69
+ print('COMPARISON',json.dumps(comparison),flush=True)
70
+ finally:shutil.rmtree(scratch)
71
+ if __name__=='__main__':main()
pipeline/pipeline.py CHANGED
@@ -5,9 +5,9 @@ from common import *
5
  from streaming import seed_download,indexed_download,build_index
6
 
7
  class Worker:
8
- def __init__(self,mode,logdir):
9
  env='/opt/goku-dinov3-eval-env/bin/python' if mode=='filter' else '/opt/da3-depth-env/bin/python'
10
- self.log=open(logdir/(mode+'.log'),'a');self.p=subprocess.Popen([env,str(BASE/'workers.py'),mode],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=self.log,text=True,bufsize=1)
11
  line=self.p.stdout.readline()
12
  if not line:raise RuntimeError(mode+' worker failed; see log')
13
  self.ready=json.loads(line);print('WORKER_READY',self.ready,flush=True)
@@ -83,6 +83,14 @@ class Run:
83
  except Exception:
84
  if attempt==4:raise
85
  time.sleep(min(30,2**attempt))
 
 
 
 
 
 
 
 
86
  def run(self):
87
  a=self.a;allrows=json.loads(Path(a.plan).read_text());existing=self.counts();done_sources=set()
88
  if not self.space():raise RuntimeError('Insufficient scratch capacity/free space for a bounded download window')
@@ -96,12 +104,12 @@ class Run:
96
  if previous and previous[0] in ('verified','reject'):continue
97
  unique.add(key);rows.append(row)
98
  cleaner=threading.Thread(target=self.cleanup,daemon=True);cleaner.start()
99
- filterworker=None;depthworker=None
100
  try:
101
  # Download bounded windows. Network workers never run arbitrarily far ahead.
102
  with cf.ThreadPoolExecutor(a.download_workers) as pool:
103
  loads=cf.ThreadPoolExecutor(2)
104
- ff=loads.submit(Worker,'filter',self.state);df=loads.submit(Worker,'depth',self.state)
105
  for first in range(0,len(rows),a.window):
106
  for uf in self.uploads:
107
  if uf.done() and uf.exception() is not None:raise RuntimeError('Upload failed; retained local media and stopped downloads: '+str(uf.exception()))
@@ -128,10 +136,12 @@ class Run:
128
  loc=row['locators'][side];pending[row['id'],side]=futures[(loc['category'],loc['kind'],loc['start'],loc['length'])]
129
  filterworker=ff.result();depthworker=df.result()
130
  for row in batch:
 
131
  if a.limit and accepted>=a.limit:break
132
- sid=row['style_id'];d=self.scratch/row['id'];counts=self.counts()
133
  # Include current in-flight uploads to reserve exact per-style quota.
134
- with self.db_lock:reserved=self.db.execute("SELECT count(*) FROM jobs WHERE style_id=? AND status IN ('uploading','processed')",(sid,)).fetchone()[0]
 
135
  if counts.get(sid,0)+reserved>=a.per_style:continue
136
  try:
137
  ts=time.monotonic()
@@ -143,10 +153,14 @@ class Run:
143
  if f['status']=='reject':
144
  atomic(self.state/'rejects'/(row['id']+'.json'),f);self.record(row,'reject',f);shutil.rmtree(d);continue
145
  if f['status']!='keep':raise RuntimeError(f.get('error','Filter failed'))
146
- self.record(row,'depth');dep=depthworker.call({'row':row,'dir':str(d)});self.metrics['depth'].append(dep);print('DEPTH',row['id'],round(dep['total_seconds'],2),flush=True)
147
- self.record(row,'uploading');future=self.upload.submit(self.ship,row,d,f,dep);self.uploads.append(future);accepted+=1
 
 
148
  except Exception as e:
149
  errors+=1;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)
 
 
150
  # Await this download window before discarding unselected scratch members.
151
  for future in set(pending.values()):
152
  try:r=future.result()
@@ -163,10 +177,12 @@ class Run:
163
  try:future.result()
164
  except Exception as e:self.metrics['errors'].append({'upload_error':str(e)});print('UPLOAD_ERROR',type(e).__name__,str(e)[:200],flush=True)
165
  finally:
 
 
166
  if filterworker:filterworker.close()
167
  if depthworker:depthworker.close()
168
  self.stop.set();cleaner.join(timeout=5);self.clean_once()
169
- self.metrics.update(run_id=self.runid,wall_seconds=time.monotonic()-self.started,accepted_for_upload=accepted,verified_counts=self.counts(),new_verified=sum(f.done() and f.exception() is None for f in self.uploads),gpu=(filterworker.ready['gpu'] if filterworker else 'unavailable'),model_startup={'filter':filterworker.ready if filterworker else None,'depth':depthworker.ready if depthworker else None},scope='pilot seeded fresh HF ranges' if a.seed_ranges else 'exact indexed full corpus')
170
  with self.db_lock:self.metrics['state_counts']=dict(self.db.execute('SELECT status,count(*) FROM jobs GROUP BY status'));self.metrics['verified_not_cleaned']=self.db.execute("SELECT count(*) FROM jobs WHERE status='verified' AND cleaned=0").fetchone()[0]
171
  atomic(self.state/('benchmark-'+self.runid+'.json'),self.metrics);atomic(self.state/'summary.json',self.metrics)
172
  print('RUN_COMPLETE',json.dumps({k:v for k,v in self.metrics.items() if k not in ['filter','depth','download_groups']}),flush=True)
@@ -176,7 +192,7 @@ class Run:
176
  return 0 if success and not self.metrics['errors'] else 2
177
 
178
  def main():
179
- p=argparse.ArgumentParser();p.add_argument('--index',choices=['source','global_style1','global_style2']);p.add_argument('--index-state',default='/workspace/styleedit-streaming-20261024/index');p.add_argument('--plan',default=str(BASE/'candidates.json'));p.add_argument('--state',default='/workspace/styleedit-streaming-20261024/state');p.add_argument('--scratch',default='/opt/styleedit-scratch');p.add_argument('--repo',default=DEST);p.add_argument('--limit',type=int,default=10);p.add_argument('--per-style',type=int,default=100);p.add_argument('--seed-ranges',action='store_true');p.add_argument('--window',type=int,default=30);p.add_argument('--download-workers',type=int,default=8);p.add_argument('--upload-workers',type=int,default=2);p.add_argument('--cleanup-seconds',type=int,default=60);p.add_argument('--scratch-gib',type=int,default=60);p.add_argument('--reserve-gib',type=int,default=25);a=p.parse_args()
180
  if a.index:build_index(a.index,a.index_state);return 0
181
  if not a.seed_ranges:
182
  dbpath=Path(a.index_state)/'catalog.sqlite'
 
5
  from streaming import seed_download,indexed_download,build_index
6
 
7
  class Worker:
8
+ def __init__(self,mode,logdir,overlap=True):
9
  env='/opt/goku-dinov3-eval-env/bin/python' if mode=='filter' else '/opt/da3-depth-env/bin/python'
10
+ self.log=open(logdir/(mode+'.log'),'a');self.p=subprocess.Popen([env,str(BASE/'workers.py'),mode],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=self.log,text=True,bufsize=1,env={**os.environ,'STYLEEDIT_OVERLAP':'1' if overlap else '0'})
11
  line=self.p.stdout.readline()
12
  if not line:raise RuntimeError(mode+' worker failed; see log')
13
  self.ready=json.loads(line);print('WORKER_READY',self.ready,flush=True)
 
83
  except Exception:
84
  if attempt==4:raise
85
  time.sleep(min(30,2**attempt))
86
+ def process_depth(self,row,d,filtered,worker):
87
+ try:
88
+ dep=worker.call({'row':row,'dir':str(d)});self.metrics['depth'].append(dep);print('DEPTH',row['id'],round(dep['total_seconds'],2),flush=True)
89
+ self.record(row,'uploading');future=self.upload.submit(self.ship,row,d,filtered,dep);self.uploads.append(future)
90
+ return True
91
+ except Exception as e:
92
+ 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)
93
+ return False
94
  def run(self):
95
  a=self.a;allrows=json.loads(Path(a.plan).read_text());existing=self.counts();done_sources=set()
96
  if not self.space():raise RuntimeError('Insufficient scratch capacity/free space for a bounded download window')
 
104
  if previous and previous[0] in ('verified','reject'):continue
105
  unique.add(key);rows.append(row)
106
  cleaner=threading.Thread(target=self.cleanup,daemon=True);cleaner.start()
107
+ filterworker=None;depthworker=None;depth_pool=cf.ThreadPoolExecutor(1);depth_pending=[]
108
  try:
109
  # Download bounded windows. Network workers never run arbitrarily far ahead.
110
  with cf.ThreadPoolExecutor(a.download_workers) as pool:
111
  loads=cf.ThreadPoolExecutor(2)
112
+ ff=loads.submit(Worker,'filter',self.state,not a.serial_gpu_stages);df=loads.submit(Worker,'depth',self.state,not a.serial_gpu_stages)
113
  for first in range(0,len(rows),a.window):
114
  for uf in self.uploads:
115
  if uf.done() and uf.exception() is not None:raise RuntimeError('Upload failed; retained local media and stopped downloads: '+str(uf.exception()))
 
136
  loc=row['locators'][side];pending[row['id'],side]=futures[(loc['category'],loc['kind'],loc['start'],loc['length'])]
137
  filterworker=ff.result();depthworker=df.result()
138
  for row in batch:
139
+ while len(depth_pending)>=2:depth_pending.pop(0).result()
140
  if a.limit and accepted>=a.limit:break
141
+ sid=row['style_id'];d=self.scratch/row['id']
142
  # Include current in-flight uploads to reserve exact per-style quota.
143
+ with self.db_lock:
144
+ counts=self.counts();reserved=self.db.execute("SELECT count(*) FROM jobs WHERE style_id=? AND status IN ('depth','uploading','processed')",(sid,)).fetchone()[0]
145
  if counts.get(sid,0)+reserved>=a.per_style:continue
146
  try:
147
  ts=time.monotonic()
 
153
  if f['status']=='reject':
154
  atomic(self.state/'rejects'/(row['id']+'.json'),f);self.record(row,'reject',f);shutil.rmtree(d);continue
155
  if f['status']!='keep':raise RuntimeError(f.get('error','Filter failed'))
156
+ self.record(row,'depth')
157
+ if a.serial_gpu_stages:self.process_depth(row,d,f,depthworker)
158
+ else:depth_pending.append(depth_pool.submit(self.process_depth,row,d,f,depthworker))
159
+ accepted+=1
160
  except Exception as e:
161
  errors+=1;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)
162
+ for future in depth_pending:future.result()
163
+ depth_pending.clear()
164
  # Await this download window before discarding unselected scratch members.
165
  for future in set(pending.values()):
166
  try:r=future.result()
 
177
  try:future.result()
178
  except Exception as e:self.metrics['errors'].append({'upload_error':str(e)});print('UPLOAD_ERROR',type(e).__name__,str(e)[:200],flush=True)
179
  finally:
180
+ depth_pool.shutdown(wait=True)
181
+ self.upload.shutdown(wait=True)
182
  if filterworker:filterworker.close()
183
  if depthworker:depthworker.close()
184
  self.stop.set();cleaner.join(timeout=5);self.clean_once()
185
+ self.metrics.update(run_id=self.runid,wall_seconds=time.monotonic()-self.started,accepted_for_upload=accepted,verified_counts=self.counts(),new_verified=sum(f.done() and f.exception() is None for f in self.uploads),gpu=(filterworker.ready['gpu'] if filterworker else 'unavailable'),model_startup={'filter':filterworker.ready if filterworker else None,'depth':depthworker.ready if depthworker else None},execution_profile='serial' if a.serial_gpu_stages else 'overlap-v1',scope='pilot seeded fresh HF ranges' if a.seed_ranges else 'exact indexed full corpus')
186
  with self.db_lock:self.metrics['state_counts']=dict(self.db.execute('SELECT status,count(*) FROM jobs GROUP BY status'));self.metrics['verified_not_cleaned']=self.db.execute("SELECT count(*) FROM jobs WHERE status='verified' AND cleaned=0").fetchone()[0]
187
  atomic(self.state/('benchmark-'+self.runid+'.json'),self.metrics);atomic(self.state/'summary.json',self.metrics)
188
  print('RUN_COMPLETE',json.dumps({k:v for k,v in self.metrics.items() if k not in ['filter','depth','download_groups']}),flush=True)
 
192
  return 0 if success and not self.metrics['errors'] else 2
193
 
194
  def main():
195
+ p=argparse.ArgumentParser();p.add_argument('--index',choices=['source','global_style1','global_style2']);p.add_argument('--index-state',default='/workspace/styleedit-streaming-20261024/index');p.add_argument('--plan',default=str(BASE/'candidates.json'));p.add_argument('--state',default='/workspace/styleedit-streaming-20261024/state');p.add_argument('--scratch',default='/opt/styleedit-scratch');p.add_argument('--repo',default=DEST);p.add_argument('--limit',type=int,default=10);p.add_argument('--per-style',type=int,default=100);p.add_argument('--seed-ranges',action='store_true');p.add_argument('--serial-gpu-stages',action='store_true',help='Diagnostic baseline: serial stages and original core-v1 loop');p.add_argument('--window',type=int,default=30);p.add_argument('--download-workers',type=int,default=16);p.add_argument('--upload-workers',type=int,default=4);p.add_argument('--cleanup-seconds',type=int,default=60);p.add_argument('--scratch-gib',type=int,default=60);p.add_argument('--reserve-gib',type=int,default=25);a=p.parse_args()
196
  if a.index:build_index(a.index,a.index_state);return 0
197
  if not a.seed_ranges:
198
  dbpath=Path(a.index_state)/'catalog.sqlite'
pipeline/pipelined_filter.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Core-v1 arithmetic and checks with bounded CPU prefetch and GPU-only locking."""
2
+ import contextlib,fcntl,math,time,traceback
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ import numpy as np
5
+ from run_pipeline import final_status
6
+ from curation.filter import Reader,probe,alignment
7
+ from curation.pair_checks import FrameCountMismatch
8
+ from curation.exposure import Rules,frame_metric,aggregate
9
+
10
+ @contextlib.contextmanager
11
+ def gpu_section(lock):
12
+ fcntl.flock(lock,fcntl.LOCK_EX)
13
+ try:yield
14
+ finally:fcntl.flock(lock,fcntl.LOCK_UN)
15
+
16
+ def pair_run(row,local_paths,encoder,cfg,lock):
17
+ import torch
18
+ import torch.nn.functional as F
19
+ from curation.eden_encoder import encode_proxy_dino
20
+ start=time.monotonic();timing={k:0. for k in ['probe_seconds','decode_wait_seconds','exposure_seconds','dino_seconds','gpu_lock_wait_seconds']}
21
+ result=dict(row);metas=[];readers=[];exp=[[],[]];distances=[];producer=None
22
+ try:
23
+ t=time.monotonic();metas=[probe(p) for p in local_paths];timing['probe_seconds']=time.monotonic()-t
24
+ integrity='keep';reasons=[]
25
+ try:alignment(*metas)
26
+ except FrameCountMismatch:integrity='reject';reasons.append('frame_count_mismatch')
27
+ except ValueError as e:
28
+ if 'FPS mismatch' in str(e):reason='fps_mismatch'
29
+ elif 'timestamps are not aligned' in str(e):reason='timestamp_mismatch'
30
+ else:raise
31
+ integrity='reject';reasons.append(reason)
32
+ result.update(integrity_status=integrity,reject_reasons=reasons,video_metadata=metas)
33
+ readers=[Reader(p,m) for p,m in zip(local_paths,metas)];rules=Rules(**cfg['exposure']);batch=cfg['batch_frames']
34
+ def prepare(first):
35
+ t=time.monotonic();arrays=[r.read(min(batch,m['frames']-first)) if first<m['frames'] else None for r,m in zip(readers,metas)];decode=time.monotonic()-t
36
+ t=time.monotonic();stats=[[],[]]
37
+ for side,a in enumerate(arrays):
38
+ if a is not None:
39
+ for offset,rgb in enumerate(a):
40
+ fm=frame_metric(rgb,rules);fm.update(index=first+offset,pts=metas[side]['pts'][first+offset]);stats[side].append(fm)
41
+ return arrays,stats,decode,time.monotonic()-t
42
+ producer=ThreadPoolExecutor(1);firsts=list(range(0,max(m['frames'] for m in metas),batch));pending=producer.submit(prepare,firsts[0])
43
+ with torch.inference_mode():
44
+ for index,first in enumerate(firsts):
45
+ arrays,stats,decode,exposure=pending.result();timing['decode_wait_seconds']+=decode;timing['exposure_seconds']+=exposure
46
+ for side in range(2):exp[side].extend(stats[side])
47
+ if index+1<len(firsts):pending=producer.submit(prepare,firsts[index+1])
48
+ if integrity=='keep':
49
+ t=time.monotonic()
50
+ with gpu_section(lock):
51
+ timing['gpu_lock_wait_seconds']+=time.monotonic()-t
52
+ torch.cuda.synchronize();t=time.monotonic();n=len(arrays[0])
53
+ images=[torch.from_numpy(a).permute(0,3,1,2).to('cuda',dtype=torch.float32)/255 for a in arrays]
54
+ if images[0].shape[-2:]!=images[1].shape[-2:]:images=[F.interpolate(x,size=(480,832),mode='bilinear',align_corners=False,antialias=True) for x in images]
55
+ y=encode_proxy_dino(encoder,torch.cat(images),image_size=(480,832),resize_mode='bilinear',projection_autocast=True)
56
+ z=F.normalize(y.squeeze(2).permute(0,2,3,1).reshape(2*n,1560,1024).float(),dim=-1)
57
+ distances.extend((1-(z[:n]*z[n:]).sum(-1).clamp(-1,1)).mean(-1).cpu().tolist())
58
+ torch.cuda.synchronize();timing['dino_seconds']+=time.monotonic()-t
59
+ producer.shutdown();producer=None
60
+ t=time.monotonic()
61
+ for reader in readers:reader.finish()
62
+ timing['decode_wait_seconds']+=time.monotonic()-t
63
+ exposure={name:{**aggregate(fs,rules),'per_frame':fs} for name,fs in zip(['source','edited'],exp)}
64
+ exposure_status='reject' if any(x['status']=='reject' for x in exposure.values()) else 'keep'
65
+ result.update(exposure=exposure,exposure_status=exposure_status,decoded_frames=sum(len(fs) for fs in exp),integrity_full_decode_passed=True)
66
+ if integrity=='keep':
67
+ d=float(np.mean(distances))
68
+ if not math.isfinite(d):raise ValueError('Nonfinite DINO distance')
69
+ assert len(distances)==metas[0]['frames'];ds='reject' if d>cfg['distance_threshold'] else 'keep'
70
+ result.update(distance=d,per_frame_distance=distances,dino_status=ds,dino_scored_frames=len(distances))
71
+ if ds=='reject':reasons.append('eden_distance_above_threshold')
72
+ else:result.update(dino_status='skipped',dino_skip_reason='pair_not_aligned',dino_scored_frames=0)
73
+ for side,m in exposure.items():
74
+ if m['status']=='reject':reasons.append(side+'_exposure')
75
+ result['status']=final_status(integrity,result['dino_status'],exposure_status)
76
+ except Exception as exc:result.update(status='error',error=type(exc).__name__+': '+str(exc),traceback=traceback.format_exc())
77
+ finally:
78
+ if producer:producer.shutdown(wait=True,cancel_futures=True)
79
+ for reader in readers:reader.close()
80
+ result['timing']={**timing,'pair_seconds':time.monotonic()-start};result['metric_cache_hit']=False
81
+ result['execution_profile']='overlap-v1; core-v1 math, all frames/pixels, batch4; CPU prefetch1; GPU-exclusive forwards'
82
+ return result
pipeline/verify_overlap.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exercise production scheduling with controlled workers, quotas and upload failure."""
2
+ import json,tempfile,time
3
+ from pathlib import Path
4
+ from types import SimpleNamespace
5
+ import pipeline
6
+ from common import atomic
7
+
8
+ class FakeWorker:
9
+ def __init__(self,mode,logdir,overlap=True):self.mode=mode;self.ready={'gpu':'test','load_seconds':0};self.active=False
10
+ def call(self,job):
11
+ assert not self.active,'Concurrent RPCs to the same worker';self.active=True
12
+ try:
13
+ time.sleep(.01)
14
+ if self.mode=='filter':return {'status':'keep','distance':0.,'timing':{'pair_seconds':.01}}
15
+ atomic(Path(job['dir'])/'depth.json',{'joint_frames':1});return {'joint_frames':1,'total_seconds':.01}
16
+ finally:self.active=False
17
+ def close(self):pass
18
+
19
+ def main():
20
+ pipeline.Worker=FakeWorker
21
+ def download(row,side,dst,index):Path(dst).write_bytes(b'input')
22
+ pipeline.indexed_download=download
23
+ with tempfile.TemporaryDirectory() as temp:
24
+ root=Path(temp)
25
+ for fail in [False,True]:
26
+ base=root/str(fail);base.mkdir();rows=[{'id':str(i),'style_id':'a' if i<6 else 'b','style_label':'test','instruction':'test','source_path':str(i),'edited_path':'e'+str(i)} for i in range(10)];atomic(base/'plan.json',rows)
27
+ a=SimpleNamespace(state=str(base/'state'),scratch=str(base/'scratch'),plan=str(base/'plan.json'),repo='',limit=0,per_style=2,seed_ranges=False,window=10,download_workers=16,upload_workers=4,cleanup_seconds=60,scratch_gib=1,reserve_gib=0,index_state='',serial_gpu_stages=False)
28
+ run=pipeline.Run(a);run.space=lambda:True
29
+ def ship(row,d,filtered,depth):
30
+ if fail:raise RuntimeError('intentional upload failure')
31
+ run.record(row,'verified',{'record':row},time.time());return True
32
+ run.ship=ship;code=run.run()
33
+ if not fail:
34
+ assert code==0 and run.counts()=={'a':2,'b':2},(code,run.counts())
35
+ assert not any((base/'scratch').rglob('*.mp4'))
36
+ print('PASS bounded asynchronous scheduling, exact per-style reservations, verified cleanup')
37
+ else:
38
+ assert code==2 and not run.counts();assert len(list((base/'scratch').glob('*/source.mp4')))==4
39
+ print('PASS failed asynchronous uploads preserve media and do not count toward quotas')
40
+ run.db.close();run.lock.close()
41
+ if __name__=='__main__':main()
pipeline/workers.py CHANGED
@@ -5,6 +5,7 @@ import fcntl,json,sys,time,traceback,contextlib,subprocess
5
  from pathlib import Path
6
  from common import *
7
  MODE=sys.argv[1]
 
8
  # Model libraries print progress to stdout. Keep the RPC stream private.
9
  RPC=sys.stdout;sys.stdout=sys.stderr
10
  import numpy as np,torch
@@ -16,6 +17,7 @@ t=time.monotonic()
16
  if MODE=='filter':
17
  sys.path.insert(0,str(CORE));sys.path.insert(0,str(CORE/'code'))
18
  from run_pipeline import pair_run
 
19
  from curation.eden_encoder import create_checkpoint_dinov3_encoder
20
  from curation.filter import weights_ready
21
  w=CORE/'weights/vision-encoder';weights_ready(w)
@@ -36,8 +38,12 @@ def depth(job):
36
  t=time.monotonic();raw=subprocess.check_output(['ffmpeg','-v','error','-threads','2','-i',str(d/'source.mp4'),'-f','rawvideo','-pix_fmt','rgb24','pipe:1']);rgb=np.frombuffer(raw,np.uint8).reshape(-1,h,w,3)
37
  assert len(rgb)==n;decode_seconds=time.monotonic()-t
38
  torch.cuda.reset_peak_memory_stats();torch.cuda.synchronize();t=time.monotonic()
39
- with torch.inference_mode():p=model.inference(image=[Image.fromarray(x) for x in rgb],process_res=504,process_res_method='upper_bound_resize',export_dir=None)
40
- torch.cuda.synchronize();inference_seconds=time.monotonic()-t
 
 
 
 
41
  dep=p.depth.astype(np.float32)
42
  if len(dep)!=n or not np.isfinite(dep).all() or np.any(dep<=0):raise ValueError('Invalid DA3 depth')
43
  t=time.monotonic()
@@ -63,8 +69,11 @@ for line in sys.stdin:
63
  try:
64
  job=json.loads(line)
65
  with contextlib.ExitStack() as stack:
66
- fcntl.flock(lock,fcntl.LOCK_EX);stack.callback(fcntl.flock,lock,fcntl.LOCK_UN)
67
- if MODE=='filter':out=pair_run(job['row'],[job['dir']+'/'+s+'.mp4' for s in ['source','edited']],model,cfg)
 
 
 
68
  else:out=depth(job)
69
  reply={'ok':True,'result':out}
70
  except Exception as e:
 
5
  from pathlib import Path
6
  from common import *
7
  MODE=sys.argv[1]
8
+ OVERLAP=os.environ.get('STYLEEDIT_OVERLAP','1')=='1'
9
  # Model libraries print progress to stdout. Keep the RPC stream private.
10
  RPC=sys.stdout;sys.stdout=sys.stderr
11
  import numpy as np,torch
 
17
  if MODE=='filter':
18
  sys.path.insert(0,str(CORE));sys.path.insert(0,str(CORE/'code'))
19
  from run_pipeline import pair_run
20
+ from pipelined_filter import pair_run as overlapped_pair_run,gpu_section
21
  from curation.eden_encoder import create_checkpoint_dinov3_encoder
22
  from curation.filter import weights_ready
23
  w=CORE/'weights/vision-encoder';weights_ready(w)
 
38
  t=time.monotonic();raw=subprocess.check_output(['ffmpeg','-v','error','-threads','2','-i',str(d/'source.mp4'),'-f','rawvideo','-pix_fmt','rgb24','pipe:1']);rgb=np.frombuffer(raw,np.uint8).reshape(-1,h,w,3)
39
  assert len(rgb)==n;decode_seconds=time.monotonic()-t
40
  torch.cuda.reset_peak_memory_stats();torch.cuda.synchronize();t=time.monotonic()
41
+ with contextlib.ExitStack() as gpu_stack:
42
+ if OVERLAP:
43
+ fcntl.flock(lock,fcntl.LOCK_EX);gpu_stack.callback(fcntl.flock,lock,fcntl.LOCK_UN)
44
+ with torch.inference_mode():p=model.inference(image=[Image.fromarray(x) for x in rgb],process_res=504,process_res_method='upper_bound_resize',export_dir=None)
45
+ torch.cuda.synchronize()
46
+ inference_seconds=time.monotonic()-t
47
  dep=p.depth.astype(np.float32)
48
  if len(dep)!=n or not np.isfinite(dep).all() or np.any(dep<=0):raise ValueError('Invalid DA3 depth')
49
  t=time.monotonic()
 
69
  try:
70
  job=json.loads(line)
71
  with contextlib.ExitStack() as stack:
72
+ if not OVERLAP:
73
+ fcntl.flock(lock,fcntl.LOCK_EX);stack.callback(fcntl.flock,lock,fcntl.LOCK_UN)
74
+ if MODE=='filter':
75
+ args=(job['row'],[job['dir']+'/'+s+'.mp4' for s in ['source','edited']],model,cfg)
76
+ out=overlapped_pair_run(*args,lock) if OVERLAP else pair_run(*args)
77
  else:out=depth(job)
78
  reply={'ok':True,'result':out}
79
  except Exception as e: