{"slug": "native-computational-graph-engine", "title": "Native Computational Graph Engine", "summary": "ZGC, an ahead-of-time tensor graph compiler written in Zig by developer krypticlogan, lowers a statically defined graph architecture into a specialized Zig type with an inline memory plan before the program runs, eliminating runtime graph interpretation and graph-level operation dispatch. The project requires Zig 0.17.0, is installed via `zig fetch --save git+https://github.com/krypticlogan/zig-graph-compiler`, and targets dense neural network inference, iterative solvers, DSP, image analysis and cellular automata; its author reports that in selected benchmarks ZGC-generated executables perform close to equivalent handwritten Zig implementations, with performance varying by graph structure, execution plan and hardware. The author warns that ZGC is under active development and that public APIs and compiled-model contracts should be expected to change before a stable release.", "body_md": "ZGC is an **ahead-of-time tensor graph compiler** written in Zig that generates statically planned, allocation-free runtimes.\n\nUsing Zig's `comptime`,\na graph architecture is defined,\nlowered and optimized to a fixed execution graph,\nassigned an inline memory plan,\nand emitted as a specialized type all before the real program ever executes.\n\nCompiled executables are validated and contain specialized execution logic directly, eliminating runtime graph interpretation. Graph traversal, tensor ranks, shapes, dtypes, layouts, and kernel selection are compile-time-known.\n\nThe project requires Zig 0.17.0.\n\nAny statically defined numerical pipeline. This includes, but is not limited to:\n\n- Inference on dense neural network graphs\n- Iterative mathematical solvers (physics simulations)\n- Audio analysis (digital signal processing)\n- Image analysis\n- Cellular automata or other rule-based simulations\n\nSpecialized for:\n\n- High visibility and control\n- Cross-compilation (thanks Zig)\n- Entirely static execution\n- No runtime graph interpretation or graph-level operation dispatch\n\nZGC provides a common static graph representation for these workloads; passing optimization off to the compiler instead of handwriting these pipelines.\n\nIn selected benchmarks, ZGC-generated executables perform close to equivalent handwritten Zig implementations. Performance varies with graph structure, selected execution plan, and hardware.\nExamples exist in the [examples](https://github.com/krypticlogan/zig-graph-compiler/blob/master/examples) directory.\n\nCheck them out and build locally if you prefer to see it in action.\n\n## conways-gol-demo.mp4\n\n## mnist-digit-demo.mov\n\nIn a Zig project directory:\n\n```\nzig fetch --save git+https://github.com/krypticlogan/zig-graph-compiler\n```\n\nAdd to your build.zig and add the ZGC module as an import to your own:\n\n``` js\nconst zgc_dep = b.dependency(\"zgc\", .{\n    .target = target,\n    .optimize = optimize,\n});\nconst zgc_mod = zgc_dep.module(\"zgc\");\n\nexe.root_module.addImport(\"zgc\", zgc_mod);\n```\n\nImport normally.\n\nNote\n\nZGC is under active development. Public APIs and compiled-model contracts should be expected to change before a stable release.\n\n`DefinitionBuilder` is the public model-building surface. Source keys and tensor\nvalues are concrete types.\n\n``` js\nconst std = @import(\"std\");\nconst zgc = @import(\"zgc\");\n\nconst Sources = enum(usize) { input, weights }; // user-defined source keys\nconst Definition = zgc.DefinitionBuilder;\n\nfn define(builder: *Definition) void { // complete graph architecture is defined here\n    const sources = builder.sources(Sources);\n    const input = sources.input(.input, .f32, &.{ 4, 8 });\n    const weights = sources.parameter(.weights, .f32, &.{ 8, 16 });\n    builder.output(\n        builder.relu(\n            builder.matmul(input, weights)\n        )\n    );\n}\n\nconst definition = blk: {\n    var builder = Definition.init();\n    define(&builder);\n    break :blk builder.finish();\n};\n\nconst MyExecutable = definition.executable(); // graph is lowered to a specialized Zig type\n\npub fn main() !void {\n    var runtime = MyExecutable.Runtime.init();\n\n    const input_values: [4 * 8]f32 = @splat(1);\n    const weight_values: [8 * 16]f32 = @splat(0.25);\n    try runtime.copyInput(.input, &input_values);\n    try runtime.copySource(.weights, &weight_values);\n    runtime.run();\n\n    const output = runtime.outputView(0);\n    std.debug.print(\"shape={any} data={any}\\n\", .{ output.shape, output.storage });\n}\n```\n\n`executableWith` chooses from the compiler's retained executable frontier at\ncompile time. The default target is `balanced`:\n\n``` js\nconst FastExecutable = definition.executableWith(.{ .target = .fast });\nconst MemoryExecutable = definition.executableWith(.{ .target = .memory });\nconst SmallExecutable = definition.executableWith(.{ .target = .small });\nconst ForcedExecutable = definition.executableWith(.{ .frontier_index = 0 });\n```\n\n`fast` minimizes estimated runtime work\n\n`memory` minimizes planned peak model buffer space\n\n`small` minimizes estimated generated-code units\n\n`balanced` combines runtime, peak memory, and code-size ratios with a 3:1:1 weighting\n\nThese are compile-time estimates; `small` does not measure the linked binary.\nAn explicit `frontier_index` overrides the target and fails compilation if the\nindex is outside the retained frontier. Inspect\n`Executable.executable_candidate_frontier` and\n`Executable.selected_executable_candidate_index` to choose an index. The frontier\nretains distinct implementations for explicit selection, including some that\nlose on every current cost metric, and holds at most 16 candidates. Source\nbindings can be supplied in the same options value with `.sources = &.{...}`.\n\nZGC provides tooling for compilation, inspection, and runtimes outside of Zig.\n\nTo install the CLI, first run `zig build -Doptimize=ReleaseFast` from the project root. This will install the CLI executable titled `zgc` to zig-out.\nFinally, add the directory containing `zgc` to your system PATH and invoke the CLI with `zgc`.\nThe CLI provides:\n\n| Instruction | Description | \n|---|---|\n| `compile <.zgir or graph.zig> <options>` | Compile graph definitions to a target artifact. Options for output and compilation. | \n| `time <executable-library> <options>` | Time a compiled & lowered runtime. Options to configure timing and output. | \n| `inspect <executable-library> <options>` | Inspect artifacts (artifact provided must be compiled using the `--inspectable` flag). | \n| `cache <options>` | Inspect configured cache path or clear it. | \n\nPython bindings exist for both executable building (`zgc-compiler`) and runtimes (` zgc-runtime`).\nSeparate Python libraries are maintained, but the compiler module depends on the runtime module.\n\nUse `zgc-compiler` to build graphs in Python, just as you would in Zig. Use `zgc-runtime` to load and execute them.\n\nUse pip to install either Python package:\n\n`pip install zgc-runtime` -- install just the runtime, for pre-compiled binaries\n\n`pip install zgc-compiler` -- installs both the runtime and compilation mechanisms\n\nA C ABI is provided for runtime loading of executables in languages besides Zig.\n\nZGIR (.zgir) is ZGC's serialized graph representation, allowing external frontends to compile graphs through the same backend as native Zig definitions. Read more about it here ([ZGIR](https://github.com/krypticlogan/zig-graph-compiler/blob/master/docs/zgir.md)).\n\nOther languages can integrate with ZGC by translating their graph definitions into ZGIR and compiling those representations through the CLI.\n\n- Front-facing `DefinitionBuilder` with enum-indexed sources composes graphs.\n- Fluent expressions chain operations from `builder.expr(value)` .\n- Arbitrary composite expression functions can be applied with typed arguments for reusable graph-level operations.\n- `definition.executable()` constructs, validates, and lowers\nthe definition to a complete executable type with a runtime.\n- Reusable, lifetime-planned runtime memory.\n- Multiple graph inputs, parameters, constants, and outputs.\n- Source-free scalar literals and zero-stride filled tensors.\n- `f32` ,`f16` ,`i8` , and strict boolean tensor dtypes.\n- Unary math, arithmetic, comparison, logical, selection, matmul, reduction, softmax, and concatenation primitives.\n- Explicit copy and row-major contiguous materialization.\n- Transpose, permutation, reshape, flatten, squeeze, unsqueeze, and static slicing view operations.\n- Trailing-axis broadcasting for binary arithmetic and compile-time single- or multi-axis reductions.\n- SIMD fast paths for contiguous kernels and generic strided traversal.\n- Graph-level fusion and traversal planning across compatible operations.\n- Compile-time layout and execution-plan selection.\n- Search-based compilation pipeline, and explicit control over executable selection.\n- Retained executable plans that can be selected for lowering at compile-time.\n- Core-backed extensions and abstractions like `nn` and`img` .\n- Operation and generated-model benchmarks, plus standalone example packages.\n- Lean binaries and first-class inspection for any compiled tensor graph.\n- C ABI for using pre-compiled models external to Zig.\n- Reusable Python bindings that dynamically load any compatible model artifact.\n- CLI tooling for graph compilation, executable inspection, and cache management.\n\nSee [development state](https://github.com/krypticlogan/zig-graph-compiler/blob/master/docs/development-state.md) for precise limitations and\n[architecture](https://github.com/krypticlogan/zig-graph-compiler/blob/master/docs/architecture.md) for the compilation pipeline.\n\n`zgc.ext.nn` composes higher-level layers through `DefinitionBuilder`\n\n``` js\nconst Dense = zgc.ext.nn.Dense(Sources);\nconst Classifier = zgc.ext.nn.Sequential(&[_]Dense{\n    .{ .weights = .w1, .bias = .b1, .output_size = 16, .activation = .relu },\n    .{ .weights = .w2, .bias = .b2, .output_size = 10, .activation = .softmax },\n});\n\nconst input = builder.input(.input, .f32, &.{ batch_size, input_size });\nbuilder.output(Classifier.apply(builder, input));\n```\n\nDense weights use logical `[input, output]` storage by default. Set\n`.weight_layout = .output_input` for sources stored as `[output, input]`; the\nlayer adds an aliasing transpose before matmul.\n\n`zgc.ext.img.Dimensions` defines channel-first or channel-last rank-4 shapes,\nand `zgc.ext.img.input` declares a core graph input with that convention.\n\nSources use runtime-owned storage by default. Runtime inputs can be copied into\nthat storage with `copyInput`, while owned parameters and constants use the\ntyped `copySource` API shown above.\n\nParameters and constants may instead be embedded directly into the program:\n\n``` js\nconst EmbeddedExecutable = definition.executableWith(.{ .sources = &.{\n    .{ .source = .weights, .binding = zgc.memory.Source.embed(@embedFile(\"weights.bin\")) },\n} });\n```\n\nThe required byte length is derived from the source tensor's compile-time dtype and shape and checked during compilation.\n\n`Source.embed` accepts raw logical\nrow-major, native-endian tensor data and packs it at compile time when lowering\nselects another physical layout.\n\n`Source.embedPacked` accepts bytes already in the layout reported by `Executable.Runtime.sourceLayout`.\n\nEmbedded values remain read-only and do not receive a region in the runtime's mutable memory plan.\n\nInputs can also borrow caller-owned runtime storage without a copy:\n\n``` js\nconst BorrowingExecutable = definition.executableWith(.{ .sources = &.{\n    .{ .source = .input, .binding = zgc.memory.Source.bound },\n    .{ .source = .weights, .binding = zgc.memory.Source.embed(@embedFile(\"weights.bin\")) },\n} });\n\nvar runtime = BorrowingExecutable.Runtime.init();\ntry runtime.bindInput(.input, runtime_values);\nruntime.run();\n```\n\nThe bound slice must:\n\n- use the physical order reported by `BorrowingExecutable.Runtime.sourceLayout(.input)`\n- remain alive and unchanged while `run()` is executing.\n\nIt may be updated or rebound between runs. `copyInput` accepts logical\nrow-major values and packs them when lowering selects another layout.\n\nUnspecified sources use runtime-owned storage, so `definition.executable()` is\nequivalent to an all-owned source plan.\n\nOutputs can borrow caller-owned writable storage as a group:\n\n``` js\nconst Executable = definition.executableWith(.{\n    .outputs = zgc.memory.Output.bound,\n});\nvar runtime = Executable.Runtime.init();\ntry runtime.bindOutput(0, output_values);\nruntime.run();\n```\n\nEvery output must be bound before `run()` in this mode. Input binding is\nindependent. Bound output buffers use the compiled physical layout reported by\n`Executable.Runtime.outputLayout(index)` and may be rebound between runs.\nOutputs must have distinct computed storage roots; use `copy` or `contiguous`\nto materialize an aliasing output first.\n\nRun the entire test suite and check the build.\n\n```\nzig build test\nzig build check\n```\n\nThe test suite contains important invariants for regression tracking and numerical validation.\n\nNew operations or graph-level intermediates should be tested and verified.\n\nThe library provides benchmarks at 2 levels.\n\nAs a part of the ZGC build system the benchmark step is retained as a way to track ZGC implementations versus handwritten equivalents. Additionally, it serves as the timing and performance check for compiler-level regressions.\n\nTo use it, run `zig build benchmark -Dbenchmark=<workload> -Doptimize=ReleaseFast` from the ZGC root.\n\nTo benchmark pre-compiled executables, use the `zgc time` interface.\n\n```\nzgc compile graph.zgir -O ReleaseFast --time -o graph.dylib\nzgc time graph.dylib\n```\n\nAppend timing records to a JSON file:\n\n```\nzgc time graph.dylib --out benchmarks/results.json\n```\n\nSee the [benchmark workloads](https://github.com/krypticlogan/zig-graph-compiler/blob/master/benchmarks/README.md) for retained reference\ngraphs and timing notes.\n\nThis project is AI-assisted and LLMs have been used in this codebase to generate documentation, test implementations, and largely as a discussion and unblocking tool. Any AI-generated code is reviewed and revised before being treated as solved.\n\nAny and all contributions should be human-reviewed at some level.\n\n| Path | Purpose | \n|---|---|\n| `src/zgc/frontend/` | Public definition types and the typed graph-building surface | \n| `src/zgc/compiler/` | Construction, validation, analysis, optimization, planning, scheduling, and executable search | \n| `src/zgc/core/` | Graph, tensor/view, model, and inspection structures | \n| `src/zgc/execution/` | Executable programs, kernel plans, and dispatch | \n| `src/zgc/operations/` | Semantic operation definitions and reusable operation-family descriptors | \n| `src/zgc/kernels/` | Elementwise, reduction, contraction, layout, and special kernels | \n| `src/zgc/storage/` | Dtypes, source policies, and memory planning | \n| `src/cli/` | Executable-specific command-line entry points | \n| `src/artifact/` | Generated-model artifact entry points | \n| `src/extensions/` | Optional domain abstractions exported through `zgc.ext.nn` and`zgc.ext.img` | \n| `bindings/` | Reusable host-language bindings for generated model artifacts | \n| `tests/` | Compile-time graph, runtime model, validation, view, and kernel coverage | \n| `benchmarks/` | Reference graph workloads and direct implementations | \n| `examples/` | Standalone model definitions, interactive applications, inspection, and artifact analysis | \n| `playground/` | Standalone scratch package for graph construction, execution, testing, inspection, and disassembly | \n| `docs/` | Architecture, design constraints, capabilities, and limitations |", "url": "https://wpnews.pro/news/native-computational-graph-engine", "canonical_source": "https://github.com/krypticlogan/zig-graph-compiler", "published_at": "2026-11-26 08:19:11+00:00", "updated_at": "2026-11-26 08:42:26.573625+00:00", "lang": "en", "topics": ["developer-tools", "ai-infrastructure", "machine-learning", "artificial-intelligence"], "entities": ["ZGC", "Zig", "krypticlogan", "DefinitionBuilder", "GitHub"], "also_reported_by": [], "takeaway": "ZGC compiles a graph defined with DefinitionBuilder into a specialized Zig type whose ranks, shapes, dtypes, layouts and kernel selection are fixed at compile time, and executableWith selects among .fast (minimizes estimated runtime work), .memory (minimizes planned peak buffer space) and .small tar", "recommendation": null, "alternates": {"html": "https://wpnews.pro/news/native-computational-graph-engine", "markdown": "https://wpnews.pro/news/native-computational-graph-engine.md", "text": "https://wpnews.pro/news/native-computational-graph-engine.txt", "jsonld": "https://wpnews.pro/news/native-computational-graph-engine.jsonld"}}