Skip to main content

Naming graph operations

Use graph.add(gpuCompact, bindings) to bind a reusable WebGPU operation to named graph values. The definition describes its scalar and vector ports, output capacity, and WebGPU implementation. Each call adds a distinct occurrence. Supply actual input data when running the compiled graph.

Choose a name​

What the API doesConventionExample
Describes work to add to a graphA lower camel case gpu name for the GPU operation. Prefer a verb such as compact; a recognized algorithm name such as connectedComponents also works.graph.add(gpuExpression, props), graph.add(gpuConnectedComponents, props)
Attaches work immediatelyA verb describing the mutation, with the destination graph as an argumentappendEffects(graph, props)
Represents an operation implementationA PascalCase class or interfaceGPUGraphOperationInstance, GPUCommandOperation
Holds device resources or persistent simulation stateA noun with an explicit lifecycleGPUVector, GPURigidBodyWorld

A definition describes an operation independently of any particular use. Pass its configuration to graph.add(definition, configuration). The graph owns scheduling and intermediate allocation. An operation's gpu prefix describes where the work executes; check the operation's backend support separately. The connected-components and compaction example below requires WebGPU.

Export general-purpose definitions from @luma.gl/graph. Export domain definitions from the library that implements them. Existing expression built-ins such as sqrt and sin stay inside expressions, and evaluator functions retain their own API.

GPU modules as graph libraries​

A domain library exports operations that read and produce named graph values. Keep shader code and command producers in the module that implements the work. A producer can also serve a lower-level command graph, so both entry points report the same GPU resource dependencies and scheduling costs. Applications import the operations they use directly.

Some libraries need a controller. For example, scientific advection exposes gpuAdvectParticles for one integration step; ScientificFlowGraph owns playback time, resident field snapshots and rotating particle buffers. The sphere world owns solver state across steps. These classes can orchestrate the same GPU work that an application composes itself. The fixed-step flow controllers can record into a GPUGraphFrame, share tentative buffers with rendering, and publish their clocks and buffer roles when the submitted frame completes.

What can I pass to graph.add()?​

For fixed-port operations, the two-argument form accepts a GPUGraphOperation definition and a map of its port names to graph value names. TypeScript infers the required keys from the definition. The definition's lower(context, bindings, id) hook constructs WebGPU commands for each use. The compiler supplies an ID unique to that lowering, including repeated iterations. Output ports can declare capacityLike to inherit an input vector's capacity and chunk boundaries.

The single-argument form accepts a step or a nested array of steps.

GPUGraphStep is the union of two independent interfaces. Both are exported from @luma.gl/graph. The graph configures each definition when you call add.

StepWhat you supplyWhen to use it
GPUGraphOperationInstanceAn id, a semantic type, and optionally metadata and a resource contractAdd work with graph.add(gpuExpression, props) and let the compiler lower it.
GPUGraphCommandProducergetCommandNodes(graph) returning a list of GPUCommandGraphEntry valuesSupply explicit commands or compose other producers. The method can use the target graph to declare scratch resources.

A producer with fixed children can omit the graph argument. Here a single authoring step groups two producers. At compilation the command graph visits their children in order until it reaches concrete compute, render, or copy commands.

import type {GPUGraphCommandProducer} from '@luma.gl/graph/gpu-graph';

function sequence(first: GPUGraphCommandProducer, second: GPUGraphCommandProducer): GPUGraphCommandProducer {
return {getCommandNodes: () => [first, second]};
}

Use graph.createScope({id}) to name a group and graph.add(scope) to capture its children for inspection. Dependencies still come from the operations and their lowered resource accesses.

The target convention for public GPU names reserves GPU<Name> and GPU<Name>Props outside an established family for a graph operation and its configuration. For instance, GPUCompactProps configures gpuCompact. Shared graph concepts use a family prefix such as GPUGraph or GPUCommand.

Shared types for operation authors use the GPUGraphOperation prefix. For example, GPUGraphOperationContract describes logical resource access, and a GPUGraphOperationLowering tells the compiler how to lower an operation.

Command-graph contributions​

On a GPUCommandGraph, the two-argument form of add binds concrete graph views and typically takes an id. Before compiling, pass that ID and the same definition or query to graph.getContribution(id, contributor) to infer the result type and check which contributor produced it. Use getContribution<Result>(id) when a generic result needs a more specific type. Consumers use the returned views to declare resource dependencies. Use graph views within the graph that created them. A result returned as a concrete GPUVector can be imported into another graph. Encode its producer first and keep the owning compiled graph and any borrowed inputs alive through submission.

A library can offer both forms under the same definition. For example, gpuEffects takes named textures on GPUGraph. On GPUCommandGraph, it takes texture views and can bind temporal history and per-frame uniforms. Use gpuEffects.commands(props) when composing a nested command producer, and scope.add(gpuEffects, props) when composing a named scope.

Core operations​

Pass operation definitions to GPUGraph.add. Use the built-in if and loop methods for structured control flow. gpuCompact, gpuMultiplyAdd, and gpuDotProduct declare fixed scalar and vector ports. Configured definitions such as gpuExpression and gpuUpload take typed props. GPUGraphOperation describes both forms. An expression's getContract(props) derives its reads from the parsed expression. The same contract is used for compilation and can be inspected before adding the step:

const props = {expression: 'x * scale', output: 'scaled'};
const accesses = gpuExpression.getContract(props).values;
graph.add(gpuExpression, props);

Here accesses contains reads of x and scale and a write of scaled. Use scope.add(gpuExpression, props) to capture the expression in a detached scope.

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

const graph = new GPUGraph();
graph.addInput('scale', {type: 'scalar', format: 'float32'});
graph.add(gpuUpload, {output: 'x', format: 'float32', data: new Float32Array([1, 2, 3])});
graph.add(gpuMultiplyAdd, {input: 'x', scale: 'scale', addend: 'x', output: 'y'});
graph.add(gpuDotProduct, {left: 'x', right: 'y', output: 'total'});
const compiledGraph = graph.compile(device, {outputs: ['total']});

Supply scale at execution. Multiply-add allocates y with the capacity and chunk partition of x. Dot product produces a scalar and can consume vectors with different chunk boundaries. Both definitions also accept typed compiler handles. For example, a bounded loop body can use scope.add(gpuDotProduct, {left: inputVector, right: weightsVector, output: totalScalar}).

/gpu-graph definitionConfiguration type
gpuExpressionGPUExpressionProps
gpuUpload, gpuCopyGPUUploadProps, GPUCopyProps
gpuCompactGPUCompactProps
gpuReduce, gpuGroupAggregateGPUReduceProps, GPUGroupAggregateProps
gpuDrawFullscreenGPUDrawFullscreenProps
gpuCommandGPUCommandProps
cpuCallbackCPUCallbackProps. The callback executes on the host.
Compiler authoring definitionConfiguration type
graph.if(), graph.loop()GPUGraphIfOptions, GPUGraphLoopOptions
gpuScalarLiteralGPUScalarLiteralProps
gpuScalarArithmetic, gpuScalarCompareGPUScalarArithmeticProps, GPUScalarCompareProps
gpuMultiplyAdd, gpuDotProductGPUMultiplyAddProps, GPUDotProductProps. Both accept named bindings or compiler handles.
gpuSparseMatVecGPUSparseMatVecProps
gpuRenderGPURenderProps
graph.createScope()Optional GPUGraphScopeOptions for a group ID and diagnostic metadata.

Use graph.add(definition, props) at the top level and scope.add(definition, props) within a group, conditional, or loop. Compatible expression and evaluator operations also use add(definition, props) on GPUSimpleGraph.

Chain add() calls to build a sequence. Create a detached scope with {id, metadata} when the group needs diagnostic details. Scheduling primitives such as GPUScan take concrete resource views in the command API.

When an operation still needs a class​

CapabilityExample
Immutable configuration over named values or concrete viewsgpuDGGSCellBoundary supports both through graph.add(). It can use caller-supplied views or allocate transient outputs.
Supply compatible parameters for each encodinggpuProjectCoordinates can select a compatible projection with programParameter. The upload is recorded in the caller’s encoder.
Own resources or simulation state across framesGPURigidBodyWorld retains solver resources. gpuStepRigidBodyWorld contributes an individual step.
Assemble command-level scheduling explicitlyGPUScan accepts typed views so another producer can schedule it with its own scratch and dependencies.

Compose operations from two modules​

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

const graph = new GPUGraph();
const uintRows = {type: 'vector', format: 'uint32'} as const;
graph.addInput('offsets', uintRows);
graph.addInput('neighbors', uintRows);
graph.addInput('keepVertex', uintRows);

graph.add(gpuConnectedComponents, {
offsets: 'offsets', neighbors: 'neighbors', vertexCount: 4, output: 'labels'
});
graph.add(gpuCompact, {
input: 'labels', flags: 'keepVertex', output: 'selectedLabels', count: 'selectedCount'
});

const compiledGraph = graph.compile(device, {outputs: ['selectedLabels', 'selectedCount']});

The first operation labels each vertex of a graph stored in compressed sparse row (CSR) form. Supply one packed uint32 chunk for each CSR input. The offsets include a final sentinel, so four vertices need five offsets. The operation uses the declared vertex count to size the labels. It applies the existing bounded weak-components algorithm (32 iterations by default); complete convergence depends on the graph and iteration budget.

The second operation reads the labels by name. The caller supplies one flag per vertex at execution. selectedCount is the number of valid rows in the prefix of selectedLabels. The caller can use both outputs and leave the intermediate labels to the graph. See compaction for capacity and count semantics.

Domain operations and persistent state​

Both definitions below satisfy GPUGraphOperation and come from their domain entry points.

import {gpuVertexDegree} from '@luma.gl/graph/gpu-graph-algorithms';

const analysis = new GPUGraph();
analysis.addInput('rowStarts', {type: 'vector', format: 'uint32'});
analysis.add(gpuVertexDegree, {offsets: 'rowStarts', output: 'degrees', vertexCount: 3});
const program = analysis.compile(device, {outputs: ['degrees']});
const {degrees} = await program.run({inputs: {rowStarts}});

Supply one packed CSR offsets chunk with a final sentinel. For example, offsets [0, 2, 2, 3] produce degrees [2, 0, 1]. The definition uses bind because the output size comes from configuration. The caller owns the returned vector.

From sphere motion to selected IDs​

A frame steps a caller-owned GPUSphereWorld, tests the solved heights and compacts the matching IDs. The world keeps its clock, orientations and contact history across frames. Bind its position and velocity buffers as two mutable graph values. Each vector must wrap the corresponding world buffer as one packed float32x4 chunk starting at byte zero, with one row per body.

import {gpuStepSphereWorld} from '@luma.gl/graph/gpu-physics';
import {gpuCompact, gpuExpression} from '@luma.gl/graph/gpu-graph';
import type {GPUVector} from '@luma.gl/graph/gpu-data';

const simulation = new GPUGraph();
simulation.addState('centers', {type: 'vector', format: 'float32x4'});
simulation.addState('motion', {type: 'vector', format: 'float32x4'});
simulation.add(gpuStepSphereWorld, {world, positions: 'centers', velocities: 'motion'});
simulation.addInput('ids', {type: 'vector', format: 'uint32'});
simulation.addInput('height', {type: 'scalar', format: 'float32'});
simulation.add(gpuExpression, {output: 'above', expression: 'centers.z > height'});
simulation.add(gpuCompact, {input: 'ids', flags: 'above', output: 'selected', count: 'count'});

const program = simulation.compile<Record<'selected' | 'count', GPUVector<'uint32'>>>(device, {
outputs: ['selected', 'count']
});
const bindings = {inputs: {ids, height: 1.01}, state: {centers: positions, motion: velocities}};
const encoder = device.createCommandEncoder();
const first = program.prepare(bindings);
const second = program.prepare(bindings);
first.encode(encoder);
second.encode(encoder);
device.submit(encoder.finish());

Both frames use the world's configured timestep. A sphere falling onto the floor can be below the selection threshold on the first frame and above it after the bounce on the second. Each selection contains the first count IDs in source order. The graph reads the updated centers directly from the solver's GPU storage.

For a command graph that already uses the world's buffers directly, call commandGraph.add(world). Both APIs expand the same solver passes. gpuAdvanceSpheres remains available for constant-velocity motion.

The graph manages the intermediate above flags. After submission, destroy both prepared executions and the encoder. Destroy each frame's selected and count vectors after consuming them, and destroy the program when finished.

Migrating constructor-based programs​

Add definitions and props to a graph or scope. Use scopes to group operations for reuse or control flow. Keep operation IDs to preserve their names in diagnostics.

Deprecated constructorDefinition
GPUCompositeOperationgraph.add(graph.createScope({id}).add(definition, props))
GPUConditionalOperation, GPULoopOperationgraph.if(), graph.loop()
GPUGraphScalarLiteral, GPUGraphScalarOperationgpuScalarLiteral, then choose gpuScalarArithmetic or gpuScalarCompare for the operator
GPUGraphSpMV, GPUGraphVectorMADD, GPUGraphDotProductgpuSparseMatVec, gpuMultiplyAdd, gpuDotProduct
GPUGraphGroupAggregation, GPUGraphReductiongpuGroupAggregate, gpuReduce
GPUUploadOperation, GPUCopyOperation, GPUCompactionOperationgpuUpload, gpuCopy, gpuCompact
GPUExpressionOperation, GPUCPUOperationgpuExpression, cpuCallback
GPUCommandOperation, GPURenderOperation, GPUFullscreenDrawOperationgpuCommand, gpuRender, gpuDrawFullscreen