Graph inputs, results, and state
Applications declare the graph's external interface. Operations define their results and private temporaries; callers do not need to declare every intermediate value.
| Value | Declared by | Storage |
|---|---|---|
| Input | graph.addInput(name, descriptor) | Supplied for each run; read-only to operations |
| Produced result | The producing operation's contract | Allocated by execution, or a selected caller-owned output target |
| State | graph.addState(name, descriptor) | Initialized, caller-owned vector supplied for each run |
| Private command scratch | The operation's lowering | Managed by the command graph and its resource planner |
Declare the interface, add operations​
import {GPUGraph, gpuExpression} from '@luma.gl/graph/gpu-graph';
const graph = new GPUGraph();
graph.addInput('positions', {type: 'vector', format: 'float32x3'});
graph.addInput('scale', {type: 'scalar', format: 'float32'});
graph
.add(gpuExpression, {output: 'scaled', expression: 'positions * scale'})
.add(gpuExpression, {output: 'lengths', expression: 'length(scaled)'});
const compiledGraph = graph.compile(device, {outputs: {lengths: {type: 'vector', format: 'float32'}}});
const results = await compiledGraph.run({
inputs: {positions: positionsVector, scale: 2}
});
// After downstream GPU consumers finish:
results.lengths.destroy();
compiledGraph.destroy();
There are no declarations for scaled or lengths. Expressions infer their numeric formats,
component widths, and scalar/vector kinds from their inputs. Result declarations are resolved
on a compilation snapshot; compilation does not add declarations to the authored graph.
Use an inline descriptor for a single declaration. When several inputs or operations
share a format, name the descriptor and use as const to retain its literal type:
const point = {type: 'vector', format: 'float32x3'} as const;
graph.addInput('start', point);
graph.addInput('end', point);
The descriptor contains format metadata. Each addInput gives that format a name in the
graph, and each run supplies the two vectors independently. For images, see
texture values and execution bindings.
Compiler declarations such as graph.compiler.vector(name, format, ...) belong to
explicit compiler authoring. A vector's length and exact chunk boundaries normally
come from execution bindings, so the same compiled graph can run on differently sized batches.
Optional {length, chunkLengths} constraints are checked rather than used to repack inputs.
Select results and optionally supply storage​
Both GPUGraph and the reusable GPUSimpleGraph accept a map of result names to
expected descriptors. Compilation checks each name, kind and format against the resolved
declarations. Supply just the kind and format. The operation and execution bindings
determine the shape.
In the example above, TypeScript infers results.lengths as GPUVector<'float32'>.
To return CPU rows from asynchronous execution, request their location by name:
const compiledGraph = graph.compile(device, {
outputs: {lengths: {type: 'vector', format: 'float32'}},
outputLocations: {lengths: 'cpu'}
});
const {lengths} = await compiledGraph.run({inputs: {positions: positionsVector, scale: 2}});
// lengths is a CPUVector<'float32'> whose arrays can outlive the compiled graph.
compiledGraph.destroy();
A selected scalar uses a one-row vector. A texture result is a Texture | TextureView,
since an execution can supply a borrowed view as its output target. Texture outputs
require GPU residency. A literal name array such as outputs: ['lengths'] preserves the selected keys. Without a
descriptor, each handle has type GPUGraphOutput (GPUVector | CPUVector | Texture | TextureView).
A variable-length array, a tuple containing a runtime choice of names, or an implicit terminal selection returns GPUGraphOutputs. Narrow a handle
before accessing type-specific properties, or select a descriptor when its kind and format are
known. An explicit result type argument remains a caller assertion.
compile(device, {outputs: [...]}) selects which named results escape an invocation.
Unselected intermediates are owned and released by execution. When operation-defined results
are present and outputs is omitted, terminal results (those not read by another operation)
are selected. Pass outputs: [] for a state-only invocation.
const gpuResults = graph.compile(device, {outputs: {lengths: {type: 'vector', format: 'float32'}}});
const results = await gpuResults.run({
inputs: {positions: positionsVector, scale: 3},
outputTargets: {lengths: destinationVector}
});
// results.lengths === destinationVector; storage remains caller-owned.
gpuResults.destroy();
TypeScript checks target names and handle types for checked selections. CPU readback allocates its own results. Describe vector lengths and texture extents on declarations; a checked selection specifies only kind and format.
Targets must name selected produced results and match their formats, row counts, chunk boundaries, and device. They cannot replace inputs or state. Aliasing incompatible writable ranges is rejected. Without a target, returned produced vectors transfer to the caller; caller-supplied inputs, targets, and state are always borrowed.
Intermediate storage reuse​
For straight-line WebGPU GPUGraph executions, unselected operation-defined vector results
remain logical shape declarations until lowering. The command-graph planner allocates their
chunks and can reuse physical buffers when scheduled lifetimes do not overlap. Logical row
counts and exact chunk boundaries are unchanged; compatible buffers may have different formats
or capacities because each view retains its own layout and the allocation uses sufficient capacity
and the union of required usages.
All logical inputs and outputs of an operation overlap for allocation purposes, including when its lowering emits multiple passes. Reuse does not imply in-place execution. Private command scratch retains its finer command-level lifetimes. Lowerings must declare actual physical reads and writes and resolve buffers through the encoding context; they must not cache a logical intermediate's physical storage for later use. Transient contents are unspecified until written; producers must initialize all elements that consumers read, including explicit clearing before accumulation when required.
Borrowed inputs, mutable state, caller-owned targets, and selected outputs never enter this pool. Selected results keep independent storage even when another operation consumes them. Legacy explicit result declarations, control-flow graphs, scalars, and SimpleGraph retain their existing allocation behavior. Each prepared execution owns a separate pool: concurrently prepared invocations cannot reuse one another's storage. No expression fusion or cross-run pooling is introduced. Destroy the prepared execution after submission to release its scratch.
Caller-owned encoding​
Read compiledGraph.supportsCallerOwnedEncoding to choose between prepare() and run().
This boolean describes the program and backend at compilation. An invocation that supplies
a CPUVector input still requires asynchronous run(). JavaScript scalar inputs work
with either path. Binding validation and resource lifetime rules apply to both.
| Compiled program | Caller-owned encoding |
|---|---|
WebGPU GPUGraph | Supported when all stages and requested outputs are GPU-resident |
Reusable GPUSimpleGraph | Supported on WebGPU for texture-copy and fullscreen shader-pass programs |
Evaluator-backed GPUSimpleGraph | Use run(); evaluator scopes have their own submission API |
compiledGraph.prepare(bindings) binds one invocation, resolves dimensions, and allocates its
results and scratch. It does not encode commands or submit work. Each prepared execution
can be encoded once into a caller-owned encoder:
import type {CommandEncoder} from '@luma.gl/core/api';
const execution = compiledGraph.prepare({
inputs: {positions: positionsVector, scale: 2}
});
let encoder: CommandEncoder | undefined;
try {
encoder = device.createCommandEncoder();
execution.encode(encoder);
// Append other graph work or rendering that consumes execution.outputs.lengths.
device.submit(encoder.finish());
} finally {
// On failure, abandon the encoder; never submit a partially encoded invocation.
encoder?.destroy();
execution.destroy();
// This example retains no outputs, including on failure or cancellation.
execution.outputs.lengths.destroy();
}
execution.outputs is available immediately after preparation, allowing one prepared
graph's outputs to bind another graph before either is submitted. GPU contents become
available in command order. Encoding neither finishes nor submits nor destroys the encoder.
The encoder must belong to the compiled graph's device.
Keep the compiled graph, borrowed bindings, outputs, and prepared execution alive through
submission. Call execution.destroy() after submission, or after abandoning an
unsubmitted encoder. This releases invocation scratch and command resources, while preserving
outputs and borrowed inputs, state, and targets. It is idempotent. You need not wait for GPU
completion to release scratch after submission; keep outputs alive for downstream consumers.
Destroying the compiled graph prevents further preparation or encoding.
An execution cannot be encoded twice, including after a failed encoding attempt. To run again,
prepare another execution. Cancellation before encoding uses the same destroy() method;
allocated outputs still belong to the caller and must also be destroyed when unused.
await compiledGraph.run(bindings) is the convenience path over preparation, encoding, submission,
and scratch cleanup. On failure it also releases allocated outputs that it could not return;
borrowed resources survive. Its promise does not imply GPU completion.
Operation-defined results​
A custom operation can publish result declarations through its contract:
const copyContract: GPUGraphOperationContract = {
outputs: {copied: {type: 'vector', format: 'uint32x2'}},
values: [
{value: 'input', access: 'read'},
{value: 'copied', access: 'write', shape: {like: 'input'}}
]
};
outputs defines logical types; the writable use's shape describes dimensions. For dependent
types, outputs can be a pure function of logical input declarations:
const copyContract: GPUGraphOperationContract = {
outputs: ({getValue}) => ({copied: getValue('input')}),
values: [
{value: 'input', access: 'read'},
{value: 'copied', access: 'write', shape: {like: 'input'}}
]
};
Import GPUGraphOperationContract as a type from @luma.gl/graph. Output inference receives no
GPU data or device and must not allocate resources or have side effects. It may run more than
once during compilation. The operation's lowering uses the resolved names through
context.resolveVector() or context.resolveScalar() as before.
Add producers before consumers. Produced results have a single writer. A missing producer,
multiple writers, writes to inputs, and result names conflicting with inputs or state fail
at compilation. Explicit compiler declarations such as graph.compiler.vector() accept flat
execution bindings. Application declarations use grouped inputs and state bindings.
Mutable state​
const positions = graph.addState('positions', {type: 'vector', format: 'float32x3'});
An operation updating this value declares read-write, or separate read and write uses, in
its contract. It must implement safe mutation in its lowering. The state name must not also
appear in contract.outputs, which is reserved for produced results.
await compiledGraph.run({
inputs: {deltaTime: 1 / 60},
state: {positions: positionsVector}
});
Supply initialized state on every invocation. Reusing the same vector preserves its contents across runs; rebinding a different initialized vector starts from that vector's contents. The compiled graph does not retain or destroy these plain state bindings. A selected state output is the same borrowed vector, not transferred ownership.
State currently requires vector storage. Represent a single mutable GPU element as a vector
with {length: 1}; a scalar remains a host numeric input or an operation-produced
scalar result, not a persistent GPU scalar binding. Expressions cannot write directly to
state. Use graph.add(gpuCopy, {input: 'nextPositions', target: 'positions'}) after producing
an expression result.
For independent owned copies and explicit reset/cleanup, use
compiledGraph.createState(bindings, {copy: true}) and pass the resulting GPUGraphState as state.
Borrowing remains the default.
See Mutable graph state for initialization, reset, ownership, and
caller-owned encoding examples.
Backend and allocation boundaries​
GPUSimpleGraph supports the same addInput, inferred expression results, and grouped input
bindings on WebGL and WebGPU. Its reusable expression path rejects state declarations and
custom lowerings explicitly. Its existing evaluator-backed APIs remain unchanged.
Graph preparation supports fixed sizes and sizes derived from execution bindings or preceding
operation results whose dimensions are already known to the CPU. shape: {like: input}
preserves exact chunk boundaries; {length, chunkLengths?} specifies fixed dimensions.
Compaction supports capacity/count pairs with a separate GPU logical count. Exact-size allocation after readback and staged execution are not automatic. If dimensions cannot be determined from a contract, declaration, or supplied target, preparation fails instead of guessing a capacity. New operation-defined results inside conditionals/loops are also deferred; existing explicit control-flow declarations remain supported.
Use graph.compile(device).run(...) for runtime-sized results. The lower-level
GPUGraphCompiler.compile(graph, bindings) still requires concrete vector dimensions.
CPU operations and execution-sized results​
GPUGraph accepts the same GPUCPUOperation as SimpleGraph.
Callbacks return typed arrays (or explicit chunks), and execution allocates and uploads
GPUVectors using the returned row counts. Multiple outputs can have different lengths,
and lengths may change between runs without recompiling the authored graph.
CPU-containing programs use asynchronous compiledGraph.run(). GPU stages use the native
GPUGraph compiler and submit before a CPU callback reads their outputs. Downstream
stages resolve their dimensions only after the callback completes. The shared CPU executor
handles readback and uploads; it does not lower CPU work to a GPU command node.
This initial implementation supports straight-line numeric graphs with addInput() and
operation-owned vector results. Textures, state, output targets, and caller-controlled
prepare()/encoding are unsupported. GPU stages and CPU stages execute in authored order;
intermediates are retained until the invocation finishes. CPU-to-CPU chains retain CPU results without transfers. Only one CPU-containing invocation may run at a time
per compiled graph, and destroying it while a callback is pending is rejected.
Selected results belong to the caller. Failures release invocation-owned intermediates, preserve borrowed inputs, and allow subsequent runs. GPU-only programs retain their existing preparation, transient allocation, and encoding behavior.
CPUVector bindings and lazy transfers​
Reusable numeric GPUGraph and GPUSimpleGraph programs accept CPUVector inputs alongside
GPUVector inputs. Declarations keep the same vector format and shape contract.
Select the expected descriptor in outputs and set outputLocations: {result: 'cpu'} to
infer a CPUVector of that format. Omitted numeric output locations return GPUVectors.
CPU callback results remain in CPU memory until a GPU consumer or GPU output needs them. GPU results are read back only for CPU consumers or CPU outputs. Each invocation caches both representations, sharing an upload or readback across branches. Caches do not survive a run. CPU input buffers are borrowed and must remain unchanged until the run settles. Callback input arrays remain read-only snapshots; array-returning callbacks remain compatible.
This first version supports portable float32, sint32 and uint32 rows with one to four components. Chunk boundaries are preserved and strided CPU inputs are packed explicitly by the executor. Nested lists, validity metadata, textures, state, output targets, and caller-owned encoding are outside the CPU residency path. Returned CPU vectors retain their arrays without requiring destroy(); returned GPU vectors follow the usual caller-owned lifetime.
Arrow adapters and explicit topology-preserving transfers​
makeCPUVectorFromArrow(vector) and makeArrowVectorFromCPUVector(vector) from
@luma.gl/graph/arrow convert numeric rows and one-level lists of numeric coordinate tuples.
They preserve chunk boundaries and parent-row validity. Arrow slices normalize their validity
and list offsets; compatible numeric payloads remain borrowed. Strided or unaligned CPU
payloads are packed when Arrow requires contiguous aligned storage. Nullable nested child
values and deeper list nesting are unsupported.
makeGPUVectorFromCPUVector(device, vector) and asynchronous
makeCPUVectorFromGPUVector(vector) from @luma.gl/graph/gpu-data perform explicit transfers
that preserve format, row count, flattened count, list offsets, validity, and chunk boundaries.
GPU results own their uploaded buffers. CPU readback owns its returned arrays. Metadata is
copied so callers can retain source vectors independently. These helpers do not expand the
portable numeric graph callback contract to list data.
projectCPUVector(vector, projection) from @luma.gl/graph/gpu-project-geoarrow projects Float32 xy/xyz
coordinates while preserving single-level list topology and validity. Null rows are skipped.
tessellateCPUVectorPolygons(vector) handles one simple polygon ring per list row, using the
existing math.gl-backed Arrow tessellator. It returns vertex-list positions, indices and source
row IDs, preserving input chunks and null polygon rows. Holes and multipolygons require the
existing nested GeoArrow pipeline. The mesh can be uploaded through the explicit transfer
helper for use by polygon GPU models.
For polygon indices, upload with {usage: Buffer.INDEX, indexType: 'uint32'} as the third
argument to makeGPUVectorFromCPUVector.
The CPU coordinate projection and descriptor adapters are available from @luma.gl/graph/gpu-project-geoarrow without
loading Apache Arrow. makeGeoArrowColumnFromCPUVector borrows packed Float32 coordinates,
validity and list offsets directly into math.gl descriptors; strided data is packed.
makeCPUVectorFromGeoArrowColumn borrows normalized interleaved Float32 point/linestring/
multipoint descriptors. Explicit dimensions distinguish XYZ from XYM. Unsupported nested,
sliced-offset, separated or nullable-child layouts are rejected rather than flattened.
tessellateGeoArrowColumnToCPUVectors(column, options) accepts full math.gl GeoArrow columns,
including polygon holes and multipolygons, and forwards resource limits. It calls math.gl directly.
Math.gl still materializes geometry rows
internally. Full geometry nesting remains in GeoArrow descriptors rather than CPUVector.
Layer-facing coordinate projection graph​
CoordinateProjectionGraph from @luma.gl/graph/gpu-project-graph is a reusable point
coordinate pipeline. Construct it with a device and {format: 'float32x2' | 'float32x3', projection} using a prepared math.gl transform. run(cpuVectorOrGPUVector) borrows its input
and returns {positions, destroy()}. Every invocation owns an independent projected GPUVector;
release it after rendering consumers finish. Destroying the compiled graph does not release
previously returned results. The layer can reuse the graph for data updates, including changes
in row count and chunking. Construct a new graph when its projection changes.
projectArrowCoordinates(graph, arrowVector) from @luma.gl/graph/arrow adapts Arrow coordinate
chunks into this same graph. GPUVector-native layers call graph.run() directly. Both paths
share CPU projection, lazy transfer, validation, and result ownership. This first layer-facing
API supports non-null packed numeric point rows. Filter null points and expand/handle list
geometry explicitly before this boundary; path/polygon graph operations remain follow-up work.