Datasets:
Remove DA3 depth host roundtrip and unused outputs; encode GPU frames directly with NVENC; record real clip parity and ten-pair throughput
Browse filesFiles changed (20)
- device-depth-quality.jsonAdded+62
- gpu-video-benchmark-before-device.jsonAdded
- gpu-video-benchmark.jsonAdded
- gpu-video-quality-before-device.jsonAdded+56
- pipeline/README.md+16
- pipeline/benchmark_gpu_video.pyAdded+72
- pipeline/benchmark_gpu_video_retry.pyAdded+72
- pipeline/benchmark_overlap.py+2-2
- pipeline/common.py+1-1
- pipeline/environment-depth.txtAdded+203
- pipeline/gpu_depth.pyAdded+63
- pipeline/pipeline.py+5-5
- pipeline/pipelined_filter.py+4-3
- pipeline/requirements-depth-codec.txtAdded+1
- pipeline/verify_device_depth.pyAdded+31
- pipeline/verify_gpu_video.pyAdded+4
- pipeline/verify_overlap.py+1-1
- pipeline/video_io.pyAdded+36
- pipeline/workers.py+32-16
- transfer-audit.jsonAdded+21
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162{ "source_id": "0ebf25f7eb89320b6371d5ff", "frames": 101, "depth_only_forward_bit_exact": true, "percentile_max_difference": 0.0, "CUDA_vs_CPU_precodec_gray_max_difference": 1, "CUDA_vs_CPU_precodec_gray_changed_fraction": 9.959003712871288e-06, "NVENC_vs_CPU_precodec_gray_mae_8bit": 0.25091803398462803, "NVENC_vs_CPU_precodec_gray_rmse_8bit": 0.5408237125210781, "depth": { "model": "depth-anything/DA3-LARGE", "model_provenance": { "config_sha256": "744dcaf53859490ed92fc6cb98d68d3daf624b8c54533aaf604bdb53f06321f5", "weights_sha256": "eaf2ae06df55889ad23eb245c82e2dd2a30c0cbf7e3d873a118fa5ed27a3e421", "code_commit": "3d835ec1a5802d64a8b8b15f817a1ab54809bfe4" }, "process_res": 504, "joint_frames": 101, "source_width": 1280, "source_height": 720, "raw_depth_shape": [ 101, 280, 504 ], "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": [ 0.6175584650039673, 1.4080844694375985 ], "decode_seconds": 0.30635125300614163, "inference_seconds": 5.309842279995792, "video_backend": "cuda", "depth_conversion": "GPU resident depth -> CUDA FP32 mapping -> NVENC device input, chunk8", "encoding": { "codec": "h264_nvenc", "api": "PyNvVideoCodec 2.2.3 device input", "preset": "p4", "rate_control": "constqp", "qp": 16, "device_stats": { "conversion_seconds": 0.020730131946038455, "encoder_submit_seconds": 0.09878889191895723, "encode_mux_seconds": 0.49283644603565335, "raw_frame_host_bytes": 0 }, "mapping_seconds": 0.432922558975406, "conversion_seconds": 0.020730131946038455, "pipe_write_seconds": 0.0, "encoder_finish_seconds": 0.4721063140896149, "validation_seconds": 0.3217859159922227 }, "encode_save_validate_seconds": 1.2586013940162957, "total_seconds": 7.198915817018133, "peak_gpu_gib": 8.788529872894287, "timestamp_validation": "all frames <=1ms", "torch": "2.8.0+cu128" }, "scope": "real full clip; test alone copies GPU depth for parity assertion; production transfers only quantile scalars and compressed bytes, no NPZ"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556{ "source_id": "0ebf25f7eb89320b6371d5ff", "frames": 101, "width": 1280, "height": 720, "nvdec_planar_rgb_bit_exact": true, "CUDA_vs_CPU_precodec_gray_max_difference": 1, "CUDA_vs_CPU_precodec_gray_changed_fraction": 9.959003712871288e-06, "NVENC_vs_CPU_precodec_gray_mae_8bit": 0.28660919023032233, "NVENC_vs_CPU_precodec_gray_rmse_8bit": 0.5916532473010299, "depth": { "model": "depth-anything/DA3-LARGE", "model_provenance": { "config_sha256": "744dcaf53859490ed92fc6cb98d68d3daf624b8c54533aaf604bdb53f06321f5", "weights_sha256": "eaf2ae06df55889ad23eb245c82e2dd2a30c0cbf7e3d873a118fa5ed27a3e421", "code_commit": "3d835ec1a5802d64a8b8b15f817a1ab54809bfe4" }, "process_res": 504, "joint_frames": 101, "source_width": 1280, "source_height": 720, "raw_depth_shape": [ 101, 280, 504 ], "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": [ 0.6175584650039673, 1.4080844694375985 ], "decode_seconds": 0.6469188660266809, "inference_seconds": 6.322209803969599, "video_backend": "cuda", "depth_conversion": "CUDA FP32 resize/inverse-depth/quantize, chunk8, single GPU section", "encoding": { "codec": "h264_nvenc", "preset": "p4", "rate_control": "constqp", "qp": 16, "mapping_seconds": 0.06505662703420967, "conversion_seconds": 0.04051619034726173, "pipe_write_seconds": 0.35969953710446134, "encoder_finish_seconds": 0.2704498099628836, "validation_seconds": 0.33810621697921306 }, "encode_save_validate_seconds": 1.0747915410320275, "total_seconds": 8.369265043002088, "peak_gpu_gib": 8.78670072555542, "timestamp_validation": "all frames <=1ms", "torch": "2.8.0+cu128" }, "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"}78 unmodified lines79808178 unmodified lines网络默认下载并发 16、上传并发 4,可用 `--download-workers` / `--upload-workers` 覆盖。有界预取窗口仍为 30,磁盘容量和校验清理规则不变。上传并发设置控制同时处理样本的线程数;底层 HF 客户端可能另有文件分片请求并发。当前吞吐基准固定使用 8/2 且不含 HF 网络,因此不用于宣称网络并发的实测收益。2026-10-24 单张 A40 同 10 条实测:串行总耗时 193.43 秒、overlap-v1 153.75 秒(含模型启动/本地输出校验,不含网络),缩短 20.5%,吞吐提高 25.8%;排除模型启动后的处理时间 181.20 → 140.31 秒,吞吐提高 29.1%。全部筛选决定、全帧曝光、逐帧 DINO 分数完全相同,深度视频解码 SHA256 也全部一致。仅一次成对整批测试;网络并发改动没有包含在该收益中。78 unmodified lines7980818283848586878889909192939495969778 unmodified lines网络默认下载并发 16、上传并发 4,可用 `--download-workers` / `--upload-workers` 覆盖。有界预取窗口仍为 30,磁盘容量和校验清理规则不变。上传并发设置控制同时处理样本的线程数;底层 HF 客户端可能另有文件分片请求并发。当前吞吐基准固定使用 8/2 且不含 HF 网络,因此不用于宣称网络并发的实测收益。2026-10-24 单张 A40 同 10 条实测:串行总耗时 193.43 秒、overlap-v1 153.75 秒(含模型启动/本地输出校验,不含网络),缩短 20.5%,吞吐提高 25.8%;排除模型启动后的处理时间 181.20 → 140.31 秒,吞吐提高 29.1%。全部筛选决定、全帧曝光、逐帧 DINO 分数完全相同,深度视频解码 SHA256 也全部一致。仅一次成对整批测试;网络并发改动没有包含在该收益中。## GPU 深度输出与设备帧编码默认 `--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 帧。两个视频后端都使用软件解码:全帧曝光和官方 DA3 预处理仍需要 CPU RGB,之前的 NVDEC 模式会引入无收益的 GPU->CPU 图像回传。现在取消这段回传,保留必要的 CPU->GPU 模型输入。GPU 后端的 DINO 输入明确以 uint8 传输,上卡后才转 FP32,避免在传输前扩展为 float32;归一化与模型计算保持原顺序。CPU 后端保留原组合 device/dtype 转换作为对照。DINO 筛选和 DA3 仍分别解码原视频,尚未合并二者的 CPU 图像缓存;当前不是整个数据清洗流程的零拷贝。ffprobe 帧时间戳验证通过 CPU 完成,完整原始/风格视频文件不重编码。CPU 后端保留 libx264 veryfast/8线程/CRF16 作为对照;同样使用精简 DA3 输出,只将需要的深度转回 CPU。GPU 后端使用 NVENC P4/constqp QP16、无 B 帧。QP16 与 CRF16 不能视为相同质量;两者都是有损编码。GPU 图像使用与灰度视频相同的全范围->有限范围转换,并校验最终完整视频帧数与相对时间戳误差 <=1ms。仍不生成或上传 NPZ。真实 101 帧 1280×720 样本:精简 DA3 与官方 inference 的浮点深度逐值完全相同,百分位端点完全相同。CUDA 映射相对 CPU 最大差 1 灰阶,仅约 0.001% 像素不同;最终 NVENC 解码相对 CPU 编码前灰度的平均绝对误差 0.251,RMSE 0.541(0–255 尺度)。详见 device-depth-quality.json;测试专门复制深度回 CPU 做断言,生产代码没有该测试用复制。环境增加 `PyNvVideoCodec==2.2.3`(当前 Python3.12/CUDA环境),安装 wheel 已保存到网络盘 runtime-assets/wheels;新 Pod 恢复 DA3 环境后安装该 wheel。依赖和代码受固定 DA3 commit 约束,切换模型或库版本后应重跑 verify_device_depth.py。NVENC 接口错误会显式报错,不静默跳过样本。`benchmark_gpu_video.py` 使用同 10 条 HF 输入核对 SHA 后,重新运行两条计算流水线;不计下载,HF 上传由完整本地输出校验代替,不是含网络的端到端速度。较早 NVDEC/CPU回传版的结果仅保留在 *before-device.json 历史报告,当前以 device-depth-quality.json 和最新 gpu-video-benchmark.json 为准。同一批 10 条新鲜 HF 输入的成对实测(单张 A40、不含网络,含模型启动/本地完整输出校验):精简 CPU 后端 148.48 秒,设备帧 GPU 后端 139.18 秒,耗时缩短 6.3%。旧 GPU 回传版 158.76 秒为此前单次记录,供参考,不能将跨轮差异全部归因于本次改动。两组逐帧曝光、帧数、筛选决定和 DINO 分数完全一致;精简 CPU 深度视频解码 SHA256 与此前基线全部相同。GPU 深度视频更换了编码器,不要求与 x264 视频字节或解码 SHA 相同。默认启用 cuda;--video-backend cpu 可用于诊断。
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""Paired ten-clip CPU / GPU-resident depth-NVENC benchmark using the real Run scheduler.Fresh HF media fetched once, verified against receipts. No HF sample changes.Temporary inputs/outputs deleted on exit; reports only persist. No NPZ output."""import concurrent.futures as cf,copy,json,os,shutil,subprocess,tempfile,threading,timefrom pathlib import Pathfrom types import SimpleNamespaceimport requestsimport pipelinefrom common import *
def main(): scratch=Path(tempfile.mkdtemp(prefix='styleedit-throughput-',dir='/opt'));reportpath=BASE/'gpu-video-benchmark.json' db=pipeline.sqlite3.connect('/workspace/styleedit-streaming-20261024/state/jobs.sqlite') receipts=[json.loads(s) for (s,) in db.execute("SELECT record FROM jobs WHERE status='verified' ORDER BY id LIMIT 10")];db.close() assert len(receipts)==10 try: media=scratch/'inputs';media.mkdir();rows=[] def download(item): v,side=item;r=v['record'];name={'source':'source.mp4','edited':'edited.mp4'}[side];p=media/(r['id']+'-'+name) 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) assert sha(p)==r['files'][name]['sha256'];return p with cf.ThreadPoolExecutor(8) as pool:list(pool.map(download,[(v,s) for v in receipts for s in ['source','edited']])) for v in receipts: 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')]}}) plan=scratch/'plan.json';atomic(plan,rows) def local_download(row,side,dst,index):shutil.copyfile(media/(row['id']+'-'+side+'.mp4'),dst) pipeline.indexed_download=local_download reports=[] class TimedWorker(pipeline.Worker): def __init__(self,mode,logdir,overlap=True,video_backend='cpu'):super().__init__(mode,logdir,overlap,video_backend);self.mode=mode def call(self,job): t=time.monotonic();value=super().call(job);events.append({'mode':self.mode,'id':job['row']['id'],'started':t-clock,'ended':time.monotonic()-clock}) if self.mode=='filter':filter_results[job['row']['id']]=value return value pipeline.Worker=TimedWorker for codec in ['cpu','cuda']: serial=False name=codec;state=scratch/(name+'-state');work=scratch/(name+'-work');events=[];filter_results={};decoded_hashes={};samples=[];done=threading.Event() 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) run=pipeline.Run(a) def local_ship(row,d,filtered,depth): assert not any(d.glob('*.npz')) for filename in ['source.mp4','edited.mp4','depth.mp4','depth.json','filter.json']:assert (d/filename).is_file() check=ffprobe(d/'depth.mp4');assert check['frames']==depth['joint_frames'] # Stream a decoded checksum rather than retaining depth arrays or videos. digest=subprocess.check_output(['ffmpeg','-v','error','-threads','2','-i',str(d/'depth.mp4'),'-f','hash','-hash','sha256','-'],text=True).strip() decoded_hashes[row['id']]=digest receipt={'record':{'id':row['id']},'verification':'LOCAL BENCHMARK ONLY; no HF commit'} atomic(state/'receipts'/(row['id']+'.json'),receipt);run.record(row,'verified',receipt,time.time());return receipt run.ship=local_ship def monitor(): while not done.is_set(): try: 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])}) except Exception:pass done.wait(1) clock=time.monotonic();thread=threading.Thread(target=monitor);thread.start() try:rc=run.run() finally:done.set();thread.join() assert rc==0,run.metrics['errors'];run.db.close();run.lock.close() first=min(e['started'] for e in events);last=max(e['ended'] for e in events) 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} 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) 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']} for jid,a in base['filter_results'].items(): 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']))) comparison['active_speedup']=base['active_processing_seconds']/opt['active_processing_seconds'];comparison['wall_speedup']=base['wall_seconds']/opt['wall_seconds'] 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 print('COMPARISON',json.dumps(comparison),flush=True) finally:shutil.rmtree(scratch)if __name__=='__main__':main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""Paired ten-clip CPU / NVDEC-NVENC benchmark using the real Run scheduler.Fresh HF media fetched once, verified against receipts. No HF sample changes.Temporary inputs/outputs deleted on exit; reports only persist. No NPZ output."""import concurrent.futures as cf,copy,json,os,shutil,subprocess,tempfile,threading,timefrom pathlib import Pathfrom types import SimpleNamespaceimport requestsimport pipelinefrom common import *
def main(): scratch=Path(tempfile.mkdtemp(prefix='styleedit-throughput-',dir='/opt'));reportpath=BASE/'gpu-video-benchmark.json' db=pipeline.sqlite3.connect('/workspace/styleedit-streaming-20261024/state/jobs.sqlite') receipts=[json.loads(s) for (s,) in db.execute("SELECT record FROM jobs WHERE status='verified' ORDER BY id LIMIT 10")];db.close() assert len(receipts)==10 try: media=scratch/'inputs';media.mkdir();rows=[] def download(item): v,side=item;r=v['record'];name={'source':'source.mp4','edited':'edited.mp4'}[side];p=media/(r['id']+'-'+name) 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) assert sha(p)==r['files'][name]['sha256'];return p with cf.ThreadPoolExecutor(8) as pool:list(pool.map(download,[(v,s) for v in receipts for s in ['source','edited']])) for v in receipts: 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')]}}) plan=scratch/'plan.json';atomic(plan,rows) def local_download(row,side,dst,index):shutil.copyfile(media/(row['id']+'-'+side+'.mp4'),dst) pipeline.indexed_download=local_download reports=[json.loads(reportpath.read_text())['runs'][0]] class TimedWorker(pipeline.Worker): def __init__(self,mode,logdir,overlap=True,video_backend='cpu'):super().__init__(mode,logdir,overlap,video_backend);self.mode=mode def call(self,job): t=time.monotonic();value=super().call(job);events.append({'mode':self.mode,'id':job['row']['id'],'started':t-clock,'ended':time.monotonic()-clock}) if self.mode=='filter':filter_results[job['row']['id']]=value return value pipeline.Worker=TimedWorker for codec in ['cuda']: serial=False name=codec;state=scratch/(name+'-state');work=scratch/(name+'-work');events=[];filter_results={};decoded_hashes={};samples=[];done=threading.Event() 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) run=pipeline.Run(a) def local_ship(row,d,filtered,depth): assert not any(d.glob('*.npz')) for filename in ['source.mp4','edited.mp4','depth.mp4','depth.json','filter.json']:assert (d/filename).is_file() check=ffprobe(d/'depth.mp4');assert check['frames']==depth['joint_frames'] # Stream a decoded checksum rather than retaining depth arrays or videos. digest=subprocess.check_output(['ffmpeg','-v','error','-threads','2','-i',str(d/'depth.mp4'),'-f','hash','-hash','sha256','-'],text=True).strip() decoded_hashes[row['id']]=digest receipt={'record':{'id':row['id']},'verification':'LOCAL BENCHMARK ONLY; no HF commit'} atomic(state/'receipts'/(row['id']+'.json'),receipt);run.record(row,'verified',receipt,time.time());return receipt run.ship=local_ship def monitor(): while not done.is_set(): try: 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])}) except Exception:pass done.wait(1) clock=time.monotonic();thread=threading.Thread(target=monitor);thread.start() try:rc=run.run() finally:done.set();thread.join() assert rc==0,run.metrics['errors'];run.db.close();run.lock.close() first=min(e['started'] for e in events);last=max(e['ended'] for e in events) 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} 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) 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']} for jid,a in base['filter_results'].items(): 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']))) comparison['active_speedup']=base['active_processing_seconds']/opt['active_processing_seconds'];comparison['wall_speedup']=base['wall_seconds']/opt['wall_seconds'] 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 print('COMPARISON',json.dumps(comparison),flush=True) finally:shutil.rmtree(scratch)if __name__=='__main__':main()27 unmodified lines282930313233341 unmodified line3637383940414227 unmodified linespipeline.indexed_download=local_downloadreports=[]class TimedWorker(pipeline.Worker):def __init__(self,mode,logdir,overlap=True):super().__init__(mode,logdir,overlap);self.mode=modedef call(self,job):t=time.monotonic();value=super().call(job);events.append({'mode':self.mode,'id':job['row']['id'],'started':t-clock,'ended':time.monotonic()-clock})if self.mode=='filter':filter_results[job['row']['id']]=value1 unmodified linepipeline.Worker=TimedWorkerfor serial in [True,False]:name='serial' if serial else 'overlap';state=scratch/(name+'-state');work=scratch/(name+'-work');events=[];filter_results={};decoded_hashes={};samples=[];done=threading.Event()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)run=pipeline.Run(a)def local_ship(row,d,filtered,depth):assert not any(d.glob('*.npz'))27 unmodified lines282930313233341 unmodified line3637383940414227 unmodified linespipeline.indexed_download=local_downloadreports=[]class TimedWorker(pipeline.Worker):def __init__(self,mode,logdir,overlap=True,video_backend='cpu'):super().__init__(mode,logdir,overlap,video_backend);self.mode=modedef call(self,job):t=time.monotonic();value=super().call(job);events.append({'mode':self.mode,'id':job['row']['id'],'started':t-clock,'ended':time.monotonic()-clock})if self.mode=='filter':filter_results[job['row']['id']]=value1 unmodified linepipeline.Worker=TimedWorkerfor serial in [True,False]:name='serial' if serial else 'overlap';state=scratch/(name+'-state');work=scratch/(name+'-work');events=[];filter_results={};decoded_hashes={};samples=[];done=threading.Event()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')run=pipeline.Run(a)def local_ship(row,d,filtered,depth):assert not any(d.glob('*.npz'))
16 unmodified lines171819202116 unmodified linesreturn h.hexdigest()def stable(row):return hashlib.sha256((REV+'\0'+row['source_path']+'\0'+row['edited_path']).encode()).hexdigest()[:24]def ffprobe(p):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)]))s=d['streams'][0];s['pts']=[float(x['best_effort_timestamp_time']) for x in d['frames']];s['frames']=len(s['pts']);return s16 unmodified lines171819202116 unmodified linesreturn h.hexdigest()def stable(row):return hashlib.sha256((REV+'\0'+row['source_path']+'\0'+row['edited_path']).encode()).hexdigest()[:24]def ffprobe(p):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)]))s=d['streams'][0];s['pts']=[float(x['best_effort_timestamp_time']) for x in d['frames']];s['frames']=len(s['pts']);return s
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203addict==2.4.0antlr4-python3-runtime==4.9.3anyio==4.15.1apsw==3.54.1.0argcomplete==3.7.2argon2-cffi==25.1.0argon2-cffi-bindings==26.1.0arrow==1.4.0asttokens==3.0.2async-lru==2.3.0attrs==26.1.0babel==2.18.0backports.zstd==1.8.0beautifulsoup4==4.15.0bleach==6.4.0blinker==1.7.0certifi==2026.10.19cffi==2.1.1charset-normalizer==3.5.2colorama==0.4.6comm==0.2.3contourpy==1.4.0cryptography==41.0.7cuda-bindings==13.4.4cuda-pathfinder==1.8.4cuda-toolkit==13.0.3.0cycler==0.12.1dbus-python==1.3.2debugpy==1.8.22decorator==4.4.2defusedxml==0.7.1-e git+https://github.com/ByteDance-Seed/Depth-Anything-3.git@3d835ec1a5802d64a8b8b15f817a1ab54809bfe4#egg=depth_anything_3distlib==0.4.3distro==1.9.0e3nn==0.6.0einops==0.8.2evo==1.38.1executing==2.2.1fastjsonschema==2.22.2filelock==4.2.4fonttools==4.67.0fqdn==1.6.0fsspec==2026.9.0h11==0.16.0hf-xet==1.7.0hf_transfer==0.1.9httpcore==1.0.9httplib2==0.20.4httpx==0.28.1huggingface_hub==0.36.2idna==3.20ImageIO==2.38.1imageio-ffmpeg==0.6.0indexed_gzip==1.10.3ipykernel==7.4.0ipython==9.17.1ipython_pygments_lexers==1.1.1ipywidgets==8.1.8isoduration==20.11.0jaraco.context==6.1.0jedi==0.20.0Jinja2==3.1.6json5==0.15.0jsonpointer==3.1.1jsonschema==4.26.0jsonschema-specifications==2025.9.1jupyter-archive==3.4.0jupyter-events==0.12.1jupyter-lsp==2.3.1jupyter_client==8.10.0jupyter_core==5.9.1jupyter_server==2.21.1jupyter_server_terminals==0.5.4jupyterlab==4.5.10jupyterlab_pygments==0.3.0jupyterlab_server==2.28.1jupyterlab_widgets==3.0.17kiwisolver==1.5.1lark==1.3.1launchpadlib==1.11.0lazr.restfulclient==0.14.6lazr.uri==1.0.6lz4==4.4.5MarkupSafe==3.0.4matplotlib==3.11.2matplotlib-inline==0.2.2mistune==3.3.4moviepy==1.0.3mpmath==1.3.0natsort==8.4.0nbclient==0.11.0nbconvert==7.17.1nbformat==5.11.1nest-asyncio2==1.7.3networkx==3.7notebook==7.5.6notebook_shim==0.2.4numexpr==2.14.2numpy==2.5.2nvidia-cublas==13.1.1.3nvidia-cublas-cu12==12.8.4.1nvidia-cuda-cupti==13.0.85nvidia-cuda-cupti-cu12==12.8.90nvidia-cuda-nvrtc==13.0.88nvidia-cuda-nvrtc-cu12==12.8.93nvidia-cuda-runtime==13.0.96nvidia-cuda-runtime-cu12==12.8.90nvidia-cudnn-cu12==9.10.2.21nvidia-cudnn-cu13==9.24.0.43nvidia-cufft==12.0.0.61nvidia-cufft-cu12==11.3.3.83nvidia-cufile==1.15.1.6nvidia-cufile-cu12==1.13.1.3nvidia-curand==10.4.0.35nvidia-curand-cu12==10.3.9.90nvidia-cusolver==12.0.4.66nvidia-cusolver-cu12==11.7.3.90nvidia-cusparse==12.6.3.3nvidia-cusparse-cu12==12.5.8.93nvidia-cusparselt-cu12==0.7.1nvidia-cusparselt-cu13==0.8.1nvidia-nccl-cu12==2.27.3nvidia-nccl-cu13==2.30.7nvidia-nvjitlink==13.4.92nvidia-nvjitlink-cu12==12.8.93nvidia-nvshmem-cu13==3.4.5nvidia-nvtx==13.0.85nvidia-nvtx-cu12==12.8.90oauthlib==3.2.2omegaconf==2.4.0opencv-python-headless==5.0.0.93opt-einsum-fx==0.1.4opt_einsum==3.4.0packaging==26.3pandas==3.1.0pandocfilters==1.5.1parso==0.8.7pexpect==4.9.0pillow==13.0.0pillow_heif==1.8.1platformdirs==4.12.2plyfile==1.1.5proglog==0.1.12prometheus_client==0.26.0prompt_toolkit==3.0.53psutil==7.2.2ptyprocess==0.7.0pure_eval==0.2.4pycolmap==4.2.1pycparser==3.0Pygments==2.21.0PyGObject==3.48.2PyJWT==2.7.0pynvvideocodec==2.2.3pyparsing==3.3.3python-apt==2.7.7+ubuntu5.3python-dateutil==3.0.0python-discovery==1.6.1python-json-logger==4.2.0PyYAML==6.0.3pyzmq==27.2.0referencing==0.37.0regex==2026.9.29requests==2.34.2rfc3339-validator==0.1.4rfc3986-validator==0.1.1rfc3987-syntax==1.1.0rosbags==0.11.9rpds-py==2026.6.3ruamel.yaml==0.19.1safetensors==0.8.0scipy==1.18.1seaborn==0.13.2Send2Trash==2.1.0setuptools==84.2.1six==1.17.0soupsieve==2.10stack-data==0.6.3sympy==1.14.0terminado==0.18.1tinycss2==1.5.1tokenizers==0.22.2torch==2.8.0+cu128torchaudio==2.8.0+cu128torchvision==0.23.0+cu128tornado==6.5.10tqdm==4.70.1traitlets==5.16.1transformers==4.57.1trimesh==5.1.1triton==3.4.0typing_extensions==4.16.0tzdata==2026.5uri-template==1.3.0urllib3==2.8.0virtualenv==21.14.1wadllib==1.3.6wcwidth==0.9.1webcolors==25.10.0webencodings==0.6.1websocket-client==1.9.2wheel==0.46.2widgetsnbextension==4.0.16123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263"""DA3 depth-only output and device-buffer NVENC; no raw-frame host roundtrip."""import math,subprocess,timefrom pathlib import Pathimport numpy as npimport torchimport torch.nn.functional as F
def infer_depth(model,images): # Same pinned DA3 preprocessing/forward defaults; no camera input or exports. imgs_cpu,ex,ins=model._preprocess_inputs(images,None,None,504,'upper_bound_resize') imgs,ex,ins=model._prepare_model_inputs(imgs_cpu,ex,ins) raw=model._run_model_forward(imgs,None,ins,[],False,False,'saddle_balanced') return raw['depth'].squeeze(0).squeeze(-1).float()
def percentiles(dep): inv=(1/dep).flatten() values=[] for q in [.005,.995]: index=(inv.numel()-1)*q;low=math.floor(index);high=math.ceil(index) a=torch.kthvalue(inv,low+1).values;b=torch.kthvalue(inv,high+1).values # NumPy percentile interpolates FP32 endpoints with FP64 weights. # Return only four scalar values; the depth tensor stays on the GPU. values.append((a,b,index-low)) out=[] for a,b,f in values: a,b=float(a),float(b) out.append(a+(b-a)*f if f<.5 else b-(b-a)*(1-f)) return out
class CudaPlane: def __init__(self,interface):self.__cuda_array_interface__=interface
class DeviceFrame: def __init__(self,tensor):self.tensor=tensor def cuda(self): t=self.tensor;h=t.shape[0]*2//3;w=t.shape[1] return [CudaPlane({'shape':(h,w,1),'strides':(w,1,1),'typestr':'|u1','data':(t.data_ptr(),False),'version':3}), CudaPlane({'shape':(h//2,w//2,2),'strides':(w,2,1),'typestr':'|u1','data':(t.data_ptr()+h*w,False),'version':3})]
def encode_device(dep,lo,hi,width,height,fps,path): import PyNvVideoCodec as nvc if width%2 or height%2:raise ValueError('NV12 requires even dimensions') start=time.monotonic();elementary=Path(str(path)+'.h264') 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) convert=submit=0. try: with elementary.open('wb') as out: for first in range(0,len(dep),8): t=time.monotonic();z=F.interpolate(dep[first:first+8,None],size=(height,width),mode='bilinear',align_corners=False)[:,0] gray=torch.round(((1/z.clamp_min(1e-6)-lo)/(hi-lo)).clamp(0,1)*255).to(torch.uint8) # Match FFmpeg full-range gray -> limited-range YUV420 conversion. y=torch.round(gray.float()*(219/255)+16).to(torch.uint8) frames=torch.full((len(y),height*3//2,width),128,dtype=torch.uint8,device=dep.device);frames[:,:height]=y torch.cuda.current_stream().synchronize();convert+=time.monotonic()-t t=time.monotonic() for frame in frames: for packet in enc.Encode(DeviceFrame(frame)):out.write(packet['data']) submit+=time.monotonic()-t for packet in enc.EndEncode():out.write(packet['data']) del enc subprocess.run(['ffmpeg','-y','-v','error','-r',str(fps),'-i',str(elementary),'-c:v','copy','-color_range','tv','-movflags','+faststart',str(path)],check=True) finally:elementary.unlink(missing_ok=True) return {'conversion_seconds':convert,'encoder_submit_seconds':submit,'encode_mux_seconds':time.monotonic()-start,'raw_frame_host_bytes':0}4 unmodified lines567891011121395 unmodified lines10911011111211311411566 unmodified lines1821831841851861871883 unmodified lines1921931941951961971984 unmodified linesfrom streaming import seed_download,indexed_download,build_indexclass Worker:def __init__(self,mode,logdir,overlap=True):env='/opt/goku-dinov3-eval-env/bin/python' if mode=='filter' else '/opt/da3-depth-env/bin/python'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'})line=self.p.stdout.readline()if not line:raise RuntimeError(mode+' worker failed; see log')self.ready=json.loads(line);print('WORKER_READY',self.ready,flush=True)95 unmodified lines# Download bounded windows. Network workers never run arbitrarily far ahead.with cf.ThreadPoolExecutor(a.download_workers) as pool:loads=cf.ThreadPoolExecutor(2)ff=loads.submit(Worker,'filter',self.state,not a.serial_gpu_stages);df=loads.submit(Worker,'depth',self.state,not a.serial_gpu_stages)for first in range(0,len(rows),a.window):for uf in self.uploads:if uf.done() and uf.exception() is not None:raise RuntimeError('Upload failed; retained local media and stopped downloads: '+str(uf.exception()))66 unmodified linesif filterworker:filterworker.close()if depthworker:depthworker.close()self.stop.set();cleaner.join(timeout=5);self.clean_once()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')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]atomic(self.state/('benchmark-'+self.runid+'.json'),self.metrics);atomic(self.state/'summary.json',self.metrics)print('RUN_COMPLETE',json.dumps({k:v for k,v in self.metrics.items() if k not in ['filter','depth','download_groups']}),flush=True)3 unmodified linesreturn 0 if success and not self.metrics['errors'] else 2def main():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()if a.index:build_index(a.index,a.index_state);return 0if not a.seed_ranges:dbpath=Path(a.index_state)/'catalog.sqlite'4 unmodified lines567891011121395 unmodified lines10911011111211311411566 unmodified lines1821831841851861871883 unmodified lines1921931941951961971984 unmodified linesfrom streaming import seed_download,indexed_download,build_indexclass Worker:def __init__(self,mode,logdir,overlap=True,video_backend='cuda'):env='/opt/goku-dinov3-eval-env/bin/python' if mode=='filter' else '/opt/da3-depth-env/bin/python'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})line=self.p.stdout.readline()if not line:raise RuntimeError(mode+' worker failed; see log')self.ready=json.loads(line);print('WORKER_READY',self.ready,flush=True)95 unmodified lines# Download bounded windows. Network workers never run arbitrarily far ahead.with cf.ThreadPoolExecutor(a.download_workers) as pool:loads=cf.ThreadPoolExecutor(2)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'))for first in range(0,len(rows),a.window):for uf in self.uploads:if uf.done() and uf.exception() is not None:raise RuntimeError('Upload failed; retained local media and stopped downloads: '+str(uf.exception()))66 unmodified linesif filterworker:filterworker.close()if depthworker:depthworker.close()self.stop.set();cleaner.join(timeout=5);self.clean_once()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')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]atomic(self.state/('benchmark-'+self.runid+'.json'),self.metrics);atomic(self.state/'summary.json',self.metrics)print('RUN_COMPLETE',json.dumps({k:v for k,v in self.metrics.items() if k not in ['filter','depth','download_groups']}),flush=True)3 unmodified linesreturn 0 if success and not self.metrics['errors'] else 2def main():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()if a.index:build_index(a.index,a.index_state);return 0if not a.seed_ranges:dbpath=Path(a.index_state)/'catalog.sqlite'
2 unmodified lines345678940 unmodified lines5051525354555620 unmodified lines7778798081822 unmodified linesfrom concurrent.futures import ThreadPoolExecutorimport numpy as npfrom run_pipeline import final_statusfrom curation.filter import Reader,probe,alignmentfrom curation.pair_checks import FrameCountMismatchfrom curation.exposure import Rules,frame_metric,aggregate40 unmodified lineswith gpu_section(lock):timing['gpu_lock_wait_seconds']+=time.monotonic()-ttorch.cuda.synchronize();t=time.monotonic();n=len(arrays[0])images=[torch.from_numpy(a).permute(0,3,1,2).to('cuda',dtype=torch.float32)/255 for a in arrays]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]y=encode_proxy_dino(encoder,torch.cat(images),image_size=(480,832),resize_mode='bilinear',projection_autocast=True)z=F.normalize(y.squeeze(2).permute(0,2,3,1).reshape(2*n,1560,1024).float(),dim=-1)20 unmodified linesfinally:if producer:producer.shutdown(wait=True,cancel_futures=True)for reader in readers:reader.close()result['timing']={**timing,'pair_seconds':time.monotonic()-start};result['metric_cache_hit']=Falseresult['execution_profile']='overlap-v1; core-v1 math, all frames/pixels, batch4; CPU prefetch1; GPU-exclusive forwards'return result2 unmodified lines34567891040 unmodified lines5152535455565720 unmodified lines7879808182832 unmodified linesfrom concurrent.futures import ThreadPoolExecutorimport numpy as npfrom run_pipeline import final_statusfrom curation.filter import probe,alignmentfrom video_io import Reader,backendfrom curation.pair_checks import FrameCountMismatchfrom curation.exposure import Rules,frame_metric,aggregate40 unmodified lineswith gpu_section(lock):timing['gpu_lock_wait_seconds']+=time.monotonic()-ttorch.cuda.synchronize();t=time.monotonic();n=len(arrays[0])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]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]y=encode_proxy_dino(encoder,torch.cat(images),image_size=(480,832),resize_mode='bilinear',projection_autocast=True)z=F.normalize(y.squeeze(2).permute(0,2,3,1).reshape(2*n,1560,1024).float(),dim=-1)20 unmodified linesfinally:if producer:producer.shutdown(wait=True,cancel_futures=True)for reader in readers:reader.close()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'result['execution_profile']='overlap-v1; core-v1 math, all frames/pixels, batch4; CPU prefetch1; GPU-exclusive forwards'return result
1PyNvVideoCodec==2.2.312345678910111213141516171819202122232425262728293031"""Full real clip parity of depth-only forward and device-buffer encoding."""import os,sys,json,tempfile,shutil,subprocess,timefrom pathlib import Pathos.environ['STYLEEDIT_VIDEO_BACKEND']='cuda';sys.argv=['verify_device_depth','depth']exec((Path(__file__).parent/'workers.py').read_text().split('for line in sys.stdin:')[0])import requestsroot=Path(tempfile.mkdtemp(prefix='styleedit-device-quality-',dir='/opt'))try: 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) meta=ffprobe(src);w,h,n=meta['width'],meta['height'],meta['frames'] 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) 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) del rgb,raw captured={};original=infer_depth def capture(*args,**kwargs): z=original(*args,**kwargs);captured['depth']=z.cpu().numpy();return z depth.__globals__['infer_depth']=capture info=depth({'dir':str(root),'row':row});dep=captured['depth'];exact=np.array_equal(dep,ref);assert exact,'Depth-only forward changed model values' 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 proc=subprocess.Popen(['ffmpeg','-v','error','-threads','2','-i',str(root/'depth.mp4'),'-f','rawvideo','-pix_fmt','gray','pipe:1'],stdout=subprocess.PIPE) errs=[];mmax=0;changed=total=0 for z in ref: 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) 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() 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 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()))) assert not proc.stdout.read(1) and proc.wait()==0;assert mmax<=1 mae=float(np.mean([e[0] for e in errs]));assert mae<.5,mae 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'} atomic(BASE/'device-depth-quality.json',report);print(json.dumps(report),file=sys.stderr)finally:shutil.rmtree(root)1234"""Verify the current GPU-resident depth and NVENC path on one real clip."""import runpyfrom pathlib import Pathrunpy.run_path(str(Path(__file__).with_name('verify_device_depth.py')),run_name='__main__')5 unmodified lines67891011125 unmodified linesfrom common import atomicclass FakeWorker:def __init__(self,mode,logdir,overlap=True):self.mode=mode;self.ready={'gpu':'test','load_seconds':0};self.active=Falsedef call(self,job):assert not self.active,'Concurrent RPCs to the same worker';self.active=Truetry:5 unmodified lines67891011125 unmodified linesfrom common import atomicclass FakeWorker:def __init__(self,mode,logdir,overlap=True,video_backend='cpu'):self.mode=mode;self.ready={'gpu':'test','load_seconds':0};self.active=Falsedef call(self,job):assert not self.active,'Concurrent RPCs to the same worker';self.active=Truetry:
123456789101112131415161718192021222324252627282930313233343536"""CPU RGB decode for CPU consumers; GPU backend refers to resident depth/NVENC."""import os,subprocess,tempfile,json
def backend(): value=os.environ.get('STYLEEDIT_VIDEO_BACKEND','cuda') if value not in ('cpu','cuda'):raise ValueError('Invalid STYLEEDIT_VIDEO_BACKEND: '+value) return value
def decode_flags():return [] # CPU consumers need RGB; avoid NVDEC readback.
def decode_output_flags():return []
def encoder_flags(): return ['-c:v','h264_nvenc','-preset','p4','-rc','constqp','-qp','16'] if backend()=='cuda' else ['-c:v','libx264','-threads','8','-preset','veryfast','-crf','16']
class Reader: def __init__(self,path,meta): self.meta=meta;self.err=tempfile.TemporaryFile() 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) def read(self,n): import numpy as np h,w=self.meta['height'],self.meta['width'];frames=[] for _ in range(n): b=self.p.stdout.read(h*w*3) if len(b)!=h*w*3: self.err.seek(0);raise ValueError('Decoder ended before expected frame count: '+self.err.read().decode(errors='replace')[-2000:]) frames.append(np.frombuffer(b,np.uint8).reshape(h,w,3)) return np.stack(frames) def finish(self): if self.p.stdout.read(1):raise ValueError('Decoder produced unexpected extra frames') if self.p.wait(timeout=30)!=0:raise ValueError('ffmpeg decoding failed') self.err.seek(0) if self.err.read():raise ValueError('ffmpeg reported decode errors') def close(self): if self.p.poll() is None:self.p.kill();self.p.wait() self.p.stdout.close();self.err.close()3 unmodified lines45678925 unmodified lines35363738394041424344454647484950515253545556575859606162636465666768693 unmodified linesimport fcntl,json,sys,time,traceback,contextlib,subprocessfrom pathlib import Pathfrom common import *MODE=sys.argv[1]OVERLAP=os.environ.get('STYLEEDIT_OVERLAP','1')=='1'# Model libraries print progress to stdout. Keep the RPC stream private.25 unmodified linespts=np.array(meta['pts']);fps=float(__import__('fractions').Fraction(meta['avg_frame_rate']))if max(abs(pts-pts[0]-np.arange(n)/fps))>0.001:raise ValueError('VFR source requires explicit timestamp-preserving encoder')if n*w*h*3>2*1024**3:raise ValueError('Decoded RGB exceeds 2GiB per-video memory cap')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)assert len(rgb)==n;decode_seconds=time.monotonic()-ttorch.cuda.reset_peak_memory_stats();torch.cuda.synchronize();t=time.monotonic()with contextlib.ExitStack() as gpu_stack:if OVERLAP:fcntl.flock(lock,fcntl.LOCK_EX);gpu_stack.callback(fcntl.flock,lock,fcntl.LOCK_UN)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)torch.cuda.synchronize()inference_seconds=time.monotonic()-tdep=p.depth.astype(np.float32)if len(dep)!=n or not np.isfinite(dep).all() or np.any(dep<=0):raise ValueError('Invalid DA3 depth')t=time.monotonic()# One fixed inverse-depth mapping per clip; only video is persisted.lo,hi=np.percentile(1/dep,[0.5,99.5]);assert hi>lomapping_seconds=time.monotonic()-t;conversion_seconds=pipe_write_seconds=0.0proc=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)try:for z in dep:stage_t=time.monotonic()z=F.interpolate(torch.from_numpy(z)[None,None],size=(h,w),mode='bilinear',align_corners=False)[0,0].numpy()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_tstage_t=time.monotonic();proc.stdin.write(gray.tobytes());pipe_write_seconds+=time.monotonic()-stage_tfinally:proc.stdin.close()stage_t=time.monotonic()if proc.wait()!=0:raise RuntimeError('Depth encoder failed')encoder_finish_seconds=time.monotonic()-stage_t;stage_t=time.monotonic()check=ffprobe(d/'depth.mp4')if check['frames']!=n or max(abs(np.array(check['pts'])-check['pts'][0]-(pts-pts[0])))>.001:raise ValueError('Depth video timestamp mismatch')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__}atomic(d/'depth.json',out);return outfor line in sys.stdin:try:3 unmodified lines456789101125 unmodified lines373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384853 unmodified linesimport fcntl,json,sys,time,traceback,contextlib,subprocessfrom pathlib import Pathfrom common import *from video_io import backend,decode_flags,decode_output_flags,encoder_flagsfrom gpu_depth import infer_depth,percentiles,encode_deviceMODE=sys.argv[1]OVERLAP=os.environ.get('STYLEEDIT_OVERLAP','1')=='1'# Model libraries print progress to stdout. Keep the RPC stream private.25 unmodified linespts=np.array(meta['pts']);fps=float(__import__('fractions').Fraction(meta['avg_frame_rate']))if max(abs(pts-pts[0]-np.arange(n)/fps))>0.001:raise ValueError('VFR source requires explicit timestamp-preserving encoder')if n*w*h*3>2*1024**3:raise ValueError('Decoded RGB exceeds 2GiB per-video memory cap')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)assert len(rgb)==n;decode_seconds=time.monotonic()-ttorch.cuda.reset_peak_memory_stats();torch.cuda.synchronize();t=time.monotonic()with contextlib.ExitStack() as gpu_stack:if OVERLAP:fcntl.flock(lock,fcntl.LOCK_EX);gpu_stack.callback(fcntl.flock,lock,fcntl.LOCK_UN)with torch.inference_mode():dep_gpu=infer_depth(model,[Image.fromarray(x) for x in rgb])torch.cuda.synchronize()inference_seconds=time.monotonic()-tif len(dep_gpu)!=n or not bool(torch.isfinite(dep_gpu).all()) or bool((dep_gpu<=0).any()):raise ValueError('Invalid DA3 depth')dep=dep_gpu if backend()=='cuda' else dep_gpu.cpu().numpy();raw_shape=list(dep.shape)t=time.monotonic()# One fixed inverse-depth mapping per clip; only video is persisted.with contextlib.ExitStack() as mapping_stack:if OVERLAP and backend()=='cuda':fcntl.flock(lock,fcntl.LOCK_EX);mapping_stack.callback(fcntl.flock,lock,fcntl.LOCK_UN)lo,hi=percentiles(dep) if backend()=='cuda' else np.percentile(1/dep,[0.5,99.5])assert hi>lomapping_seconds=time.monotonic()-t;conversion_seconds=pipe_write_seconds=0.0device_stats={}if backend()=='cuda':with contextlib.ExitStack() as conversion_stack:if OVERLAP:fcntl.flock(lock,fcntl.LOCK_EX);conversion_stack.callback(fcntl.flock,lock,fcntl.LOCK_UN)device_stats=encode_device(dep,float(lo),float(hi),w,h,meta['avg_frame_rate'],d/'depth.mp4')conversion_seconds=device_stats['conversion_seconds'];encoder_finish_seconds=device_stats['encode_mux_seconds']-conversion_secondselse: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)try:for z in dep:stage_t=time.monotonic()z=F.interpolate(torch.from_numpy(z)[None,None],size=(h,w),mode='bilinear',align_corners=False)[0,0].numpy()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_tstage_t=time.monotonic();proc.stdin.write(gray.tobytes());pipe_write_seconds+=time.monotonic()-stage_tfinally:proc.stdin.close()stage_t=time.monotonic()if proc.wait()!=0:raise RuntimeError('Depth encoder failed')encoder_finish_seconds=time.monotonic()-stage_tstage_t=time.monotonic()check=ffprobe(d/'depth.mp4')if check['frames']!=n or max(abs(np.array(check['pts'])-check['pts'][0]-(pts-pts[0])))>.001:raise ValueError('Depth video timestamp mismatch')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__}atomic(d/'depth.json',out);return outfor line in sys.stdin:try:
123456789101112131415161718192021{ "profile": "cuda resident depth, CPU decode for CPU consumers", "basis": "code audit; raw host byte counters cover explicit application frame buffers, not an Nsight trace", "removed": [ "NVDEC GPU decoded image -> CPU image (software decode now)", "DA3 GPU depth -> NumPy CPU depth -> CUDA depth", "CUDA gray -> CPU gray pipe -> NVENC GPU input", "Unused DA3 confidence/sky/camera output conversions and processed image visualization" ], "remaining": [ "CPU decoded uint8 RGB -> DINO GPU input, FP32 conversion after transfer", "DA3 CPU official preprocessed tensor -> GPU model input", "Four percentile endpoint scalars and scalar validation results -> CPU", "NVENC compressed bitstream -> CPU/network", "CPU ffprobe frame/timestamp validation" ], "not_removed": [ "Source CPU decoding occurs in both filter and depth stages; no shared RGB cache" ], "no_npz": true}device-depth-quality.jsonAdded+62
gpu-video-benchmark-before-device.jsonAdded
gpu-video-benchmark.jsonAdded
gpu-video-quality-before-device.jsonAdded+56
pipeline/README.md+16
pipeline/benchmark_gpu_video.pyAdded+72
pipeline/benchmark_gpu_video_retry.pyAdded+72
pipeline/benchmark_overlap.py+2-2
pipeline/common.py+1-1
pipeline/environment-depth.txtAdded+203
pipeline/gpu_depth.pyAdded+63
pipeline/pipeline.py+5-5
pipeline/pipelined_filter.py+4-3
pipeline/requirements-depth-codec.txtAdded+1
pipeline/verify_device_depth.pyAdded+31
pipeline/verify_gpu_video.pyAdded+4
pipeline/verify_overlap.py+1-1
pipeline/video_io.pyAdded+36
pipeline/workers.py+32-16
transfer-audit.jsonAdded+21