Build a Cache-Aware DAG Format for GPU Test Pipelines
System DesignModel answerLast updated
Design a DAG-based intermediate representation for GPU test pipelines and explain how to compile it into a cached, incremental, deterministic plan that survives schema changes.
Your team runs automated graphics validation: compiling shaders, building driver or toolchain artifacts, rendering scenes on specific GPUs, comparing output against reference images, and measuring performance. Many teams author these pipelines, and the definitions must keep working as tooling changes.
Design an intermediate representation (IR) that describes such a pipeline as a directed acyclic graph, and explain how a compiler turns it into an executable plan.
Your answer should cover:
- Graph model: the node kinds and edge kinds, and what metadata each carries (resources, timeouts, tolerances, ownership).
- Side effects: how the IR represents pure steps, external reads, exclusive resources such as GPU leases, nondeterministic steps, and external writes such as publishing results.
- Compilation: the stages that take the IR to an executable plan, including validation and normalization.
- Caching: how results are identified and reused.
- Incremental rebuilds: how a small change triggers only the work it must.
- Deterministic ordering: how identical inputs always yield identical schedules.
- Versioning: how the format evolves without breaking existing pipeline files.
State your scale assumptions, for example the number of nodes per run, the number of machines, and the fraction of the graph touched by a typical change. Discuss trade-offs and failure modes.
Hints
Hint 1
Make the identity of every node a content hash of its operation, parameters, input digests and relevant environment. Caching, incremental rebuilds and stable ordering all follow from that.
Hint 2
Give each node an explicit effect class (pure, reads external state, acquires a resource, nondeterministic, writes externally). The compiler can then decide what is cacheable, retryable or must be fenced.
Hint 3
For deterministic ordering, use a topological sort with a priority queue keyed on (priority, stable id). For incremental builds, think about early cutoff: if a rebuilt node's output digest is unchanged, its dependents stay clean.
Hint 4
For schema evolution, put a version in every file, keep changes additive where possible, and ship automated upgraders that migrate old files to the current form before compilation.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarify scope and assumptions
Workloads: shader compilation, toolchain builds, rendering on specific GPUs, golden-image comparison, perf benchmarks, result publishing.
Assumed scale: roughly 50k nodes per nightly run, about 2k GPU machines across about 20 SKUs, and per-commit runs touching 1-5% of the graph.
Goals: reproducible results, minimal recomputation, identical schedules for identical inputs, and long-lived pipeline files authored by many teams.
The central idea is to separate pure computation from effects and make node identity content-addressed. Caching, incrementality and determinism then follow almost for free.
IR structure
A workflow document holds a schema_version, a list of nodes, a list of edges and defaults (timeout, retries, environment).
Nodes have an op, an op_version, typed parameters, typed input and output ports, a resource request and an effect declaration.
| Op | Effect class |
|---|---|
fetch_source | external read, pure once pinned to a revision digest |
build, compile_shader | pure and hermetic |
provision_gpu | acquires an exclusive resource (lease) |
render | runs on GPU, may vary in timing and low-level bits |
image_compare | pure, uses a tolerance such as PSNR >= 45 dB |
perf_measure | nondeterministic, not cached by default |
publish | external write |
Additional metadata: owner, tags, timeout, retries, resources (for example gpu_arch, vram_gb, exclusive) and a tolerance spec, because GPU output may differ bitwise across drivers.
Edges come in two kinds:
- Data edges link
(node, out_port)to(node, in_port)and carry typed artifacts (blob, image, shader binary, lease, metrics). Port types are checked at compile time. - Order edges mean "run after" without data flow. Use them sparingly, since they usually signal an unmodeled effect.
Resource contention is deliberately not an edge. It is a scheduling constraint derived from resource requests. Modeling it as edges would over-serialize the graph.
Effect model
Pure: output depends only on inputs. Cacheable and freely retryable.ReadsWorld: for example network fetches. Becomes pure after pinning (branch to commit digest).AcquiresResource: yields a linear token such as a device lease, which must be released and held by one consumer if exclusive.Nondeterministic: runs every time, or is cached only with an explicit TTL and a stale marker.WritesWorld: publish or file-a-bug. Never cached, executed at most once per plan, guarded by idempotency keys.
Compilation pipeline
- Validate. Detect cycles (three-color DFS), check port types, check required inputs are connected, check resource requests match known SKUs. Reject any
WritesWorldoutput feeding aPurenode, since it would break cache semantics. - Normalize. Expand matrix nodes (for example
render x {ada, hopper} x {driver A, driver B}becomes four nodes), apply defaults, and pin floating references (branch to commit, "latest" to an exact version). After this the plan is a pure function of the IR and pinned inputs. - Assign stable IDs and cache keys. IDs are content hashes, not positions, so reordering a file or renaming does not change scheduling.
action_key(n) = H(op, op_version, canonical_params(n),
sorted(input_digests), env_fingerprint(n))
The environment fingerprint includes only what affects output: toolchain digest, driver version, GPU architecture, OS image. Exclude irrelevant data like hostnames.
- Order deterministically. Run Kahn's algorithm with a min-heap on
(priority, stable_id).
import heapq
from collections import defaultdict
def deterministic_order(nodes, edges, priority):
indeg = {n: 0 for n in nodes}
succ = defaultdict(list)
for s, d in edges:
succ[s].append(d)
indeg[d] += 1
heap = [(priority.get(n, 0), n) for n, k in indeg.items() if k == 0]
heapq.heapify(heap)
order = []
while heap:
_, n = heapq.heappop(heap)
order.append(n)
for m in succ[n]:
indeg[m] -= 1
if indeg[m] == 0:
heapq.heappush(heap, (priority.get(m, 0), m))
if len(order) != len(indeg):
raise ValueError("cycle detected")
return order
Complexity is O((V + E) log V). Parallel execution may reorder independent nodes at runtime, but result determinism comes from pure nodes, explicit seeds as parameters, and aggregating outputs sorted by stable ID. Plan and log determinism come from this ordering.
Caching
Use a content-addressed store with two layers: an action cache (action_key to output digests) and a blob store (digest to bytes). Pure and pinned-read nodes are always cacheable; nondeterministic nodes are skipped or TTL-bound; write nodes are never cached. Golden images also live in the store, so updating a golden is just a new digest flowing along edges.
Remote cache considerations: authenticate writers, so a bad worker cannot poison shared entries, and verify digests on read.
Incremental rebuilds
- Recompute keys from the changed leaves downward.
- A node is dirty only if its key misses the cache.
- Early cutoff: if a rebuilt node yields the same output digest as before, dependents keep their keys and stay clean. A comment-only shader edit produces identical bytecode, so no GPU time is spent.
- Target pruning: schedule only ancestors of requested outputs.
With a 1-5% touched fraction, most of the 50k nodes should be cache hits, so planning cost is dominated by key computation, which is linear in graph size.
Scheduling notes
Resource-aware scheduling places nodes on matching SKUs, with lease acquisition and release fenced by order. Retries are safe for pure nodes; for writes, rely on idempotency keys. Flaky renders can be retried with a bounded count and flagged rather than silently cached.
Versioning and schema evolution
- Every document carries
schema_version; every op carriesop_version. Changing op semantics bumpsop_version, which changes cache keys and correctly invalidates stale results. - Prefer additive changes: new optional fields with defaults, unknown fields preserved or rejected by explicit policy.
- Provide upgraders (v1 to v2 to v3) run before validation, so the compiler only understands the latest form. Test upgraders with round-trip and golden-plan tests.
- Use semantic versioning: minor versions are backward compatible, major versions may require migration. Support N previous majors and publish a deprecation schedule.
- Canonicalize serialization (sorted keys, normalized numbers) so hashes are stable across tools and languages.
Common mistakes
- Using insertion order or file paths as identity.
- Putting hostnames, timestamps or absolute paths into cache keys.
- Modeling resource contention as edges.
- Caching nondeterministic or write nodes.
- Forgetting early cutoff, which makes small edits rebuild everything downstream.
- Changing op behavior without bumping
op_version. - Using exact image equality across GPUs instead of tolerance-based comparison.
Validation
Test with property checks: shuffling the input order yields an identical plan; no-op changes yield zero dirty nodes; cycles and type mismatches are rejected; upgraded old files compile to the same plan as hand-written new ones.