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

Remove DA3 depth host roundtrip and unused outputs; encode GPU frames directly with NVENC; record real clip parity and ten-pair throughput

Browse files
device-depth-quality.json ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source_id": "0ebf25f7eb89320b6371d5ff",
3
+ "frames": 101,
4
+ "depth_only_forward_bit_exact": true,
5
+ "percentile_max_difference": 0.0,
6
+ "CUDA_vs_CPU_precodec_gray_max_difference": 1,
7
+ "CUDA_vs_CPU_precodec_gray_changed_fraction": 9.959003712871288e-06,
8
+ "NVENC_vs_CPU_precodec_gray_mae_8bit": 0.25091803398462803,
9
+ "NVENC_vs_CPU_precodec_gray_rmse_8bit": 0.5408237125210781,
10
+ "depth": {
11
+ "model": "depth-anything/DA3-LARGE",
12
+ "model_provenance": {
13
+ "config_sha256": "744dcaf53859490ed92fc6cb98d68d3daf624b8c54533aaf604bdb53f06321f5",
14
+ "weights_sha256": "eaf2ae06df55889ad23eb245c82e2dd2a30c0cbf7e3d873a118fa5ed27a3e421",
15
+ "code_commit": "3d835ec1a5802d64a8b8b15f817a1ab54809bfe4"
16
+ },
17
+ "process_res": 504,
18
+ "joint_frames": 101,
19
+ "source_width": 1280,
20
+ "source_height": 720,
21
+ "raw_depth_shape": [
22
+ 101,
23
+ 280,
24
+ 504
25
+ ],
26
+ "stored_depth": "depth.mp4 only",
27
+ "units": "relative_depth_not_meters",
28
+ "video_mapping": "inverse depth, per-video fixed percentile 0.5/99.5; near bright",
29
+ "inverse_depth_clip": [
30
+ 0.6175584650039673,
31
+ 1.4080844694375985
32
+ ],
33
+ "decode_seconds": 0.30635125300614163,
34
+ "inference_seconds": 5.309842279995792,
35
+ "video_backend": "cuda",
36
+ "depth_conversion": "GPU resident depth -> CUDA FP32 mapping -> NVENC device input, chunk8",
37
+ "encoding": {
38
+ "codec": "h264_nvenc",
39
+ "api": "PyNvVideoCodec 2.2.3 device input",
40
+ "preset": "p4",
41
+ "rate_control": "constqp",
42
+ "qp": 16,
43
+ "device_stats": {
44
+ "conversion_seconds": 0.020730131946038455,
45
+ "encoder_submit_seconds": 0.09878889191895723,
46
+ "encode_mux_seconds": 0.49283644603565335,
47
+ "raw_frame_host_bytes": 0
48
+ },
49
+ "mapping_seconds": 0.432922558975406,
50
+ "conversion_seconds": 0.020730131946038455,
51
+ "pipe_write_seconds": 0.0,
52
+ "encoder_finish_seconds": 0.4721063140896149,
53
+ "validation_seconds": 0.3217859159922227
54
+ },
55
+ "encode_save_validate_seconds": 1.2586013940162957,
56
+ "total_seconds": 7.198915817018133,
57
+ "peak_gpu_gib": 8.788529872894287,
58
+ "timestamp_validation": "all frames <=1ms",
59
+ "torch": "2.8.0+cu128"
60
+ },
61
+ "scope": "real full clip; test alone copies GPU depth for parity assertion; production transfers only quantile scalars and compressed bytes, no NPZ"
62
+ }
gpu-video-benchmark-before-device.json ADDED
The diff for this file is too large to render. See raw diff
 
gpu-video-benchmark.json ADDED
The diff for this file is too large to render. See raw diff
 
gpu-video-quality-before-device.json ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source_id": "0ebf25f7eb89320b6371d5ff",
3
+ "frames": 101,
4
+ "width": 1280,
5
+ "height": 720,
6
+ "nvdec_planar_rgb_bit_exact": true,
7
+ "CUDA_vs_CPU_precodec_gray_max_difference": 1,
8
+ "CUDA_vs_CPU_precodec_gray_changed_fraction": 9.959003712871288e-06,
9
+ "NVENC_vs_CPU_precodec_gray_mae_8bit": 0.28660919023032233,
10
+ "NVENC_vs_CPU_precodec_gray_rmse_8bit": 0.5916532473010299,
11
+ "depth": {
12
+ "model": "depth-anything/DA3-LARGE",
13
+ "model_provenance": {
14
+ "config_sha256": "744dcaf53859490ed92fc6cb98d68d3daf624b8c54533aaf604bdb53f06321f5",
15
+ "weights_sha256": "eaf2ae06df55889ad23eb245c82e2dd2a30c0cbf7e3d873a118fa5ed27a3e421",
16
+ "code_commit": "3d835ec1a5802d64a8b8b15f817a1ab54809bfe4"
17
+ },
18
+ "process_res": 504,
19
+ "joint_frames": 101,
20
+ "source_width": 1280,
21
+ "source_height": 720,
22
+ "raw_depth_shape": [
23
+ 101,
24
+ 280,
25
+ 504
26
+ ],
27
+ "stored_depth": "depth.mp4 only",
28
+ "units": "relative_depth_not_meters",
29
+ "video_mapping": "inverse depth, per-video fixed percentile 0.5/99.5; near bright",
30
+ "inverse_depth_clip": [
31
+ 0.6175584650039673,
32
+ 1.4080844694375985
33
+ ],
34
+ "decode_seconds": 0.6469188660266809,
35
+ "inference_seconds": 6.322209803969599,
36
+ "video_backend": "cuda",
37
+ "depth_conversion": "CUDA FP32 resize/inverse-depth/quantize, chunk8, single GPU section",
38
+ "encoding": {
39
+ "codec": "h264_nvenc",
40
+ "preset": "p4",
41
+ "rate_control": "constqp",
42
+ "qp": 16,
43
+ "mapping_seconds": 0.06505662703420967,
44
+ "conversion_seconds": 0.04051619034726173,
45
+ "pipe_write_seconds": 0.35969953710446134,
46
+ "encoder_finish_seconds": 0.2704498099628836,
47
+ "validation_seconds": 0.33810621697921306
48
+ },
49
+ "encode_save_validate_seconds": 1.0747915410320275,
50
+ "total_seconds": 8.369265043002088,
51
+ "peak_gpu_gib": 8.78670072555542,
52
+ "timestamp_validation": "all frames <=1ms",
53
+ "torch": "2.8.0+cu128"
54
+ },
55
+ "scope": "full 101-frame source RGB parity; full-frame precodec quantization parity; decoded NVENC quality against the original CPU 8bit depth mapping; lossy video, no NPZ"
56
+ }
pipeline/README.md CHANGED
@@ -79,3 +79,19 @@ $PY "$APP" --limit 0 --per-style 100 \
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 也全部一致。仅一次成对整批测试;网络并发改动没有包含在该收益中。
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 也全部一致。仅一次成对整批测试;网络并发改动没有包含在该收益中。
82
+
83
+ ## GPU 深度输出与设备帧编码
84
+
85
+ 默认 `--video-backend cuda` 使用精简 DA3 接口,只取 GPU 深度张量;不转换或保存未使用的置信度、天空掩码、相机输出与预处理可视化图像。整段反深度 0.5/99.5 百分位在 GPU 上计算,只有四个端点标量回传 CPU;深度、缩放、量化和 NV12 帧始终在 GPU,PyNvVideoCodec 2.2.3 通过设备缓冲直接交给 NVENC。CPU 仅接收压缩 H.264 字节并由 FFmpeg copy 封装 MP4,不经过 CPU 原始灰度视频缓冲,也不再次上传编码帧。GPU 临时帧工作区每批 8 帧。
86
+
87
+ 两个视频后端都使用软件解码:全帧曝光和官方 DA3 预处理仍需要 CPU RGB,之前的 NVDEC 模式会引入无收益的 GPU->CPU 图像回传。现在取消这段回传,保留必要的 CPU->GPU 模型输入。GPU 后端的 DINO 输入明确以 uint8 传输,上卡后才转 FP32,避免在传输前扩展为 float32;归一化与模型计算保持原顺序。CPU 后端保留原组合 device/dtype 转换作为对照。DINO 筛选和 DA3 仍分别解码原视频,尚未合并二者的 CPU 图像缓存;当前不是整个数据清洗流程的零拷贝。ffprobe 帧时间戳验证通过 CPU 完成,完整原始/风格视频文件不重编码。
88
+
89
+ CPU 后端保留 libx264 veryfast/8线程/CRF16 作为对照;同样使用精简 DA3 输出,只将需要的深度转回 CPU。GPU 后端使用 NVENC P4/constqp QP16、无 B 帧。QP16 与 CRF16 不能视为相同质量;两者都是有损编码。GPU 图像使用与灰度视频相同的全范围->有限范围转换,并校验最终完整视频帧数与相对时间戳误差 <=1ms。仍不生成或上传 NPZ。
90
+
91
+ 真实 101 帧 1280×720 样本:精简 DA3 与官方 inference 的浮点深度逐值完全相同,百分位端点完全相同。CUDA 映射相对 CPU 最大差 1 灰阶,仅约 0.001% 像素不同;最终 NVENC 解码相对 CPU 编码前灰度的平均绝对误差 0.251,RMSE 0.541(0–255 尺度)。详见 device-depth-quality.json;测试专门复制深度回 CPU 做断言,生产代码没有该测试用复制。
92
+
93
+ 环境增加 `PyNvVideoCodec==2.2.3`(当前 Python3.12/CUDA环境),安装 wheel 已保存到网络盘 runtime-assets/wheels;新 Pod 恢复 DA3 环境后安装该 wheel。依赖和代码受固定 DA3 commit 约束,切换模型或库版本后应重跑 verify_device_depth.py。NVENC 接口错误会显式报错,不静默跳过样本。
94
+
95
+ `benchmark_gpu_video.py` 使用同 10 条 HF 输入核对 SHA 后,重新运行两条计算流水线;不计下载,HF 上传由完整本地输出校验代替,不是含网络的端到端速度。较早 NVDEC/CPU回传版的结果仅保留在 *before-device.json 历史报告,当前以 device-depth-quality.json 和最新 gpu-video-benchmark.json 为准。
96
+
97
+ 同一批 10 条新鲜 HF 输入的成对实测(单张 A40、不含网络,含模型启动/本地完整输出校验):精简 CPU 后端 148.48 秒,设备帧 GPU 后端 139.18 秒,耗时缩短 6.3%。旧 GPU 回传版 158.76 秒为此前单次记录,供参考,不能将跨轮差异全部归因于本次改动。两组逐帧曝光、帧数、筛选决定和 DINO 分数完全一致;精简 CPU 深度视频解码 SHA256 与此前基线全部相同。GPU 深度视频更换了编码器,不要求与 x264 视频字节或解码 SHA 相同。默认启用 cuda;--video-backend cpu 可用于诊断。
pipeline/benchmark_gpu_video.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Paired ten-clip CPU / GPU-resident depth-NVENC 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/'gpu-video-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,video_backend='cpu'):super().__init__(mode,logdir,overlap,video_backend);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 codec in ['cpu','cuda']:
38
+ serial=False
39
+ name=codec;state=scratch/(name+'-state');work=scratch/(name+'-work');events=[];filter_results={};decoded_hashes={};samples=[];done=threading.Event()
40
+ 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,video_backend=codec)
41
+ run=pipeline.Run(a)
42
+ def local_ship(row,d,filtered,depth):
43
+ assert not any(d.glob('*.npz'))
44
+ for filename in ['source.mp4','edited.mp4','depth.mp4','depth.json','filter.json']:assert (d/filename).is_file()
45
+ check=ffprobe(d/'depth.mp4');assert check['frames']==depth['joint_frames']
46
+ # Stream a decoded checksum rather than retaining depth arrays or videos.
47
+ digest=subprocess.check_output(['ffmpeg','-v','error','-threads','2','-i',str(d/'depth.mp4'),'-f','hash','-hash','sha256','-'],text=True).strip()
48
+ decoded_hashes[row['id']]=digest
49
+ receipt={'record':{'id':row['id']},'verification':'LOCAL BENCHMARK ONLY; no HF commit'}
50
+ atomic(state/'receipts'/(row['id']+'.json'),receipt);run.record(row,'verified',receipt,time.time());return receipt
51
+ run.ship=local_ship
52
+ def monitor():
53
+ while not done.is_set():
54
+ try:
55
+ 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])})
56
+ except Exception:pass
57
+ done.wait(1)
58
+ clock=time.monotonic();thread=threading.Thread(target=monitor);thread.start()
59
+ try:rc=run.run()
60
+ finally:done.set();thread.join()
61
+ assert rc==0,run.metrics['errors'];run.db.close();run.lock.close()
62
+ first=min(e['started'] for e in events);last=max(e['ended'] for e in events)
63
+ 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}
64
+ 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)
65
+ 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']}
66
+ for jid,a in base['filter_results'].items():
67
+ 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'])))
68
+ comparison['active_speedup']=base['active_processing_seconds']/opt['active_processing_seconds'];comparison['wall_speedup']=base['wall_seconds']/opt['wall_seconds']
69
+ 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-3
70
+ print('COMPARISON',json.dumps(comparison),flush=True)
71
+ finally:shutil.rmtree(scratch)
72
+ if __name__=='__main__':main()
pipeline/benchmark_gpu_video_retry.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Paired ten-clip CPU / NVDEC-NVENC 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/'gpu-video-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=[json.loads(reportpath.read_text())['runs'][0]]
30
+ class TimedWorker(pipeline.Worker):
31
+ def __init__(self,mode,logdir,overlap=True,video_backend='cpu'):super().__init__(mode,logdir,overlap,video_backend);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 codec in ['cuda']:
38
+ serial=False
39
+ name=codec;state=scratch/(name+'-state');work=scratch/(name+'-work');events=[];filter_results={};decoded_hashes={};samples=[];done=threading.Event()
40
+ 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,video_backend=codec)
41
+ run=pipeline.Run(a)
42
+ def local_ship(row,d,filtered,depth):
43
+ assert not any(d.glob('*.npz'))
44
+ for filename in ['source.mp4','edited.mp4','depth.mp4','depth.json','filter.json']:assert (d/filename).is_file()
45
+ check=ffprobe(d/'depth.mp4');assert check['frames']==depth['joint_frames']
46
+ # Stream a decoded checksum rather than retaining depth arrays or videos.
47
+ digest=subprocess.check_output(['ffmpeg','-v','error','-threads','2','-i',str(d/'depth.mp4'),'-f','hash','-hash','sha256','-'],text=True).strip()
48
+ decoded_hashes[row['id']]=digest
49
+ receipt={'record':{'id':row['id']},'verification':'LOCAL BENCHMARK ONLY; no HF commit'}
50
+ atomic(state/'receipts'/(row['id']+'.json'),receipt);run.record(row,'verified',receipt,time.time());return receipt
51
+ run.ship=local_ship
52
+ def monitor():
53
+ while not done.is_set():
54
+ try:
55
+ 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])})
56
+ except Exception:pass
57
+ done.wait(1)
58
+ clock=time.monotonic();thread=threading.Thread(target=monitor);thread.start()
59
+ try:rc=run.run()
60
+ finally:done.set();thread.join()
61
+ assert rc==0,run.metrics['errors'];run.db.close();run.lock.close()
62
+ first=min(e['started'] for e in events);last=max(e['ended'] for e in events)
63
+ 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}
64
+ 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)
65
+ 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']}
66
+ for jid,a in base['filter_results'].items():
67
+ 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'])))
68
+ comparison['active_speedup']=base['active_processing_seconds']/opt['active_processing_seconds'];comparison['wall_speedup']=base['wall_seconds']/opt['wall_seconds']
69
+ 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-3
70
+ print('COMPARISON',json.dumps(comparison),flush=True)
71
+ finally:shutil.rmtree(scratch)
72
+ if __name__=='__main__':main()
pipeline/benchmark_overlap.py CHANGED
@@ -28,7 +28,7 @@ def main():
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
@@ -36,7 +36,7 @@ def main():
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'))
 
28
  pipeline.indexed_download=local_download
29
  reports=[]
30
  class TimedWorker(pipeline.Worker):
31
+ def __init__(self,mode,logdir,overlap=True,video_backend='cpu'):super().__init__(mode,logdir,overlap,video_backend);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
 
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,video_backend='cpu')
40
  run=pipeline.Run(a)
41
  def local_ship(row,d,filtered,depth):
42
  assert not any(d.glob('*.npz'))
pipeline/common.py CHANGED
@@ -17,5 +17,5 @@ def sha(p):
17
  return h.hexdigest()
18
  def stable(row):return hashlib.sha256((REV+'\0'+row['source_path']+'\0'+row['edited_path']).encode()).hexdigest()[:24]
19
  def ffprobe(p):
20
- d=json.loads(subprocess.check_output(['ffprobe','-v','error','-select_streams','v:0','-show_streams','-show_frames','-show_entries','stream=width,height,avg_frame_rate,r_frame_rate:frame=best_effort_timestamp_time','-of','json',str(p)]))
21
  s=d['streams'][0];s['pts']=[float(x['best_effort_timestamp_time']) for x in d['frames']];s['frames']=len(s['pts']);return s
 
17
  return h.hexdigest()
18
  def stable(row):return hashlib.sha256((REV+'\0'+row['source_path']+'\0'+row['edited_path']).encode()).hexdigest()[:24]
19
  def ffprobe(p):
20
+ d=json.loads(subprocess.check_output(['ffprobe','-v','error','-select_streams','v:0','-show_streams','-show_frames','-show_entries','stream=width,height,pix_fmt,avg_frame_rate,r_frame_rate:frame=best_effort_timestamp_time','-of','json',str(p)]))
21
  s=d['streams'][0];s['pts']=[float(x['best_effort_timestamp_time']) for x in d['frames']];s['frames']=len(s['pts']);return s
pipeline/environment-depth.txt ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ addict==2.4.0
2
+ antlr4-python3-runtime==4.9.3
3
+ anyio==4.15.1
4
+ apsw==3.54.1.0
5
+ argcomplete==3.7.2
6
+ argon2-cffi==25.1.0
7
+ argon2-cffi-bindings==26.1.0
8
+ arrow==1.4.0
9
+ asttokens==3.0.2
10
+ async-lru==2.3.0
11
+ attrs==26.1.0
12
+ babel==2.18.0
13
+ backports.zstd==1.8.0
14
+ beautifulsoup4==4.15.0
15
+ bleach==6.4.0
16
+ blinker==1.7.0
17
+ certifi==2026.10.19
18
+ cffi==2.1.1
19
+ charset-normalizer==3.5.2
20
+ colorama==0.4.6
21
+ comm==0.2.3
22
+ contourpy==1.4.0
23
+ cryptography==41.0.7
24
+ cuda-bindings==13.4.4
25
+ cuda-pathfinder==1.8.4
26
+ cuda-toolkit==13.0.3.0
27
+ cycler==0.12.1
28
+ dbus-python==1.3.2
29
+ debugpy==1.8.22
30
+ decorator==4.4.2
31
+ defusedxml==0.7.1
32
+ -e git+https://github.com/ByteDance-Seed/Depth-Anything-3.git@3d835ec1a5802d64a8b8b15f817a1ab54809bfe4#egg=depth_anything_3
33
+ distlib==0.4.3
34
+ distro==1.9.0
35
+ e3nn==0.6.0
36
+ einops==0.8.2
37
+ evo==1.38.1
38
+ executing==2.2.1
39
+ fastjsonschema==2.22.2
40
+ filelock==4.2.4
41
+ fonttools==4.67.0
42
+ fqdn==1.6.0
43
+ fsspec==2026.9.0
44
+ h11==0.16.0
45
+ hf-xet==1.7.0
46
+ hf_transfer==0.1.9
47
+ httpcore==1.0.9
48
+ httplib2==0.20.4
49
+ httpx==0.28.1
50
+ huggingface_hub==0.36.2
51
+ idna==3.20
52
+ ImageIO==2.38.1
53
+ imageio-ffmpeg==0.6.0
54
+ indexed_gzip==1.10.3
55
+ ipykernel==7.4.0
56
+ ipython==9.17.1
57
+ ipython_pygments_lexers==1.1.1
58
+ ipywidgets==8.1.8
59
+ isoduration==20.11.0
60
+ jaraco.context==6.1.0
61
+ jedi==0.20.0
62
+ Jinja2==3.1.6
63
+ json5==0.15.0
64
+ jsonpointer==3.1.1
65
+ jsonschema==4.26.0
66
+ jsonschema-specifications==2025.9.1
67
+ jupyter-archive==3.4.0
68
+ jupyter-events==0.12.1
69
+ jupyter-lsp==2.3.1
70
+ jupyter_client==8.10.0
71
+ jupyter_core==5.9.1
72
+ jupyter_server==2.21.1
73
+ jupyter_server_terminals==0.5.4
74
+ jupyterlab==4.5.10
75
+ jupyterlab_pygments==0.3.0
76
+ jupyterlab_server==2.28.1
77
+ jupyterlab_widgets==3.0.17
78
+ kiwisolver==1.5.1
79
+ lark==1.3.1
80
+ launchpadlib==1.11.0
81
+ lazr.restfulclient==0.14.6
82
+ lazr.uri==1.0.6
83
+ lz4==4.4.5
84
+ MarkupSafe==3.0.4
85
+ matplotlib==3.11.2
86
+ matplotlib-inline==0.2.2
87
+ mistune==3.3.4
88
+ moviepy==1.0.3
89
+ mpmath==1.3.0
90
+ natsort==8.4.0
91
+ nbclient==0.11.0
92
+ nbconvert==7.17.1
93
+ nbformat==5.11.1
94
+ nest-asyncio2==1.7.3
95
+ networkx==3.7
96
+ notebook==7.5.6
97
+ notebook_shim==0.2.4
98
+ numexpr==2.14.2
99
+ numpy==2.5.2
100
+ nvidia-cublas==13.1.1.3
101
+ nvidia-cublas-cu12==12.8.4.1
102
+ nvidia-cuda-cupti==13.0.85
103
+ nvidia-cuda-cupti-cu12==12.8.90
104
+ nvidia-cuda-nvrtc==13.0.88
105
+ nvidia-cuda-nvrtc-cu12==12.8.93
106
+ nvidia-cuda-runtime==13.0.96
107
+ nvidia-cuda-runtime-cu12==12.8.90
108
+ nvidia-cudnn-cu12==9.10.2.21
109
+ nvidia-cudnn-cu13==9.24.0.43
110
+ nvidia-cufft==12.0.0.61
111
+ nvidia-cufft-cu12==11.3.3.83
112
+ nvidia-cufile==1.15.1.6
113
+ nvidia-cufile-cu12==1.13.1.3
114
+ nvidia-curand==10.4.0.35
115
+ nvidia-curand-cu12==10.3.9.90
116
+ nvidia-cusolver==12.0.4.66
117
+ nvidia-cusolver-cu12==11.7.3.90
118
+ nvidia-cusparse==12.6.3.3
119
+ nvidia-cusparse-cu12==12.5.8.93
120
+ nvidia-cusparselt-cu12==0.7.1
121
+ nvidia-cusparselt-cu13==0.8.1
122
+ nvidia-nccl-cu12==2.27.3
123
+ nvidia-nccl-cu13==2.30.7
124
+ nvidia-nvjitlink==13.4.92
125
+ nvidia-nvjitlink-cu12==12.8.93
126
+ nvidia-nvshmem-cu13==3.4.5
127
+ nvidia-nvtx==13.0.85
128
+ nvidia-nvtx-cu12==12.8.90
129
+ oauthlib==3.2.2
130
+ omegaconf==2.4.0
131
+ opencv-python-headless==5.0.0.93
132
+ opt-einsum-fx==0.1.4
133
+ opt_einsum==3.4.0
134
+ packaging==26.3
135
+ pandas==3.1.0
136
+ pandocfilters==1.5.1
137
+ parso==0.8.7
138
+ pexpect==4.9.0
139
+ pillow==13.0.0
140
+ pillow_heif==1.8.1
141
+ platformdirs==4.12.2
142
+ plyfile==1.1.5
143
+ proglog==0.1.12
144
+ prometheus_client==0.26.0
145
+ prompt_toolkit==3.0.53
146
+ psutil==7.2.2
147
+ ptyprocess==0.7.0
148
+ pure_eval==0.2.4
149
+ pycolmap==4.2.1
150
+ pycparser==3.0
151
+ Pygments==2.21.0
152
+ PyGObject==3.48.2
153
+ PyJWT==2.7.0
154
+ pynvvideocodec==2.2.3
155
+ pyparsing==3.3.3
156
+ python-apt==2.7.7+ubuntu5.3
157
+ python-dateutil==3.0.0
158
+ python-discovery==1.6.1
159
+ python-json-logger==4.2.0
160
+ PyYAML==6.0.3
161
+ pyzmq==27.2.0
162
+ referencing==0.37.0
163
+ regex==2026.9.29
164
+ requests==2.34.2
165
+ rfc3339-validator==0.1.4
166
+ rfc3986-validator==0.1.1
167
+ rfc3987-syntax==1.1.0
168
+ rosbags==0.11.9
169
+ rpds-py==2026.6.3
170
+ ruamel.yaml==0.19.1
171
+ safetensors==0.8.0
172
+ scipy==1.18.1
173
+ seaborn==0.13.2
174
+ Send2Trash==2.1.0
175
+ setuptools==84.2.1
176
+ six==1.17.0
177
+ soupsieve==2.10
178
+ stack-data==0.6.3
179
+ sympy==1.14.0
180
+ terminado==0.18.1
181
+ tinycss2==1.5.1
182
+ tokenizers==0.22.2
183
+ torch==2.8.0+cu128
184
+ torchaudio==2.8.0+cu128
185
+ torchvision==0.23.0+cu128
186
+ tornado==6.5.10
187
+ tqdm==4.70.1
188
+ traitlets==5.16.1
189
+ transformers==4.57.1
190
+ trimesh==5.1.1
191
+ triton==3.4.0
192
+ typing_extensions==4.16.0
193
+ tzdata==2026.5
194
+ uri-template==1.3.0
195
+ urllib3==2.8.0
196
+ virtualenv==21.14.1
197
+ wadllib==1.3.6
198
+ wcwidth==0.9.1
199
+ webcolors==25.10.0
200
+ webencodings==0.6.1
201
+ websocket-client==1.9.2
202
+ wheel==0.46.2
203
+ widgetsnbextension==4.0.16
pipeline/gpu_depth.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DA3 depth-only output and device-buffer NVENC; no raw-frame host roundtrip."""
2
+ import math,subprocess,time
3
+ from pathlib import Path
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn.functional as F
7
+
8
+ def infer_depth(model,images):
9
+ # Same pinned DA3 preprocessing/forward defaults; no camera input or exports.
10
+ imgs_cpu,ex,ins=model._preprocess_inputs(images,None,None,504,'upper_bound_resize')
11
+ imgs,ex,ins=model._prepare_model_inputs(imgs_cpu,ex,ins)
12
+ raw=model._run_model_forward(imgs,None,ins,[],False,False,'saddle_balanced')
13
+ return raw['depth'].squeeze(0).squeeze(-1).float()
14
+
15
+ def percentiles(dep):
16
+ inv=(1/dep).flatten()
17
+ values=[]
18
+ for q in [.005,.995]:
19
+ index=(inv.numel()-1)*q;low=math.floor(index);high=math.ceil(index)
20
+ a=torch.kthvalue(inv,low+1).values;b=torch.kthvalue(inv,high+1).values
21
+ # NumPy percentile interpolates FP32 endpoints with FP64 weights.
22
+ # Return only four scalar values; the depth tensor stays on the GPU.
23
+ values.append((a,b,index-low))
24
+ out=[]
25
+ for a,b,f in values:
26
+ a,b=float(a),float(b)
27
+ out.append(a+(b-a)*f if f<.5 else b-(b-a)*(1-f))
28
+ return out
29
+
30
+ class CudaPlane:
31
+ def __init__(self,interface):self.__cuda_array_interface__=interface
32
+
33
+ class DeviceFrame:
34
+ def __init__(self,tensor):self.tensor=tensor
35
+ def cuda(self):
36
+ t=self.tensor;h=t.shape[0]*2//3;w=t.shape[1]
37
+ return [CudaPlane({'shape':(h,w,1),'strides':(w,1,1),'typestr':'|u1','data':(t.data_ptr(),False),'version':3}),
38
+ CudaPlane({'shape':(h//2,w//2,2),'strides':(w,2,1),'typestr':'|u1','data':(t.data_ptr()+h*w,False),'version':3})]
39
+
40
+ def encode_device(dep,lo,hi,width,height,fps,path):
41
+ import PyNvVideoCodec as nvc
42
+ if width%2 or height%2:raise ValueError('NV12 requires even dimensions')
43
+ start=time.monotonic();elementary=Path(str(path)+'.h264')
44
+ enc=nvc.CreateEncoder(width,height,'NV12',False,codec='h264',preset='P4',rc='constqp',constqp=16,bf=0,fps=round(float(__import__('fractions').Fraction(fps))),cudacontext=0,cudastream=torch.cuda.current_stream().cuda_stream)
45
+ convert=submit=0.
46
+ try:
47
+ with elementary.open('wb') as out:
48
+ for first in range(0,len(dep),8):
49
+ t=time.monotonic();z=F.interpolate(dep[first:first+8,None],size=(height,width),mode='bilinear',align_corners=False)[:,0]
50
+ gray=torch.round(((1/z.clamp_min(1e-6)-lo)/(hi-lo)).clamp(0,1)*255).to(torch.uint8)
51
+ # Match FFmpeg full-range gray -> limited-range YUV420 conversion.
52
+ y=torch.round(gray.float()*(219/255)+16).to(torch.uint8)
53
+ frames=torch.full((len(y),height*3//2,width),128,dtype=torch.uint8,device=dep.device);frames[:,:height]=y
54
+ torch.cuda.current_stream().synchronize();convert+=time.monotonic()-t
55
+ t=time.monotonic()
56
+ for frame in frames:
57
+ for packet in enc.Encode(DeviceFrame(frame)):out.write(packet['data'])
58
+ submit+=time.monotonic()-t
59
+ for packet in enc.EndEncode():out.write(packet['data'])
60
+ del enc
61
+ subprocess.run(['ffmpeg','-y','-v','error','-r',str(fps),'-i',str(elementary),'-c:v','copy','-color_range','tv','-movflags','+faststart',str(path)],check=True)
62
+ finally:elementary.unlink(missing_ok=True)
63
+ return {'conversion_seconds':convert,'encoder_submit_seconds':submit,'encode_mux_seconds':time.monotonic()-start,'raw_frame_host_bytes':0}
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,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)
@@ -109,7 +109,7 @@ class Run:
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()))
@@ -182,7 +182,7 @@ class Run:
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,7 +192,7 @@ class Run:
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'
 
5
  from streaming import seed_download,indexed_download,build_index
6
 
7
  class Worker:
8
+ def __init__(self,mode,logdir,overlap=True,video_backend='cuda'):
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','STYLEEDIT_VIDEO_BACKEND':video_backend})
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)
 
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,getattr(a,'video_backend','cuda'));df=loads.submit(Worker,'depth',self.state,not a.serial_gpu_stages,getattr(a,'video_backend','cuda'))
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()))
 
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',video_backend=getattr(a,'video_backend','cuda'),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('--video-backend',choices=['cpu','cuda'],default='cuda',help='CPU depth encoding or GPU-resident depth/NVENC device input; RGB decode stays CPU');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 CHANGED
@@ -3,7 +3,8 @@ 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
 
@@ -50,7 +51,7 @@ def pair_run(row,local_paths,encoder,cfg,lock):
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)
@@ -77,6 +78,6 @@ def pair_run(row,local_paths,encoder,cfg,lock):
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
 
3
  from concurrent.futures import ThreadPoolExecutor
4
  import numpy as np
5
  from run_pipeline import final_status
6
+ from curation.filter import probe,alignment
7
+ from video_io import Reader,backend
8
  from curation.pair_checks import FrameCountMismatch
9
  from curation.exposure import Rules,frame_metric,aggregate
10
 
 
51
  with gpu_section(lock):
52
  timing['gpu_lock_wait_seconds']+=time.monotonic()-t
53
  torch.cuda.synchronize();t=time.monotonic();n=len(arrays[0])
54
+ images=[(torch.from_numpy(a).permute(0,3,1,2).to('cuda').float() if backend()=='cuda' else torch.from_numpy(a).permute(0,3,1,2).to('cuda',dtype=torch.float32))/255 for a in arrays]
55
  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]
56
  y=encode_proxy_dino(encoder,torch.cat(images),image_size=(480,832),resize_mode='bilinear',projection_autocast=True)
57
  z=F.normalize(y.squeeze(2).permute(0,2,3,1).reshape(2*n,1560,1024).float(),dim=-1)
 
78
  finally:
79
  if producer:producer.shutdown(wait=True,cancel_futures=True)
80
  for reader in readers:reader.close()
81
+ result['timing']={**timing,'pair_seconds':time.monotonic()-start};result['metric_cache_hit']=False;result['video_backend']=backend();result['dino_input_transfer']='uint8 H2D then CUDA FP32' if backend()=='cuda' else 'combined device/dtype conversion'
82
  result['execution_profile']='overlap-v1; core-v1 math, all frames/pixels, batch4; CPU prefetch1; GPU-exclusive forwards'
83
  return result
pipeline/requirements-depth-codec.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ PyNvVideoCodec==2.2.3
pipeline/verify_device_depth.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Full real clip parity of depth-only forward and device-buffer encoding."""
2
+ import os,sys,json,tempfile,shutil,subprocess,time
3
+ from pathlib import Path
4
+ os.environ['STYLEEDIT_VIDEO_BACKEND']='cuda';sys.argv=['verify_device_depth','depth']
5
+ exec((Path(__file__).parent/'workers.py').read_text().split('for line in sys.stdin:')[0])
6
+ import requests
7
+ root=Path(tempfile.mkdtemp(prefix='styleedit-device-quality-',dir='/opt'))
8
+ try:
9
+ row=json.loads(Path('/workspace/styleedit-streaming-20261024/metadata.jsonl').read_text().splitlines()[0]);r=requests.get(row['source_video'],timeout=120);r.raise_for_status();src=root/'source.mp4';src.write_bytes(r.content)
10
+ meta=ffprobe(src);w,h,n=meta['width'],meta['height'],meta['frames']
11
+ raw=subprocess.check_output(['ffmpeg','-v','error','-threads','2','-i',str(src),'-f','rawvideo','-pix_fmt','rgb24','pipe:1']);rgb=np.frombuffer(raw,np.uint8).reshape(n,h,w,3)
12
+ with torch.inference_mode():ref=model.inference(image=[Image.fromarray(x) for x in rgb],process_res=504,process_res_method='upper_bound_resize',export_dir=None).depth.astype(np.float32)
13
+ del rgb,raw
14
+ captured={};original=infer_depth
15
+ def capture(*args,**kwargs):
16
+ z=original(*args,**kwargs);captured['depth']=z.cpu().numpy();return z
17
+ depth.__globals__['infer_depth']=capture
18
+ info=depth({'dir':str(root),'row':row});dep=captured['depth'];exact=np.array_equal(dep,ref);assert exact,'Depth-only forward changed model values'
19
+ lo,hi=np.percentile(1/ref,[.5,99.5]);pdiff=max(abs(lo-info['inverse_depth_clip'][0]),abs(hi-info['inverse_depth_clip'][1]));assert pdiff<1e-6
20
+ proc=subprocess.Popen(['ffmpeg','-v','error','-threads','2','-i',str(root/'depth.mp4'),'-f','rawvideo','-pix_fmt','gray','pipe:1'],stdout=subprocess.PIPE)
21
+ errs=[];mmax=0;changed=total=0
22
+ for z in ref:
23
+ zz=F.interpolate(torch.from_numpy(z)[None,None],size=(h,w),mode='bilinear',align_corners=False)[0,0].numpy();expected=np.rint(np.clip((1/np.maximum(zz,1e-6)-lo)/(hi-lo),0,1)*255).astype(np.uint8)
24
+ zz=F.interpolate(torch.from_numpy(z)[None,None].cuda(),size=(h,w),mode='bilinear',align_corners=False)[0,0];mapped=torch.round(((1/zz.clamp_min(1e-6)-lo)/(hi-lo)).clamp(0,1)*255).to(torch.uint8).cpu().numpy()
25
+ diff=np.abs(mapped.astype(np.int16)-expected.astype(np.int16));mmax=max(mmax,int(diff.max()));changed+=np.count_nonzero(diff);total+=diff.size
26
+ buf=proc.stdout.read(w*h);assert len(buf)==w*h;decoded=np.frombuffer(buf,np.uint8).reshape(h,w);diff=decoded.astype(np.float32)-expected;errs.append((float(np.abs(diff).mean()),float((diff**2).mean())))
27
+ assert not proc.stdout.read(1) and proc.wait()==0;assert mmax<=1
28
+ mae=float(np.mean([e[0] for e in errs]));assert mae<.5,mae
29
+ report={'source_id':row['id'],'frames':n,'depth_only_forward_bit_exact':exact,'percentile_max_difference':pdiff,'CUDA_vs_CPU_precodec_gray_max_difference':mmax,'CUDA_vs_CPU_precodec_gray_changed_fraction':float(changed/total),'NVENC_vs_CPU_precodec_gray_mae_8bit':mae,'NVENC_vs_CPU_precodec_gray_rmse_8bit':float(np.sqrt(np.mean([e[1] for e in errs]))),'depth':info,'scope':'real full clip; test alone copies GPU depth for parity assertion; production transfers only quantile scalars and compressed bytes, no NPZ'}
30
+ atomic(BASE/'device-depth-quality.json',report);print(json.dumps(report),file=sys.stderr)
31
+ finally:shutil.rmtree(root)
pipeline/verify_gpu_video.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """Verify the current GPU-resident depth and NVENC path on one real clip."""
2
+ import runpy
3
+ from pathlib import Path
4
+ runpy.run_path(str(Path(__file__).with_name('verify_device_depth.py')),run_name='__main__')
pipeline/verify_overlap.py CHANGED
@@ -6,7 +6,7 @@ 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:
 
6
  from common import atomic
7
 
8
  class FakeWorker:
9
+ def __init__(self,mode,logdir,overlap=True,video_backend='cpu'):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:
pipeline/video_io.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CPU RGB decode for CPU consumers; GPU backend refers to resident depth/NVENC."""
2
+ import os,subprocess,tempfile,json
3
+
4
+ def backend():
5
+ value=os.environ.get('STYLEEDIT_VIDEO_BACKEND','cuda')
6
+ if value not in ('cpu','cuda'):raise ValueError('Invalid STYLEEDIT_VIDEO_BACKEND: '+value)
7
+ return value
8
+
9
+ def decode_flags():return [] # CPU consumers need RGB; avoid NVDEC readback.
10
+
11
+ def decode_output_flags():return []
12
+
13
+ def encoder_flags():
14
+ return ['-c:v','h264_nvenc','-preset','p4','-rc','constqp','-qp','16'] if backend()=='cuda' else ['-c:v','libx264','-threads','8','-preset','veryfast','-crf','16']
15
+
16
+ class Reader:
17
+ def __init__(self,path,meta):
18
+ self.meta=meta;self.err=tempfile.TemporaryFile()
19
+ self.p=subprocess.Popen(['ffmpeg','-nostdin','-v','error','-threads','1',*decode_flags(),'-i',str(path),'-map','0:v:0','-vsync','0',*decode_output_flags(),'-f','rawvideo','-pix_fmt','rgb24','-threads','1','pipe:1'],stdout=subprocess.PIPE,stderr=self.err)
20
+ def read(self,n):
21
+ import numpy as np
22
+ h,w=self.meta['height'],self.meta['width'];frames=[]
23
+ for _ in range(n):
24
+ b=self.p.stdout.read(h*w*3)
25
+ if len(b)!=h*w*3:
26
+ self.err.seek(0);raise ValueError('Decoder ended before expected frame count: '+self.err.read().decode(errors='replace')[-2000:])
27
+ frames.append(np.frombuffer(b,np.uint8).reshape(h,w,3))
28
+ return np.stack(frames)
29
+ def finish(self):
30
+ if self.p.stdout.read(1):raise ValueError('Decoder produced unexpected extra frames')
31
+ if self.p.wait(timeout=30)!=0:raise ValueError('ffmpeg decoding failed')
32
+ self.err.seek(0)
33
+ if self.err.read():raise ValueError('ffmpeg reported decode errors')
34
+ def close(self):
35
+ if self.p.poll() is None:self.p.kill();self.p.wait()
36
+ self.p.stdout.close();self.err.close()
pipeline/workers.py CHANGED
@@ -4,6 +4,8 @@ os.environ.setdefault('HF_HUB_OFFLINE','1')
4
  import fcntl,json,sys,time,traceback,contextlib,subprocess
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.
@@ -35,35 +37,49 @@ def depth(job):
35
  pts=np.array(meta['pts']);fps=float(__import__('fractions').Fraction(meta['avg_frame_rate']))
36
  if max(abs(pts-pts[0]-np.arange(n)/fps))>0.001:raise ValueError('VFR source requires explicit timestamp-preserving encoder')
37
  if n*w*h*3>2*1024**3:raise ValueError('Decoded RGB exceeds 2GiB per-video memory cap')
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()
50
  # One fixed inverse-depth mapping per clip; only video is persisted.
51
- lo,hi=np.percentile(1/dep,[0.5,99.5]);assert hi>lo
 
 
 
 
52
  mapping_seconds=time.monotonic()-t;conversion_seconds=pipe_write_seconds=0.0
53
- proc=subprocess.Popen(['ffmpeg','-y','-v','error','-threads','2','-f','rawvideo','-pix_fmt','gray','-s',f'{w}x{h}','-r',meta['avg_frame_rate'],'-i','pipe:0','-an','-c:v','libx264','-threads','8','-preset','veryfast','-crf','16','-pix_fmt','yuv420p','-movflags','+faststart',str(d/'depth.mp4')],stdin=subprocess.PIPE)
54
- try:
55
- for z in dep:
56
- stage_t=time.monotonic()
57
- z=F.interpolate(torch.from_numpy(z)[None,None],size=(h,w),mode='bilinear',align_corners=False)[0,0].numpy()
58
- gray=np.rint(np.clip((1/np.maximum(z,1e-6)-lo)/(hi-lo),0,1)*255).astype(np.uint8);conversion_seconds+=time.monotonic()-stage_t
59
- stage_t=time.monotonic();proc.stdin.write(gray.tobytes());pipe_write_seconds+=time.monotonic()-stage_t
60
- finally:proc.stdin.close()
 
 
 
 
 
 
 
 
 
 
 
 
61
  stage_t=time.monotonic()
62
- if proc.wait()!=0:raise RuntimeError('Depth encoder failed')
63
- encoder_finish_seconds=time.monotonic()-stage_t;stage_t=time.monotonic()
64
  check=ffprobe(d/'depth.mp4')
65
  if check['frames']!=n or max(abs(np.array(check['pts'])-check['pts'][0]-(pts-pts[0])))>.001:raise ValueError('Depth video timestamp mismatch')
66
- out={'model':'depth-anything/DA3-LARGE','model_provenance':da3_provenance,'process_res':504,'joint_frames':n,'source_width':w,'source_height':h,'raw_depth_shape':list(dep.shape),'stored_depth':'depth.mp4 only','units':'relative_depth_not_meters','video_mapping':'inverse depth, per-video fixed percentile 0.5/99.5; near bright','inverse_depth_clip':[float(lo),float(hi)],'decode_seconds':decode_seconds,'inference_seconds':inference_seconds,'encoding':{'codec':'libx264','preset':'veryfast','threads':8,'crf':16,'mapping_seconds':mapping_seconds,'conversion_seconds':conversion_seconds,'pipe_write_seconds':pipe_write_seconds,'encoder_finish_seconds':encoder_finish_seconds,'validation_seconds':time.monotonic()-stage_t},'encode_save_validate_seconds':time.monotonic()-t,'total_seconds':time.monotonic()-start,'peak_gpu_gib':torch.cuda.max_memory_allocated()/1024**3,'timestamp_validation':'all frames <=1ms','torch':torch.__version__}
67
  atomic(d/'depth.json',out);return out
68
  for line in sys.stdin:
69
  try:
 
4
  import fcntl,json,sys,time,traceback,contextlib,subprocess
5
  from pathlib import Path
6
  from common import *
7
+ from video_io import backend,decode_flags,decode_output_flags,encoder_flags
8
+ from gpu_depth import infer_depth,percentiles,encode_device
9
  MODE=sys.argv[1]
10
  OVERLAP=os.environ.get('STYLEEDIT_OVERLAP','1')=='1'
11
  # Model libraries print progress to stdout. Keep the RPC stream private.
 
37
  pts=np.array(meta['pts']);fps=float(__import__('fractions').Fraction(meta['avg_frame_rate']))
38
  if max(abs(pts-pts[0]-np.arange(n)/fps))>0.001:raise ValueError('VFR source requires explicit timestamp-preserving encoder')
39
  if n*w*h*3>2*1024**3:raise ValueError('Decoded RGB exceeds 2GiB per-video memory cap')
40
+ t=time.monotonic();raw=subprocess.check_output(['ffmpeg','-v','error','-threads','2',*decode_flags(),'-i',str(d/'source.mp4'),*decode_output_flags(),'-f','rawvideo','-pix_fmt','rgb24','pipe:1']);rgb=np.frombuffer(raw,np.uint8).reshape(-1,h,w,3)
41
  assert len(rgb)==n;decode_seconds=time.monotonic()-t
42
  torch.cuda.reset_peak_memory_stats();torch.cuda.synchronize();t=time.monotonic()
43
  with contextlib.ExitStack() as gpu_stack:
44
  if OVERLAP:
45
  fcntl.flock(lock,fcntl.LOCK_EX);gpu_stack.callback(fcntl.flock,lock,fcntl.LOCK_UN)
46
+ with torch.inference_mode():dep_gpu=infer_depth(model,[Image.fromarray(x) for x in rgb])
47
  torch.cuda.synchronize()
48
  inference_seconds=time.monotonic()-t
49
+ if len(dep_gpu)!=n or not bool(torch.isfinite(dep_gpu).all()) or bool((dep_gpu<=0).any()):raise ValueError('Invalid DA3 depth')
50
+ dep=dep_gpu if backend()=='cuda' else dep_gpu.cpu().numpy();raw_shape=list(dep.shape)
51
  t=time.monotonic()
52
  # One fixed inverse-depth mapping per clip; only video is persisted.
53
+ with contextlib.ExitStack() as mapping_stack:
54
+ if OVERLAP and backend()=='cuda':
55
+ fcntl.flock(lock,fcntl.LOCK_EX);mapping_stack.callback(fcntl.flock,lock,fcntl.LOCK_UN)
56
+ lo,hi=percentiles(dep) if backend()=='cuda' else np.percentile(1/dep,[0.5,99.5])
57
+ assert hi>lo
58
  mapping_seconds=time.monotonic()-t;conversion_seconds=pipe_write_seconds=0.0
59
+ device_stats={}
60
+ if backend()=='cuda':
61
+ with contextlib.ExitStack() as conversion_stack:
62
+ if OVERLAP:
63
+ fcntl.flock(lock,fcntl.LOCK_EX);conversion_stack.callback(fcntl.flock,lock,fcntl.LOCK_UN)
64
+ device_stats=encode_device(dep,float(lo),float(hi),w,h,meta['avg_frame_rate'],d/'depth.mp4')
65
+ conversion_seconds=device_stats['conversion_seconds'];encoder_finish_seconds=device_stats['encode_mux_seconds']-conversion_seconds
66
+ else:
67
+ proc=subprocess.Popen(['ffmpeg','-y','-v','error','-threads','2','-f','rawvideo','-pix_fmt','gray','-s',f'{w}x{h}','-r',meta['avg_frame_rate'],'-i','pipe:0','-an',*encoder_flags(),'-pix_fmt','yuv420p','-movflags','+faststart',str(d/'depth.mp4')],stdin=subprocess.PIPE)
68
+ try:
69
+ for z in dep:
70
+ stage_t=time.monotonic()
71
+ z=F.interpolate(torch.from_numpy(z)[None,None],size=(h,w),mode='bilinear',align_corners=False)[0,0].numpy()
72
+ gray=np.rint(np.clip((1/np.maximum(z,1e-6)-lo)/(hi-lo),0,1)*255).astype(np.uint8)
73
+ conversion_seconds+=time.monotonic()-stage_t
74
+ stage_t=time.monotonic();proc.stdin.write(gray.tobytes());pipe_write_seconds+=time.monotonic()-stage_t
75
+ finally:proc.stdin.close()
76
+ stage_t=time.monotonic()
77
+ if proc.wait()!=0:raise RuntimeError('Depth encoder failed')
78
+ encoder_finish_seconds=time.monotonic()-stage_t
79
  stage_t=time.monotonic()
 
 
80
  check=ffprobe(d/'depth.mp4')
81
  if check['frames']!=n or max(abs(np.array(check['pts'])-check['pts'][0]-(pts-pts[0])))>.001:raise ValueError('Depth video timestamp mismatch')
82
+ out={'model':'depth-anything/DA3-LARGE','model_provenance':da3_provenance,'process_res':504,'joint_frames':n,'source_width':w,'source_height':h,'raw_depth_shape':raw_shape,'stored_depth':'depth.mp4 only','units':'relative_depth_not_meters','video_mapping':'inverse depth, per-video fixed percentile 0.5/99.5; near bright','inverse_depth_clip':[float(lo),float(hi)],'decode_seconds':decode_seconds,'inference_seconds':inference_seconds,'video_backend':backend(),'depth_conversion':'GPU resident depth -> CUDA FP32 mapping -> NVENC device input, chunk8' if backend()=='cuda' else 'CPU FP32 resize/inverse-depth/quantize','encoding':{**({'codec':'h264_nvenc','api':'PyNvVideoCodec 2.2.3 device input','preset':'p4','rate_control':'constqp','qp':16,'device_stats':device_stats} if backend()=='cuda' else {'codec':'libx264','preset':'veryfast','threads':8,'crf':16}),'mapping_seconds':mapping_seconds,'conversion_seconds':conversion_seconds,'pipe_write_seconds':pipe_write_seconds,'encoder_finish_seconds':encoder_finish_seconds,'validation_seconds':time.monotonic()-stage_t},'encode_save_validate_seconds':time.monotonic()-t,'total_seconds':time.monotonic()-start,'peak_gpu_gib':torch.cuda.max_memory_allocated()/1024**3,'timestamp_validation':'all frames <=1ms','torch':torch.__version__}
83
  atomic(d/'depth.json',out);return out
84
  for line in sys.stdin:
85
  try:
transfer-audit.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "profile": "cuda resident depth, CPU decode for CPU consumers",
3
+ "basis": "code audit; raw host byte counters cover explicit application frame buffers, not an Nsight trace",
4
+ "removed": [
5
+ "NVDEC GPU decoded image -> CPU image (software decode now)",
6
+ "DA3 GPU depth -> NumPy CPU depth -> CUDA depth",
7
+ "CUDA gray -> CPU gray pipe -> NVENC GPU input",
8
+ "Unused DA3 confidence/sky/camera output conversions and processed image visualization"
9
+ ],
10
+ "remaining": [
11
+ "CPU decoded uint8 RGB -> DINO GPU input, FP32 conversion after transfer",
12
+ "DA3 CPU official preprocessed tensor -> GPU model input",
13
+ "Four percentile endpoint scalars and scalar validation results -> CPU",
14
+ "NVENC compressed bitstream -> CPU/network",
15
+ "CPU ffprobe frame/timestamp validation"
16
+ ],
17
+ "not_removed": [
18
+ "Source CPU decoding occurs in both filter and depth stages; no shared RGB cache"
19
+ ],
20
+ "no_npz": true
21
+ }