Use your model
Run PyTorch, ONNX Runtime, MLX or any other framework on live frames, with the frame handed to the model on the GPU and the results written for the rest of the stream.
Tato doesn’t ship an inference stack. Your model runs in a process node, with whatever framework you already use, installed in your project like any other package. This page shows how to hand it frames on the GPU and write its results for the rest of the stream.
Where the model goes
Section titled “Where the model goes”Put the model in a node of its own, as one more reader of the camera, with a newest input:
camera ─┬─ (the effect, the Node visualizer, an encoder, …) └─ detector ── detections ──▶ (a logger, a dashboard, a MoQ track, …)- The node runs in its own process, so a slow or crashing model can’t stall the picture or anything else in the stream. A crash restarts that one node.
newestmeans the model always gets the latest frame. If inference takes 50 ms and the camera delivers a frame every 33 ms, the model skips frames instead of falling further behind.- Load the model once, in
setup, and run it inprocess.
Install your framework into the project:
uv add torchGet the frame as a tensor
Section titled “Get the frame as a tensor”A frame hands itself to any framework that speaks DLPack, without a copy to the CPU:
import torch
frame = ctx.inputs.read(self.video)if frame is not None: pixels = torch.from_dlpack(frame) # height × width × 4, uint8, on the device the frame lives on rgb = pixels[..., :3].permute(2, 0, 1).unsqueeze(0).float() / 255.0 # 1 × 3 × H × WWhere the tensor lives depends on the machine:
| Machine | torch.from_dlpack(frame) gives |
|---|---|
| Linux with a CUDA runtime | A CUDA tensor |
| Apple silicon Mac | A Metal tensor over the frame’s own IOSurface, which PyTorch 2.10 or later imports as mps, and MLX 0.32 or later as an array |
| No device side | The frame in host memory |
The tensor is valid while the frame object exists, and the runtime won’t reuse the frame’s memory until then. On Linux, a tiled texture reaches a linear tensor through one GPU copy, because DLPack describes linear memory only; it never goes through the CPU.
Treat the tensor as read-only: other nodes can be reading the same frame. To change a frame in place, open it with frame.writable().
Prepare the model’s input on the GPU
Section titled “Prepare the model’s input on the GPU”ModelInputTensorKernel turns an RGBA frame into a model’s input tensor in one compute pass: stretched, letterboxed or padded to the model’s size, channels in the model’s order, scaled and normalised, laid out nchw or nhwc. Build it in setup and apply it per frame:
from tatolab.stream import ModelInputTensorKernel
def setup(self, ctx): self.prepare = ModelInputTensorKernel.compile( ctx.gpu_full_access, width=640, height=640, fit="letterbox", channel_order="rgb", layout="nchw", dtype="float32", scale=1.0 / 255.0, )
def process(self, ctx): frame = ctx.inputs.read(self.video) if frame is None: return model_input = self.prepare.apply_to_surface(ctx.gpu_limited_access, frame.surface_id) with model_input.tensor_surface as tensor_surface: batch = torch.from_dlpack(tensor_surface) # 1 × 3 × 640 × 640, float32 boxes = self.model(batch) boxes_in_frame = model_input.geometry.boxes_to_source(boxes)mean and std normalise per channel. fit="pad_bottom_right" never resizes: it pads the frame up to a multiple of pad_to_multiple_of, so the boxes a model reports are already in frame pixels. Otherwise geometry.boxes_to_source maps them back.
A complete detector
Section titled “A complete detector”This node runs YOLO through ultralytics on each frame it gets and writes what it finds:
from dataclasses import dataclassfrom pathlib import Path
import torchfrom tatolab.stream import ( Image, Input, ModelInputTensorKernel, Output, Records, RuntimeContextFullAccess, RuntimeContextLimitedAccess, log, node,)from ultralytics import YOLO
@dataclassclass ObjectDetectorConfig: weights: str = "yolov8n.pt" confidence: float = 0.4
@node.meta(category="Analysis", description="Finds objects in each frame with YOLO, on the GPU.")@node.processclass ObjectDetector: video = Input(Image, delivery="newest") detections = Output(Records, names=("objects",))
def __init__(self, config: ObjectDetectorConfig) -> None: self.weights = config.weights self.confidence = config.confidence
def setup(self, ctx: RuntimeContextFullAccess) -> None: device = torch.accelerator.current_accelerator(check_available=True) if device is None: raise RuntimeError("this torch build sees no usable GPU") weights = Path(ctx.stream_project_directory) / self.weights self.model = YOLO(str(weights)).to(device) self.names = self.model.names self.prepare = ModelInputTensorKernel.compile( ctx.gpu_full_access, fit="pad_bottom_right", pad_to_multiple_of=32 ) log.info("detector ready", weights=self.weights, device=str(device))
def process(self, ctx: RuntimeContextLimitedAccess) -> None: frame = ctx.inputs.read(self.video) if frame is None: return model_input = self.prepare.apply_to_surface(ctx.gpu_limited_access, frame.surface_id) with model_input.tensor_surface as tensor_surface: result = self.model(torch.from_dlpack(tensor_surface), conf=self.confidence, verbose=False)[0] objects = [ { "label": self.names[int(cls)], "confidence": round(float(conf), 3), "box": [int(v) for v in box], } for cls, conf, box in zip(result.boxes.cls, result.boxes.conf, result.boxes.xyxy) ] ctx.outputs.write(self.detections, {"objects": objects}, timestamp_ns=frame.timestamp_ns)Its weights setting names a checkpoint in the project, resolved against ctx.stream_project_directory; ultralytics downloads a known checkpoint that’s missing. The fisheye-object-detection example is a fuller version: it rectifies a fisheye frame with a compute kernel first, then draws the boxes on the GPU.
Write the results
Section titled “Write the results”Write detections as Records, stamped with the frame’s timestamp_ns, as above. A reader pairs each record with the frame it came from by that stamp, whether it’s another node in the stream, or a stream on another machine reading the track through a MoQ relay.
Records are capped at 64 KiB a message, plenty for detections, poses or a caption. For a mask or an embedding, use an Array output, or publish a picture with the boxes drawn on as an Image output.
Other frameworks and the CPU
Section titled “Other frameworks and the CPU”- ONNX Runtime, TensorRT, MLX, JAX: anything that imports DLPack takes the frame or the prepared tensor the same way. Install it with
uv add. - On the CPU:
with frame.cpu() as pixels:gives a numpy array,H×W×4uint8. It costs a copy back from the GPU; fine for a small model or a frame a second. - A model server: call it from
processlike any other library. The node’s own process absorbs the wait, and nothing else in the stream does.
Keeping up
Section titled “Keeping up”tatolab graphshows each node’s counters: how many frames its input dropped because the model was busy. That’s normal withnewest; it means the model is working on the newest frame it could get.- If the model can’t keep up at all, give it fewer pixels: a smaller
widthandheightforModelInputTensorKernel, or a smaller checkpoint. - Keep the model’s node apart from the picture. An effect or encoder reading the same camera gets every frame, whatever the model does.