StyleEdit / pipeline /gpu_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.19 kB
"""DA3 depth-only output and device-buffer NVENC; no raw-frame host roundtrip."""
import math,subprocess,time
from pathlib import Path
import numpy as np
import torch
import 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}