Skip to main content

Getting started with graphs

A graph describes a GPU computation before its input data is supplied. Declare the external inputs, add operations, choose the results you want to keep, and compile. Each execution binds actual data; operations define intermediate values and the graph manages their storage.

Start with GPUGraph on a WebGPU device. For the shared expression subset on WebGL, use GPUSimpleGraph. A semantic operation is not automatically portable between the two implementations.

1. Describe the computation​

import {GPUGraph, gpuExpression} from '@luma.gl/graph/gpu-graph';

const graph = new GPUGraph();
graph.addInput('values', {type: 'vector', format: 'float32'});
graph.addInput('scale', {type: 'scalar', format: 'float32'});
graph.add(gpuExpression, {output: 'scaled', expression: 'values * scale'});
graph.add(gpuExpression, {output: 'result', expression: 'scaled + 1'});

Names connect operations. values and scale are inputs; scaled and result are produced values. There is no separate declaration or buffer allocation for either produced value. Add producers before consumers. The expression reference explains functions, casts, typed rows, component access, and selection.

A vector descriptor specifies the stored row format. Its length and chunk boundaries come from the GPUVector supplied at execution. A float32x3 vector stores three components per row. Supply the scalar scale as a JavaScript number.

2. Compile once, supply data per execution​

Compile once. For this example, values is a caller-owned GPUVector with one chunk containing three float32 rows: [1, 2, 3]. The executable walkthrough includes the upload, readback, and cleanup on failure.

const compiledGraph = graph.compile(device, {outputs: {result: {type: 'vector', format: 'float32'}}});
const {result} = await compiledGraph.run({inputs: {values, scale: 2}});
try {
const chunk = result.data[0];
const bytes = await chunk.buffer.readAsync(chunk.byteOffset, 12);
// new Float32Array(bytes.buffer, bytes.byteOffset, 3) contains [3, 5, 7].
} finally {
result.destroy();
}

On this GPU-only path, run() submits the work. Reading the bytes waits for the result. Keep compiledGraph and values for the second invocation below.

3. Understand ownership​

ResourceOwnerCleanup
Input vector and initialized stateCallerKeep alive through submission and subsequent uses
Unselected operation resultPrepared executionCompiler-managed transient storage; eligible results can reuse allocations
Returned allocated outputCallerDestroy when no longer needed by submitted or future consumers
Caller-supplied output targetCallerBorrowed by the execution; never destroyed by graph cleanup
Reusable compiled graphCallerDestroy after its executions have been submitted or abandoned

Chunk boundaries are preserved. Expressions require matching vector-input partitions; the graph does not silently concatenate or repack data. Reuse is within one invocation, not a cache shared between concurrent executions. See values and storage for state, targets, lifetime rules, and allocation limits.

Scoped cleanup with using​

Compiled graphs, prepared executions, state, and owned vectors support Symbol.dispose. A using declaration runs their normal cleanup at the end of the scope, including on early return or error. Declare owners before the resources that depend on them so cleanup happens in reverse order.

{
using program = graph.compile(device, {outputs: ['result']});
using execution = program.prepare({inputs: {values, scale: 3}});
using result = execution.outputs.result;

execution.encode(encoder);
addDownstreamCommands(encoder, result);
device.submit(encoder.finish());
}

Keep the scope open through submission or discard the encoder before leaving the scope. Prepared execution cleanup releases scratch and keeps returned outputs alive. Give an allocated output its own using declaration when that scope owns it. Keep borrowed inputs or output targets under their original owner.

Use a runtime with Symbol.dispose, or load its polyfill before importing the graph package. TypeScript projects can include ESNext.Disposable in their compiler libraries. destroy() remains available for resources that outlive a lexical scope.

4. Compose with a frame​

Use the same compiled graph and input vector with a new scale. Here a buffer copy stands in for the next consumer in a frame. Both commands use the caller's encoder. When accepting a compiled graph from another component, check compiledGraph.supportsCallerOwnedEncoding before preparing it. If false, use await compiledGraph.run(bindings) and consume the returned outputs after it resolves.

import {Buffer} from '@luma.gl/core/api';

const readback = device.createBuffer({byteLength: 12, usage: Buffer.MAP_READ | Buffer.COPY_DST});
const execution = compiledGraph.prepare({inputs: {values, scale: 3}});
const encoder = device.createCommandEncoder();
execution.encode(encoder);
const chunk = execution.outputs.result.data[0];
encoder.copyBufferToBuffer({
sourceBuffer: chunk.buffer instanceof Buffer ? chunk.buffer : chunk.buffer.buffer,
sourceOffset: chunk.byteOffset,
destinationBuffer: readback,
size: 12
});
device.submit(encoder.finish());
encoder.destroy();
execution.destroy();
execution.outputs.result.destroy();
const bytes = await readback.readAsync();
// new Float32Array(bytes.buffer, bytes.byteOffset, 3) contains [4, 7, 10].
readback.destroy();
values.destroy();
compiledGraph.destroy();

If encoding fails, discard the unsubmitted encoder before releasing execution scratch and the selected output. A prepared execution encodes once. See values and state for the detailed lifetime rules and CPU and GPU data flow for programs with asynchronous CPU stages.

5. Add work from a GPU library​

Choose the graph that matches the inputs you already have.

Inputs and output you needHow to add the workExample
Named inputs connected to other operationsgraph.add(definition, props) on GPUGraph. Use the output names in downstream operations.Raster smoothing and gradients
Existing GPU buffers or textures, with results to consume before compilinggraph.add(query, {id}) or graph.add(definition, props) on GPUCommandGraph. Borrow typed views with graph.getContribution(id, queryOrDefinition).Shared topology and traversal, indexed vector search
Concrete GPU commands inside an existing command graphgraph.add(producer). The producer supplies compute, render, or copy nodes.Nested effect commands

A contribution's views stay valid while their enclosing graph owns the allocations. After compiling, encode producers and consumers together. For a frame that may be abandoned, use GPUGraphFrame to submit all recorded work and publish any attached history together.

Where to go next​

To see why operations need intermediate values, try the interactive visibility pipeline. Toggle a row and trace it from input to draw. The compiler diagram then shows when two named temporaries can occupy the same physical buffer.

Own resources across frames​

Set allocation sizes when adding a contribution or creating its controller. For example, ocean resolution and fire volume dimensions determine which resources the graph allocates. Pass per-frame settings through the compiled graph's execution parameters.

Use getContribution(id, definition) before compilation to connect borrowed result views to downstream work. For example, a render pass can sample the fire contribution's combustion texture. A physics application can also use the rigid-body contribution's world to change controls or read diagnostics between frames.

The graph releases resources its contributions create. If you supply an existing controller, keep it alive through graph execution and release it afterward. When several steps maintain frame history, give them the same GPUGraphFrame so their state advances with the submitted work.