---
title: "Use your model"
description: "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."
type: "docs-page"
url: "https://tatolab.com/docs/build/models"
site: "Tatolab"
section: "Build in code"
---

# 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

Put the model in a node of its own, as one more reader of the camera, with a `newest` input:

```txt
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.
- `newest` means 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 in `process`.

Install your framework into the project:

```sh
uv add torch
```

## Get the frame as a tensor

A frame hands itself to any framework that speaks [DLPack](https://dmlc.github.io/dlpack/latest/), without a copy to the CPU:

```python
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 × W
```

Where 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

`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:

```python
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

This node runs [YOLO](https://docs.ultralytics.com) through ultralytics on each frame it gets and writes what it finds:

```python title="nodes/object_detector.py"
from dataclasses import dataclass
from pathlib import Path

import torch
from tatolab.stream import (
    Image,
    Input,
    ModelInputTensorKernel,
    Output,
    Records,
    RuntimeContextFullAccess,
    RuntimeContextLimitedAccess,
    log,
    node,
)
from ultralytics import YOLO


@dataclass
class 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.process
class 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

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

- **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×4` `uint8`. It costs a copy back from the GPU; fine for a small model or a frame a second.
- **A model server**: call it from `process` like any other library. The node's own process absorbs the wait, and nothing else in the stream does.

## Keeping up

- `tatolab graph` shows each node's counters: how many frames its input dropped because the model was busy. That's normal with `newest`; 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 `width` and `height` for `ModelInputTensorKernel`, 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.
