---
title: "GPU effects"
description: "Write pixel effects as Slang shader nodes, and reach for a compute, graphics or ray-tracing kernel in a process node when one pixel function isn't enough. Frames stay on the GPU throughout."
type: "docs-page"
url: "https://tatolab.com/docs/build/gpu-effects"
site: "Tatolab"
section: "Build in code"
---

# GPU effects

> Write pixel effects as Slang shader nodes, and reach for a compute, graphics or ray-tracing kernel in a process node when one pixel function isn't enough. Frames stay on the GPU throughout.

A frame stays on the GPU from the moment it's captured. Pixel work happens there too, written in [Slang](https://shader-slang.org), which the runtime carries and compiles, so you need no shader toolchain. There are two ways to write it:

- **A shader node**: one Slang function from pictures and numbers to a picture. No Python runs, and nothing to set up. Start here.
- **A kernel in a process node**: a Slang compute, graphics or ray-tracing kernel your node builds in `setup` and dispatches each frame. For effects that need a picture's size, several passes, state between frames, or output that isn't a picture.

## Shader nodes

```python title="nodes/vignette.py"
from tatolab.stream import ImageFrame, node


@node.meta(category="Effects", description="Darken the corners.")
@node.shader(
    """
float4 SoftVignette(ImageInput image, float strength, float softness)
{
    float2 from_centre = (image.uv - 0.5) * float2(1.0, 0.5625) * 2.0;
    float fade = smoothstep(1.0 - softness, 1.0, length(from_centre));
    return float4(image.pixel.rgb * (1.0 - strength * fade), image.pixel.a);
}
"""
)
def SoftVignette(image: ImageFrame, strength: float = 0.6, softness: float = 0.5) -> ImageFrame: ...
```

The Python signature declares the node's ports: each `ImageFrame` is a picture input, each `float` a number input with its default, and the return is the picture output, `result`. The Slang function, named for the node, computes one pixel:

| In Slang | Is |
|---|---|
| `image.pixel` | The input at this pixel, as `float4` RGBA from 0 to 1 |
| `image.uv` | This pixel's position, from `(0, 0)` at the top left to `(1, 1)` |
| `image.sample(uv)` | The input at any position, bilinear |
| each `float` | The number input's value: what it holds, or what's wired into it |

Save the file and the node appears in Tato Studio's node search. Every number input shows its value on the node; drag it and the picture follows. Wire a number node into it, an LFO or a Ramp from the core nodes, and it moves on its own.

The output is the size of the first picture input. A node with two picture inputs blends them:

```python title="nodes/crossfade.py"
from tatolab.stream import ImageFrame, node


@node.meta(category="Composite", description="Fade from a to b.")
@node.shader(
    """
float4 Crossfade(ImageInput a, ImageInput b, float position)
{
    return lerp(a.pixel, b.sample(a.uv), position);
}
"""
)
def Crossfade(a: ImageFrame, b: ImageFrame, position: float = 0.5) -> ImageFrame: ...
```

### Things a shader node can't do

- **It isn't told the picture's size.** A radius or offset in `uv` stretches on a picture that isn't the shape you assumed. The core nodes assume 16:9, which is why their offsets multiply by `0.5625`.
- **It isn't handed the time.** Wire a Timer, Ramp or LFO into the input that moves it.
- **It runs once per picture it's sent.** A number changing doesn't run it, so the picture source sets the frame rate.
- **It needs a picture input.** A generator takes its size from one; the core nodes' Gradient and Noise read `size_from` and none of its pixels.
- **It takes RGBA pictures**, and keeps no state between frames.

The core nodes are worth reading as examples: every Color, Filters, Transform and Composite node in them is a shader node. They're in the runtime's `imports/core-nodes` in every project.

## Compute kernels

A process node builds a kernel once, in `setup`, where it has full access to the GPU, and dispatches it per frame in `process`. No handle, fence or slot number reaches Python: the kernel object is the handle.

```python title="nodes/grayscale.py"
import struct
from dataclasses import dataclass

from tatolab.stream import (
    Image,
    ImageFrameToWrite,
    Input,
    NodeOutputTextureRing,
    Output,
    RuntimeContextFullAccess,
    RuntimeContextLimitedAccess,
    node,
)

GRAYSCALE_SLANG = """
[[vk::binding(0, 0)]] Sampler2D source_frame;
[[vk::binding(1, 0)]] [format("rgba8")] RWTexture2D<float4> graded_frame;

struct Dial { float strength; };
[[vk::push_constant]] ConstantBuffer<Dial> dial;

[numthreads(8, 8, 1)]
void main(uint3 invocation : SV_DispatchThreadID) {
    uint2 extent;
    graded_frame.GetDimensions(extent.x, extent.y);
    if (any(invocation.xy >= extent)) {
        return;
    }
    float4 source = source_frame.Load(int3(invocation.xy, 0));
    float luma = dot(source.rgb, float3(0.299, 0.587, 0.114));
    graded_frame[invocation.xy] = float4(lerp(source.rgb, float3(luma), dial.strength), source.a);
}
"""

DIAL = struct.Struct("<f")


def tiles_covering(pixels: int) -> int:
    return (pixels + 7) // 8


@dataclass
class GrayscaleConfig:
    strength: float = 1.0


@node.meta(category="Effects", description="Grades each frame toward black and white.")
@node.process
class Grayscale:
    video_in = Input(Image, delivery="newest")
    video_out = Output(Image)

    def __init__(self, config: GrayscaleConfig) -> None:
        self.dial = DIAL.pack(config.strength)

    def setup(self, ctx: RuntimeContextFullAccess) -> None:
        self.kernel = ctx.gpu_full_access.create_compute_kernel(
            source=GRAYSCALE_SLANG,
            push_constant_size=DIAL.size,
            bindings={"source_frame": "sampled_texture", "graded_frame": "storage_image"},
        )
        # A camera or test pattern frame is a pixel buffer, which a kernel can't sample,
        # so each one is copied into a texture first, on the GPU.
        self.landing = NodeOutputTextureRing("rgba8_unorm", ["texture_binding"], depth=1)
        self.graded = NodeOutputTextureRing("rgba8_unorm", ["storage_binding", "texture_binding"])

    def process(self, ctx: RuntimeContextLimitedAccess) -> None:
        frame = ctx.inputs.read(self.video_in)
        if frame is None:
            return
        gpu = ctx.gpu_limited_access
        source = self.landing.next_texture_for_this_frame(gpu, frame.width, frame.height)
        gpu.copy_surface_to_surface(frame.surface_id, source)
        graded = self.graded.next_texture_for_this_frame(gpu, frame.width, frame.height)
        self.kernel.dispatch(
            bindings={"source_frame": source, "graded_frame": graded},
            group_count=(tiles_covering(frame.width), tiles_covering(frame.height), 1),
            push_constants=self.dial,
        )
        ctx.outputs.write(
            self.video_out,
            ImageFrameToWrite.of_texture(graded, frame.colour),
            timestamp_ns=frame.timestamp_ns,
        )
```

- `create_compute_kernel` checks the `bindings` you name against the shader's own reflection, so a binding renamed on one side is refused at `setup`, not at the first frame.
- **Push constants** travel with each dispatch. Pack them with `struct`, in the order the Slang struct declares them, and change the two together.
- `NodeOutputTextureRing` hands out a texture per frame from a small ring the node owns, sized to the frame. A texture you publish stays out of reuse until every reader is done with it.
- A frame from a camera or the test pattern is a **pixel buffer**, which a kernel can't sample, so it's copied into a texture first, device to device. A frame another kernel published is a texture already, and binds straight into a dispatch with `frame.surface_id`.
- `ImageFrameToWrite.of_texture(texture, colour)` publishes a texture as a frame, carrying the input's colour description on.

Edit the Slang while `tatolab dev` runs and save: the project reloads with the new text compiled. A kernel that doesn't compile fails the node at `setup`, and the compiler's message is in the log.

## Graphics and ray-tracing kernels

`ctx.gpu_full_access` also builds **graphics kernels**, a vertex and fragment pipeline for drawing geometry, and **ray-tracing kernels** over acceleration structures you build from meshes. The `raytracing-showcase` example renders one scene both ways, side by side; ray tracing needs a GPU and driver that support it, and refuses by name on macOS.

## Edit pixels in place, or on the CPU

- `with frame.writable() as view:` opens a frame for a GPU package to edit in place through DLPack, ordered ahead of the runtime's next read of it.
- `torch.from_dlpack(frame)` hands it to torch as device memory. See [Use your model](https://tatolab.com/docs/build/models).
- `with frame.cpu() as pixels:` copies it back to a numpy array. Fine once a second; per frame, it's the slow way.

## Chain effects

Each effect is a node, so chaining them is linking them: test pattern into Pixelate into your Vignette into the Node visualizer. Shader nodes in a chain each run on the GPU with no process between them; a process node with a kernel adds a process boundary, but the frame stays on the GPU across it.
