StyleEdit / pipeline /verify_device_depth.py
faraway00's picture
Remove DA3 depth host roundtrip and unused outputs; encode GPU frames directly with NVENC; record real clip parity and ten-pair throughput
7ebc150 verified
Raw History Blame Contribute Delete
3.29 kB
"""Full real clip parity of depth-only forward and device-buffer encoding."""
import os,sys,json,tempfile,shutil,subprocess,time
from pathlib import Path
os.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 requests
root=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)