evoxc 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. evoxc/CONTEXT.md +255 -0
  2. evoxc/__init__.py +301 -0
  3. evoxc/backends/CONTEXT.md +196 -0
  4. evoxc/backends/__init__.py +133 -0
  5. evoxc/backends/adapters/CONTEXT.md +226 -0
  6. evoxc/backends/adapters/PER-ADAPTER-NOTES.md +238 -0
  7. evoxc/backends/adapters/__init__.py +53 -0
  8. evoxc/backends/adapters/_mlir_bindings.py +78 -0
  9. evoxc/backends/adapters/_pjrt_c_api.py +818 -0
  10. evoxc/backends/adapters/iree.py +3200 -0
  11. evoxc/backends/adapters/tvm.py +480 -0
  12. evoxc/backends/adapters/tvm_util.py +880 -0
  13. evoxc/backends/adapters/xla.py +1412 -0
  14. evoxc/backends/adapters/xla_util.py +1466 -0
  15. evoxc/backends/backend.py +207 -0
  16. evoxc/backends/compiler.py +612 -0
  17. evoxc/backends/external_split.py +787 -0
  18. evoxc/backends/external_validate.py +350 -0
  19. evoxc/backends/inline.py +500 -0
  20. evoxc/backends/numpy/CONTEXT.md +132 -0
  21. evoxc/backends/numpy/__init__.py +445 -0
  22. evoxc/backends/numpy/collectives.py +66 -0
  23. evoxc/backends/numpy/exec_context.py +55 -0
  24. evoxc/backends/numpy/inline.py +20 -0
  25. evoxc/backends/numpy/interpreter.py +504 -0
  26. evoxc/backends/numpy/kernels/__init__.py +117 -0
  27. evoxc/backends/numpy/kernels/collective.py +188 -0
  28. evoxc/backends/numpy/kernels/control_flow.py +138 -0
  29. evoxc/backends/numpy/kernels/custom.py +245 -0
  30. evoxc/backends/numpy/kernels/elementwise.py +329 -0
  31. evoxc/backends/numpy/kernels/indexing.py +386 -0
  32. evoxc/backends/numpy/kernels/linalg.py +612 -0
  33. evoxc/backends/numpy/kernels/random.py +634 -0
  34. evoxc/backends/numpy/kernels/reductions.py +198 -0
  35. evoxc/backends/numpy/kernels/sorting.py +97 -0
  36. evoxc/backends/numpy/kernels/sparse.py +1209 -0
  37. evoxc/backends/numpy/kernels/structural.py +145 -0
  38. evoxc/backends/numpy/shapes.py +129 -0
  39. evoxc/backends/options.py +190 -0
  40. evoxc/backends/program.py +379 -0
  41. evoxc/backends/registry.py +101 -0
  42. evoxc/backends/stablehlo/CONTEXT.md +288 -0
  43. evoxc/backends/stablehlo/EMISSION-NOTES.md +309 -0
  44. evoxc/backends/stablehlo/__init__.py +183 -0
  45. evoxc/backends/stablehlo/eigh_batched.py +649 -0
  46. evoxc/backends/stablehlo/ops.py +376 -0
  47. evoxc/backends/stablehlo/random_export.py +1445 -0
  48. evoxc/backends/stablehlo/split_reduce.py +801 -0
  49. evoxc/backends/stablehlo/writer.py +4896 -0
  50. evoxc/block/CONTEXT.md +280 -0
  51. evoxc/block/__init__.py +25 -0
  52. evoxc/block/decl.py +561 -0
  53. evoxc/block/errors.py +24 -0
  54. evoxc/block/op.py +473 -0
  55. evoxc/block/registry.py +82 -0
  56. evoxc/block/rules.py +429 -0
  57. evoxc/build_cache.py +429 -0
  58. evoxc/core/CONTEXT.md +74 -0
  59. evoxc/core/__init__.py +170 -0
  60. evoxc/core/device.py +379 -0
  61. evoxc/core/dim.py +306 -0
  62. evoxc/core/dtypes.py +93 -0
  63. evoxc/core/errors.py +84 -0
  64. evoxc/core/spec.py +69 -0
  65. evoxc/core/symbolic.py +279 -0
  66. evoxc/core/tensor.py +804 -0
  67. evoxc/core/tree.py +592 -0
  68. evoxc/dist/CONTEXT.md +155 -0
  69. evoxc/dist/__init__.py +49 -0
  70. evoxc/dist/_op_utils.py +271 -0
  71. evoxc/dist/collectives.py +337 -0
  72. evoxc/dist/context.py +216 -0
  73. evoxc/dist/group.py +148 -0
  74. evoxc/external.py +578 -0
  75. evoxc/external_rules.py +509 -0
  76. evoxc/io.py +439 -0
  77. evoxc/ir/CONTEXT.md +330 -0
  78. evoxc/ir/__init__.py +129 -0
  79. evoxc/ir/block.py +75 -0
  80. evoxc/ir/builder.py +759 -0
  81. evoxc/ir/effects.py +30 -0
  82. evoxc/ir/function.py +59 -0
  83. evoxc/ir/inference.py +1928 -0
  84. evoxc/ir/location.py +37 -0
  85. evoxc/ir/module.py +76 -0
  86. evoxc/ir/op.py +130 -0
  87. evoxc/ir/op_defs/__init__.py +180 -0
  88. evoxc/ir/op_defs/collective.py +233 -0
  89. evoxc/ir/op_defs/control.py +218 -0
  90. evoxc/ir/op_defs/elementwise.py +203 -0
  91. evoxc/ir/op_defs/linalg.py +270 -0
  92. evoxc/ir/op_defs/random.py +266 -0
  93. evoxc/ir/op_defs/reduction.py +136 -0
  94. evoxc/ir/op_defs/sorting.py +92 -0
  95. evoxc/ir/op_defs/sparse.py +320 -0
  96. evoxc/ir/op_defs/structure.py +307 -0
  97. evoxc/ir/printer.py +233 -0
  98. evoxc/ir/region.py +58 -0
  99. evoxc/ir/serialize.py +901 -0
  100. evoxc/ir/types.py +114 -0
  101. evoxc/ir/value.py +110 -0
  102. evoxc/ir/verify.py +819 -0
  103. evoxc/ir/version.py +13 -0
  104. evoxc/numpy/CONTEXT.md +128 -0
  105. evoxc/numpy/__init__.py +51 -0
  106. evoxc/numpy/_linalg.py +68 -0
  107. evoxc/numpy/_map.py +80 -0
  108. evoxc/numpy/creation.py +114 -0
  109. evoxc/numpy/elementwise.py +131 -0
  110. evoxc/numpy/linalg.py +16 -0
  111. evoxc/numpy/logic.py +69 -0
  112. evoxc/numpy/reductions.py +89 -0
  113. evoxc/numpy/shape.py +261 -0
  114. evoxc/ops/CONTEXT.md +111 -0
  115. evoxc/ops/__init__.py +118 -0
  116. evoxc/ops/_registration.py +67 -0
  117. evoxc/ops/_utils.py +517 -0
  118. evoxc/ops/comparison.py +268 -0
  119. evoxc/ops/constant.py +313 -0
  120. evoxc/ops/elementwise.py +522 -0
  121. evoxc/ops/external.py +125 -0
  122. evoxc/ops/indexing.py +725 -0
  123. evoxc/ops/linalg.py +794 -0
  124. evoxc/ops/random.py +561 -0
  125. evoxc/ops/reductions.py +250 -0
  126. evoxc/ops/sorting.py +258 -0
  127. evoxc/ops/stats.py +211 -0
  128. evoxc/ops/structural.py +511 -0
  129. evoxc/persist/CONTEXT.md +186 -0
  130. evoxc/persist/__init__.py +26 -0
  131. evoxc/persist/cache.py +271 -0
  132. evoxc/persist/codec.py +822 -0
  133. evoxc/persist/container.py +362 -0
  134. evoxc/pipeline.py +1736 -0
  135. evoxc/pipeline_options.py +252 -0
  136. evoxc/random.py +50 -0
  137. evoxc/sparse/CONTEXT.md +215 -0
  138. evoxc/sparse/__init__.py +98 -0
  139. evoxc/sparse/_utils.py +297 -0
  140. evoxc/sparse/ops.py +911 -0
  141. evoxc/sparse/rules.py +820 -0
  142. evoxc/sparse/value.py +1036 -0
  143. evoxc/trace/CONTEXT.md +429 -0
  144. evoxc/trace/__init__.py +38 -0
  145. evoxc/trace/_tree.py +278 -0
  146. evoxc/trace/builder.py +98 -0
  147. evoxc/trace/control_flow.py +946 -0
  148. evoxc/trace/defn.py +89 -0
  149. evoxc/trace/graph.py +602 -0
  150. evoxc/trace/trace.py +483 -0
  151. evoxc/transforms/CONTEXT.md +234 -0
  152. evoxc/transforms/__init__.py +58 -0
  153. evoxc/transforms/_bands.py +713 -0
  154. evoxc/transforms/_emit.py +733 -0
  155. evoxc/transforms/_merge.py +763 -0
  156. evoxc/transforms/_metadata.py +70 -0
  157. evoxc/transforms/_wrappers.py +59 -0
  158. evoxc/transforms/autodiff.py +673 -0
  159. evoxc/transforms/batch_functions.py +644 -0
  160. evoxc/transforms/batching.py +870 -0
  161. evoxc/transforms/grad.py +343 -0
  162. evoxc/transforms/jvp.py +73 -0
  163. evoxc/transforms/rules.py +953 -0
  164. evoxc/transforms/vectorize.py +388 -0
  165. evoxc/transforms/vjp.py +105 -0
  166. evoxc/transforms/vmap.py +481 -0
  167. evoxc-0.1.0.dist-info/METADATA +556 -0
  168. evoxc-0.1.0.dist-info/RECORD +170 -0
  169. evoxc-0.1.0.dist-info/WHEEL +4 -0
  170. evoxc-0.1.0.dist-info/licenses/LICENSE +201 -0
evoxc/CONTEXT.md ADDED
@@ -0,0 +1,255 @@
1
+ ---
2
+ skill:
3
+ - evoxc-vulkan-device-recipe
4
+ ---
5
+ # evoxc package — public API contract
6
+
7
+ ## Intent
8
+
9
+ The `evoxc` package — **EvoX Compiler**: a minimal, explicit, compiler-neutral tensor graph compiler and runtime.
10
+ See root `../CONTEXT.md` for the binding principles, the four-concept value-model table, the import-acyclicity contract, the error strategy, and the non-goals — all binding here.
11
+ This file owns the **public API surface** (names that must exist) and the **cross-module contracts** every submodule must honor; per-feature implementation detail lives in the child nodes listed in the routing table.
12
+ This file must stay under the ~64 KB per-file read limit — push new detail down to the owning child node instead of growing it.
13
+
14
+ Pipeline objects are distinct public types (`Defn` → `Graph` → `LoweredProgram` → `CompiledArtifact` → `Executable` → `Tensor`); no function silently consumes an earlier-stage object and performs the missing steps.
15
+
16
+ ## Public API surface (the contract — must exist, exact names)
17
+
18
+ **Staging & pipeline** (owned by `pipeline.py`):
19
+ - `@evoxc.defn` → `Defn` (calling a `Defn` with concrete tensors must raise `TraceError` directing to `trace`/`evaluate`)
20
+ - `evoxc.trace(fn_or_defn, *specs) -> Graph` (accepts nested structures of `TensorSpec` + static values)
21
+ - `evoxc.lower(graph, backend=None, **options) -> LoweredProgram`; `evoxc.compile(lowered, backend=None, **options) -> CompiledArtifact`; `evoxc.load(artifact, backend=None, device=None) -> Executable`
22
+ - `evoxc.run(executable, *args) -> outputs` (structured inputs/outputs via TreeSpec; validates static fields)
23
+ - `evoxc.bind(obj, **bindings) -> BoundExecutable|callable` (pure argument-supply sugar; validates names/dtypes/shapes/devices; never alters the graph)
24
+ - `evoxc.build(fn, *specs, backend=None, device=None, **options) -> Executable` — documented shorthand for trace→lower→compile→load
25
+ - `evoxc.evaluate(fn, *args, backend=None, device=None, **options)` — documented shorthand: derive specs → build → run (deriving a spec from a concrete tensor snapshots shape+dtype only)
26
+ - `evoxc.build_cached(fn, *specs, backend=None, device=None, cache=None, **options) -> Executable` — documented shorthand for a MEMOIZED `build` (see "Memoized build sugar" below)
27
+ - `evoxc.CompileCache` — the in-memory LRU compile cache backing `build_cached` (default `maxsize=128`)
28
+ - `Executable.synchronize()` — wait until all device work submitted by previous `run()` calls on this executable has completed; the output Tensors' values are already valid before the call (any read awaits), only their *timing* needs this. It is an EXPLICIT caller-invoked primitive — nothing in evoxc calls it implicitly and `evoxc.run` is unchanged (no per-call sync; dispatch overlap stays a feature); a backend whose `run()` already blocks (numpy, iree) needs no work here, so the method is a documented no-op on them. `BoundExecutable.synchronize()` delegates, so `evoxc.bind(...)` results expose the same call shape.
29
+ - **`build`/`evaluate`/`build_cached` env defaults** (explicit kwargs ALWAYS win; env read lazily at call time): unset `backend` from `EVOXC_BACKEND` (default `"numpy"` when unset/empty); unset `device` from `EVOXC_DEVICE` (`"kind[:index]"`, e.g. `"cpu"`/`"cuda:0"`/`"rocm:0"`/`"vulkan:0"`, parsed to `core.Device`; malformed → `DeviceError` naming the variable and value); unset `target_backends` from `EVOXC_TARGET_BACKENDS` (comma-separated), otherwise an iree-family backend (name startswith `"iree"`) infers it from the resolved device (`cuda` → `["cuda"]`, `rocm`/`hip` → `["rocm"]`, `vulkan` → `["vulkan-spirv"]`, `cpu` → `["llvm-cpu"]`). AMD ROCm devices are spelled `"rocm"` (canonical) or the accepted alias `"hip"` — both valid and equivalent, never rewritten. The explicit stage functions (`lower`/`compile`/`load`) keep their documented defaults. Implementation: `pipeline._resolve_backend_device`; regression suite `tests/pipeline_env_defaults_test.py`.
30
+ - `evoxc.io` — namespaced submodule (like `evoxc.random`, NOT flat top-level names): `evoxc.io.prefetch(host_tensor, device) -> AsyncCopy`, `evoxc.io.sink(device_tensor) -> AsyncCopy`, `evoxc.io.wait_all(timeout=None)`, class `evoxc.io.AsyncCopy` (see "evoxc.io" below)
31
+
32
+ ## Backend options override (binding)
33
+
34
+ Design principle: *"we only took care of the graph, provide a clean pipeline, and everything else should be hack-able"* — evoxc never hardcodes compiler flags users cannot override.
35
+ - **Every stage accepts options**: `lower(graph, backend=..., **options)`, `compile(lowered, backend=..., **options)`, `load(artifact, backend=..., device=..., **options)`, `run(executable, *args, **options)`, and `build`/`evaluate`/`build_cached` forward ONE options dict through every stage. Option keys are ADDITIVE (existing signatures keep working).
36
+ - **Option keys are validated by the framework; option values are the consumer's job.** Each backend/executable declares `KNOWN_OPTIONS: dict[stage, frozenset[str]]` (`lower`/`compile`/`load`/`run`); `evoxc.backends.options.validate_options` validates a caller's dict against the UNION of all stage sets — a key valid for ANY stage passes and is accepted-and-ignored at the others (so one dict can be forwarded), a key valid for NO stage raises `core.BackendError` listing the per-stage known sets. Flag/option VALUES otherwise pass through to the compiler (or, for exporter options, to the stablehlo Writer) — evoxc never parses compiler flags.
37
+ - **The only values evoxc itself validates** (`normalize_opt_level` / `normalize_bool_option` in `evoxc/backends/options.py`): `opt_level` (below), and BOOL-valued options — TYPE-COERCED to a real `bool` (real bools, ints 0/1, and `"1"/"0"/"true"/"false"/"yes"/"no"/"on"/"off"` case-insensitively; anything else → loud `BackendError` naming the option, value and accepted forms), so an env-style string like `"0"` can never hit the `bool("0") is True` trap.
38
+ - **Precedence (binding): explicit kwarg > env var > evoxc default.** Env vars are read lazily per call; empty/whitespace = unset; malformed → `core.BackendError` naming the variable and value. Env vars are stage-scoped; full table + parsers in `evoxc/pipeline_options.py`:
39
+
40
+ | Env var | Backend / stage | Option key | Value format |
41
+ |---|---|---|---|
42
+ | `EVOXC_IREE_COMPILE_ARGS` | iree / compile | `iree_compile_args` | shlex-split flag list (quoting IS processed, ≥1 flag) |
43
+ | `EVOXC_IREE_RUNTIME_ARGS` | iree / load | `iree_runtime_args` | shlex-split flag list |
44
+ | `EVOXC_IREE_VULKAN_TARGET` | iree / compile | `vulkan_target` | SPIR-V target profile string (`rdna3`, `sm_80`, `adreno`, …; whitespace-stripped — the VALUE is the compiler's to validate) |
45
+ | `EVOXC_XLA_COMPILE_OPTIONS` | xla / compile | `xla_compile_options` | base64 of serialized `xla.CompileOptionsProto` bytes |
46
+ | `EVOXC_TVM_TARGET` | tvm / compile | `tvm_target` | plain string (whitespace-stripped) |
47
+ | `EVOXC_TVM_PASS_CONFIGS` | tvm / compile | `tvm_pass_configs` | JSON object (must decode to a dict) |
48
+ | `EVOXC_OPT_LEVEL` | iree/tvm/xla / compile | `opt_level` | `'O0'`–`'O3'` (case-insensitive), `'0'`–`'3'`, or ints 0–3 (evoxc-validated value) |
49
+ | `EVOXC_EIGH_ALGORITHM` | iree/tvm/xla / lower | `eigh_algorithm` | `"jacobi"` or `"jacobi_batched"` (whitespace-stripped; VALUE validated by the Writer) |
50
+ | `EVOXC_SPLIT_REDUCTION` | iree/tvm/xla / lower | `split_reduction` | bool spellings (coerced by `normalize_bool_option`) |
51
+
52
+ - **Backend-agnostic spellings.** An option every compiler adapter accepts IDENTICALLY gets ONE `EVOXC_<OPTION>` spelling rather than one variable per backend (`EVOXC_OPT_LEVEL`, `EVOXC_EIGH_ALGORITHM`, `EVOXC_SPLIT_REDUCTION`); such a row is repeated under each adapter's `(backend, stage)` key, so `lower` carries env rows like `compile`/`load` do.
53
+ - **`opt_level` — the first-class evoxc-defined compile-stage option.** Values `'O0'`–`'O3'` (case-insensitive), `'0'`–`'3'`, or ints 0–3, normalized to 0..3 by `evoxc.backends.options.normalize_opt_level`; a bad value raises a loud `core.BackendError` naming the option and accepted forms (raw compiler flags remain pass-through). Per-adapter translation: iree derives `--iree-opt-level=N`; xla sets the `CompileOptionsProto` optimization-level field; tvm sets its build optimization level; numpy documents-ignores it. Conflict rule (binding): an explicit raw flag with the same underlying name (e.g. `--iree-opt-level=N` in `iree_compile_args`, or an already-set field in `xla_compile_options`) WINS over the derived value — never both. `evoxc.bench` defaults compiler backends to `opt_level="O3"` (env-aware, explicit wins, numpy unaffected).
54
+ - **`vulkan_target` — the SPIR-V target-profile compile-stage option.** A non-empty string deriving the iree-compile default flag `--iree-vulkan-target=<profile>`, joined into the SAME defaults list as `opt_level` so the identical conflict rule applies (a raw `--iree-vulkan-target=<p>` in `iree_compile_args` WINS — never both). UNSET derives NO flag (byte-identical existing behaviour for every target); a non-str/empty value, or a value supplied without `vulkan-spirv` in `target_backends`, raises a loud `core.BackendError`. The value itself is the compiler's to validate — evoxc never parses compiler flag values. Purpose: without a profile, `vulkan-spirv` codegen uses IREE's default `vp_android_baseline_2022` (16384-byte workgroup memory, 128 threads), which cannot compile 124M-parameter-class graphs. Env `EVOXC_IREE_VULKAN_TARGET`.
55
+ - **Reserved lower-stage exporter options** (forwarded by `CompilerBackend._exporter_options` to `evoxc.backends.stablehlo`; the framework validates KEYS, the Writer validates VALUES with a loud `BackendError` naming the accepted forms). Declared in `KNOWN_OPTIONS["lower"]` by iree (all six) and by xla/tvm (`rng_bit_generator`, `dot_precision`, `eigh_algorithm`, `split_reduction`):
56
+ - `rng_bit_generator` — bool or a collection of random algorithm names; default = the adapter's `Capabilities.rng_bit_generator` (per-call override of the native `stablehlo.rng_bit_generator` capability).
57
+ - `eigh_algorithm` — `"jacobi"` | `"jacobi_batched"`, case-insensitive, whitespace-stripped, default `"jacobi_batched"` (all mutually disjoint rotations of one odd-even round-robin round per `stablehlo.while` iteration vs `jacobi`'s single rotation per iteration, which is the plain sequential composition; batched is 65–74× faster at n=100 and 4–5.7× at n=10).
58
+ - `split_reduction` — bool, default `True`: two-stage split reductions for rank-0-result reductions (`False` = the byte-identical single-stage text; measured 7.1–8.1× on those ops).
59
+ - `sort_emission` — `"pair"` | `"count"` | `"auto"`, default = `CompilerBackend.default_sort_emission` (`"pair"` base, `"auto"` on iree, upgraded to `"count"` for cuda targets).
60
+ - `while_init_rewrite` — bool, default `True`.
61
+ - `dot_precision` — `"DEFAULT"` | `"HIGH"` | `"HIGHEST"`, default `"DEFAULT"` (no `precision_config`, byte-unchanged export); only `"HIGHEST"` disables XLA/ROCm's TF32-class fp32 `dot`.
62
+ - **Three Writer sub-knobs are `stablehlo.export`-ONLY** — not forwarded by `_exporter_options`, in no adapter's `KNOWN_OPTIONS`, and with no `EVOXC_*` row, so they are passed directly to `stablehlo.export(graph, options=...)`: `eigh_early_exit` (bool, default `False`; llvm-cpu-only convergence early exit), `split_reduction_threshold` (int ≥ 2, default 1024 — the `total_reduced` gate), `split_reduction_non_exact` (bool, default `False` — opts float `sum`/`prod`/`mean` into splitting, which reassociates the accumulation).
63
+ - **Backend defaults are minimal, documented, and OVERRIDABLE** — a user flag with the same NAME as an evoxc default drops the default (never both). iree keeps exactly `--iree-input-demote-f64-to-f32=false` (always) and `--iree-llvmcpu-target-cpu=generic` + `--iree-llvmcpu-link-embedded=false` (llvm-cpu only), and forces no process-global runtime flag (iree's own stream-ordered `--cuda_async_allocations=true` default stands; any loader/HAL flag is overridable per load via `iree_runtime_args` or `IREE_PY_RUNTIME_FLAGS`); a small DENY list is rejected with actionable reasons — `--iree-hal-target-backends` (use `target_backends`), `--iree-input-type` (StableHLO is always the input), `--iree-vm-bytecode-module-output-format` (the adapter requires the default VM flatbuffer output). The numpy reference backend documents-ignores unknown options. Per-adapter details: `./backends/adapters/CONTEXT.md`; framework contract: `./backends/CONTEXT.md`.
64
+
65
+ ## Device kinds (binding)
66
+
67
+ Accepted `core.Device` kinds: `"cpu"` (always available, host memory), `"cuda"`, `"rocm"` (canonical AMD spelling; `"hip"` is an accepted equivalent alias, preserved as spelled), and `"vulkan"` (the IREE Vulkan/SPIR-V HAL — served by the iree adapter only; numpy/xla/tvm do not accept it and raise an explicit `BackendError`).
68
+ `Device(kind, index)` indices are PER-KIND ENUMERATION indices, not IREE HAL device ids: for cuda/rocm/hip the adapter maps `index` → the HAL's 1-BASED `device_id = index + 1`, while vulkan HAL device ids are QUERIED PER-PROCESS UUID HASHES, so the adapter maps `Device("vulkan", index)` → `query_available_devices()[index]` and creates the device from that info dict — a vulkan index has no ordinal meaning, and an out-of-range index raises an explicit error naming the requested index and the enumerated count.
69
+ One HAL device is cached per `(kind, index, runtime_args)` in a THREAD-LOCAL adapter cache shared by `load()` and the placement provider (HAL devices are thread-affine; repeated device creation is slow and leaks).
70
+ Compile spelling: a `"vulkan"` device on an iree-family backend infers `target_backends=["vulkan-spirv"]` (there is NO `--iree-hal-vulkan-target`; the optional SPIR-V profile knob is the `vulkan_target` compile option / a raw `--iree-vulkan-target=<profile>`); the artifact label for that target is `"vulkan"`, and a vulkan device only runs an artifact compiled for `vulkan-spirv` (mismatch → explicit `BackendError`, never a silent recompile).
71
+ Staging stays honest and kind-neutral: vulkan runs are DEVICE-RESIDENT exactly like cuda/rocm — outputs wrap `IreeDevicePayload` on `Device("vulkan", N)` and are never auto-copied, host inputs are rejected at the run boundary, `.numpy()` on a vulkan output raises with the explicit `.to(cpu)` remedy, and same-device inputs pass through with zero host round-trips.
72
+ `Tensor.to(Device("vulkan", N))` goes through a vulkan device-transfer provider the iree adapter registers in BOTH the per-backend and the flat DEFAULT slot; vulkan deliberately does NOT use the CUDA pinned/DMA staging tier (its ordering guarantee is a CUDA-driver property, unverified elsewhere) and takes the plain `asdevicearray` host→device copy instead.
73
+ `evoxc.devices("vulkan")` enumerates the IREE Vulkan HAL devices (lazy iree import; returns `[]` — never raises, never invents a device — when iree is absent, the driver cannot initialize, or no device is visible).
74
+ `evoxc.devices()` (kind `None`) deliberately lists `cpu + cuda + rocm` only: enumerating vulkan would instantiate the IREE Vulkan runtime and the system Vulkan loader, and on a software-Vulkan host it would report a CPU rasterizer as an accelerator — ask for `devices("vulkan")` explicitly.
75
+ Software-Vulkan hosts: IREE 3.11 hard-codes a device-NAME denylist that hides Mesa lavapipe (`llvmpipe…`) with no env override, so a lavapipe-only host enumerates nothing unless `VK_ICD_FILENAMES` selects a differently-named ICD — recipe, the default-profile budget and this host's GPU-Vulkan verdict: `./backends/adapters/CONTEXT.md` + `../bench_logs/vulkan_findings.md`.
76
+
77
+ ## Value model (owned by `core`)
78
+
79
+ - `evoxc.TensorSpec(shape, dtype, device=None, name=None)`; `evoxc.dim(name_or_int)` → `Dim`; `evoxc.dtype(obj)`; dtype constants `evoxc.float16/float32/float64/int8/int16/int32/int64/uint8/uint16/uint32/uint64/bool_/complex64/complex128` (numpy dtype objects; `bool_` avoids shadowing the builtin).
80
+ - Concrete creators `evoxc.tensor(data, dtype=None, device=None)`, `evoxc.zeros/ones/full/empty(shape, dtype=...)`, `evoxc.from_numpy(array)`, `evoxc.from_dlpack(capsule_or_tensor)` are **host-only**: they produce ndarray-backed tensors on `Device("cpu", 0)`, so `device=` accepts only `None`/`Device("cpu", 0)` (anything else → creator-naming `DeviceError`); placing data elsewhere is the explicit post-creation `t.to(device)`.
81
+ - `evoxc.constant(tensor) -> SymbolicTensor` — graph-time only, snapshots data, warns above `EVOXC_LARGE_CONSTANT_BYTES` (default 1 MiB). **Snapshots HOST data only**: a non-cpu tensor raises `DeviceError` (no implicit D2H — `t.to(core.Device("cpu", 0))` first). Owned by `ops`; `core` provides the `register_constant_builder` hook `ops` populates.
82
+ - Devices: `evoxc.devices(kind=None) -> list[Device]`, `evoxc.split_tensor(tensor, axis, devices)`, `evoxc.replicate_tensor(tensor, devices)` — the latter two are **v1 host-only data preparation** (source ndarray-backed on `Device("cpu", 0)`, every target `Device("cpu", 0)`; anything else → `DeviceError`).
83
+
84
+ ## Tensor ops (owned by `ops`; SymbolicTensor-in/SymbolicTensor-out; Python scalars auto-promote to scalar constants; concrete `Tensor` args raise `TraceError`)
85
+
86
+ `add, subtract, multiply, divide, power, remainder, maximum, minimum, abs, negate, square, sqrt, exp, log, log1p, sin, cos, tan, tanh, sigmoid, relu, gelu, erf, sign, bitwise_and/or/xor/left_shift/right_shift, logical_and/or/not, cast, equal, not_equal, less, less_equal, greater, greater_equal, select, broadcast, reshape, transpose, slice, gather, scatter, concatenate, pad, reduce_sum, reduce_max, reduce_min, reduce_mean, reduce_prod, sum, max, min, mean, prod, argmax, argmin, dot, conv, tril, triu, cumsum, solve, stop_gradient, runtime_call(callback, *operands, result=TensorSpec...), external_call(name, *operands, result=TensorSpec...)`
87
+
88
+ `sort, argsort, topk, tile, stack, flip, roll, clamp, diag, isnan, nan_to_num, eye, linspace, matmul, cumprod` (sorting: sort/argsort/topk · structural: tile/stack/flip/roll/diag · numeric: clamp/isnan/nan_to_num · creation: eye/linspace · linalg: matmul/cumprod — design notes in `./ops/CONTEXT.md`)
89
+
90
+ `eigh, cholesky, qr, matrix_rank, svd, matrix_exp` (linalg factorizations, numpy `linalg` semantics; eigh/qr/svd are multi-result tuple ops; cholesky is lower-triangular, non-PD raises at runtime)
91
+
92
+ **Control flow** (owned by `trace`): `evoxc.cond(pred, true_fn, false_fn, *operands)`, `evoxc.while_loop(cond_fn, body_fn, init)`, `evoxc.scan(f, init, xs, length=None)` — branch/body functions are traced into IR regions.
93
+
94
+ **Transforms** (owned by `transforms`, graph→graph): `evoxc.vectorize(graph, axes) -> Graph` (traced Graph only — a bare fn cannot yield a Graph; `TypeError` directs to `evoxc.vmap`), `evoxc.vmap(fn_or_graph, in_axes=0, out_axes=0)`, `evoxc.grad(fn_or_graph, argnums=None)`, `evoxc.jvp(fn_or_graph, tangents)`, `evoxc.vjp(fn_or_graph, cotangents=None)`, `evoxc.batch_functions(fns, axes=0, out_axes=0, *, switch_ops=None, bands=None, alignment="variant")` — with a fn/Defn input these return a `TransformCallable` `(*specs) -> Graph` (transforms never execute); with a Graph input they return a `Graph`. `vjp` cotangents default `None` = scalar-one (single scalar output only). `batch_functions` merges a non-empty list of same-signature programs (Graphs or callables, never mixed) into ONE graph whose leading axis is a STATIC length-N function axis — row i evaluates function i, mapped inputs supply their row, unmapped inputs are shared — with exact-structure positions becoming one batched op, `switch_ops` opting into per-row op switching (one op per variant + a static per-row `select` cascade), and other divergence `select`-muxed; it returns `BatchReport`/`SwitchRecord` metadata on `graph.batch_report`. Two keyword-only strategy options tune the merge without changing its semantics (row i always equals program i's own output, bit for bit). `bands`: `None` (default — one flat merge) | `int K` (`1 <= K <= N` contiguous bands, each merged independently, per-band outputs concatenated in function-axis order; `K == 1` is the flat merge) | `"auto"` (programs grouped by structural fingerprint into candidate partitions scored by a static work-vs-dispatch cost model, never worse than flat); a banded merge rejects `out_axes=None` on a tensor output (`TransformError`). `alignment`: `"variant"` (default — a program's same-skeleton `switch_ops`-group op joins an existing class that already holds that op variant: fewer ops and `select`s on branchy/sibling populations, e.g. 6 vs 17 ops and 3.31 vs 9.76 µs per row) | `"occurrence"` (the byte-stable legacy merge — joins the k-th occurrence class) | `"auto"`. Alignment is a PURE performance heuristic: any class assignment still yields a row-correct graph, and constant payloads always stack by occurrence. `BatchReport` adds `bands`, `band_sizes`, `band_strategy`, `cost_estimate`, `flat_cost_estimate` to its original fields (`value_classes`/`shared_classes`/`emitted_ops` become totals across bands; `SwitchRecord.rows_per_variant` stays in terms of GLOBAL function indices). Unsupported ops (no rule) raise `TransformError` — never a silent fallback; v1 restrictions/deferrals (full list in `../CONTEXT.md`): non-zero `in_axes`/`out_axes` entries (mapped axes must be leading), vectorizing control-flow (`cond`/`while_loop`/`scan`) regions, ops without a registered batching rule — control flow, `runtime_call`/`external_call` without their namespaced rules, collectives, `random_*`, `sort`/`argsort`/`tile`/`flip`/`roll`/`diag`/`cumprod`/`nan_to_num`, unruled block calls — plus registered pytree output nodes with static leaves. `sparse_*` ops DO merge (they have registered batching rules, so a sparse value can be built/consumed inside a merged program); only a sparse value in the OUTPUT tree is deferred.
95
+
96
+ **Distributed** (owned by `dist`): `evoxc.dist.group(name, ranks) -> Group`, `evoxc.dist.all_reduce/all_gather/reduce_scatter/all_to_all/broadcast/collective_permute(tensor, ..., group=Group)`, graph scalars `evoxc.dist.rank()`, `evoxc.dist.world_size()`.
97
+
98
+ **Sparse tensors** (owned by `sparse`, numpy-backend-only in v1): value model `SparseTensor`, `CSRTensor`, `CSCTensor`, `SparseTensorSpec` (+ `SparseTensorSpec.from_concrete`, the derive-spec entry used by `evoxc.evaluate`), `is_sparse`; creators `coo(indices, values, shape)`, `csr(indptr, indices, values, shape)`, `csc(...)`, `from_dense(dense)` (polymorphic: concrete → eager validated + canonical-form checked; symbolic → in-graph assembly via `from_parts`, `sparse_from_dense` op); converters `to_dense`/`to_csr`/`to_csc`/`to_coo` (polymorphic: concrete → eager, symbolic → graph op); ops `add`, `subtract`, `multiply`, `multiply_dense`, `negate`, `sum` (alias `reduce_sum`, dense result), `transpose`, `reshape`, `concatenate`, `matmul` (sparse@dense and dense@sparse; sparse@sparse → `TraceError` v1 deferral). Pytree contract: ONE registered base class, children = tensor leaves + `dense_shape` ints + `np.dtype` + format string as static leaves, polymorphic unflatten (first child kind selects spec/symbolic/concrete rebuild). v1 deferrals (explicit errors, never silent): no sparse constant, no sparse@sparse, compiler backends defer with an explicit `BackendError` (densify with `evoxc.sparse.to_dense`), whole-sparse `bind`, `concatenate`/`csc` vjp `TransformError`s. Full surface: `./sparse/CONTEXT.md`.
99
+
100
+ **Random** (owned by `random`; `evoxc/random.py` re-exports the frontend in `evoxc/ops/random.py`): key-based functional RNG as pure graph ops — `key(seed, algorithm="splitmix64")`, `split(key) -> (key_a, key_b)`, `split_n(key, n) -> tuple`, `uniform(key, shape, low=0.0, high=1.0, dtype=float32)`, `normal(key, shape, mean=0.0, std=1.0, dtype=float32)`, `randint(key, shape, low, high, dtype=int32)`, `permutation(key, n, dtype=int32)`, `multinomial(key, input, num_samples)` (int32 output).
101
+ **Multi-algorithm framework (binding):** `key()`'s `algorithm` takes a validated string or an `Algorithm` enum member (`SPLITMIX64`/`THREEFRY2X32`/`PHILOX4X32_10`); `ALGORITHMS`/`DEFAULT_ALGORITHM`/`validate_algorithm`/`algorithm_key_type` live in `evoxc/ir/op_defs/random.py` (re-exported at `evoxc.random`).
102
+ The algorithm IS the key's static shape/dtype tag — splitmix64 rank-0 int64 (`key(seed)` masks to 64 bits), threefry2x32 `(2,)` int32, philox4x32_10 `(4,)` int32 — so every other random fn takes NO algorithm param and instead infers it from the key operand at trace time, stamping the op's `algorithm` attribute (all 6 OpDefs; unknown → `ValueError`, no matching key form → `ShapeError`/`DTypeError` naming the three forms).
103
+ Deterministic/stateless (same key + operands ⇒ BIT-IDENTICAL values across `run`/`evaluate`) and never key-mutating (`split`/`split_n` for independent keys); dtypes default f32 (uniform/normal) / i32 (randint/permutation/multinomial); `key()` is the ONLY polymorphic creator, the rest are graph ops (`TraceError` outside a trace / for concrete `Tensor`s).
104
+ numpy is the reference for all 3 algorithms; 5 of 6 ops export as v1 StableHLO (`random_multinomial` defers, `BackendError`); `DEFAULT_ALGORITHM` is `splitmix64` (`evoxc/bench/rng_bench_results.md`); transforms have no random-op rules → `TransformError` (6 OpDefs: category "random", effect "pure", usable in `cond`/`while_loop`/`scan`). Full stream/salt/lowering contract: `./ops/CONTEXT.md` + `./backends/stablehlo/CONTEXT.md`.
105
+
106
+ **Custom ops** (owned by `block`): `evoxc.block(name, inputs=None, outputs=None, attributes=None, effects=None, batching=None, portable=None)` — decorator/factory returning a callable `BlockOp`; `BlockOp.impl(backend_name)`; `BlockOp.batching_rule(fn)`; `BlockOp.jvp_rule/vjp_rule(fn)`. No rule + no safe policy + no portable decomposition ⇒ `TransformError`.
107
+
108
+ **Backends** (owned by `backends`): `evoxc.backends.Backend` (abstract: `name`, `capabilities`, `lower`, `compile`, `load`), `evoxc.backends.register/get(name)`, `evoxc.backends.numpy_backend` (default CPU interpreter), `evoxc.backends.stablehlo` (`export(graph|module) -> str` MLIR text). `evoxc.lower/compile/load` default to `numpy_backend`.
109
+
110
+ **Persistence** (owned by `persist`, used by pipeline types): `Graph.save/load`, `LoweredProgram.save/load/.text()`, `CompiledArtifact.save/load`, `Executable.save/load`, `evoxc.Cache` (explicit; `FileCache(directory)` in `persist`). Loading never silently re-traces/recompiles; incompatibility fails clearly.
111
+
112
+ **Namespace**: `evoxc.numpy` (alias `enp`) + `evoxc.numpy.linalg` — numpy-style graph API producing the same IR as `ops`.
113
+
114
+ **Structured I/O**: tuple/list/dict/namedtuple/dataclass supported everywhere (trace inputs, run outputs, bind); custom containers register via `evoxc.register_pytree_node`. **Pytree utilities** (owned by `core`, exported on `evoxc`): `tree_map(fn, *trees)`, `tree_leaves(tree)`, `tree_structure(tree)`, `tree_flatten(tree)`, `tree_unflatten(leaves, treespec)` — pure sugar over flatten/unflatten (no new semantics). Container edge behavior: `defaultdict`/`Counter` roundtrip (default_factory preserved when `None`/a class, else a clear `unflatten` error); unorderable dict keys, dataclass `InitVar`/`init=False` rebuilds, and `register_pytree_node(object, ...)` raise plain `TypeError`/`ValueError` with actionable messages. **Structure-mismatch diagnostics**: every structural mismatch (`tree_map`, `Graph.flatten_inputs`/`validate_inputs`, `run`/`bind`, transforms' axes/tangent trees) reports the first divergent pytree path with expected/got node descriptions (e.g. `first mismatch at pytree path [0]['z']: expected dict with keys ['a', 'b'], got list of length 3`) via the shared `core.first_mismatch_path`/`format_path` helpers; per-caller lead-in wording is preserved (tests match the substrings).
115
+
116
+ ## Cross-module contracts (must-expose names)
117
+
118
+ - **`core`** exports: `Tensor`, `SymbolicTensor`, `TensorSpec`, `Dim`, `DimExpr`, `Device`, `TreeSpec` (`flatten`/`unflatten`/`register_pytree_node`), the pytree sugar above, the internal structure-mismatch helpers `first_mismatch_path`/`format_path` (consumed by trace graph.py, pipeline, transforms — NOT part of the top-level `evoxc` surface), `dtype(obj)`, dtype constants, `EVOXCError` + subclasses, concrete creators, device helpers, `register_operator_handlers(kind, handler)` — a hook dict (`add`/`sub`/`mul`/`matmul`/`getitem`/`truediv`/`pow`/`neg`/`lt`/`le`/`gt`/`ge`/`eq`) that `ops` populates at import time so `SymbolicTensor.__add__` etc. work without import cycles — and `register_constant_builder` (the `evoxc.constant` hook, populated by `ops`).
119
+ - **`ir`** exports: `Module`, `Function`, `Region`, `Block`, `Op`, `Value`, `Builder`, `Location`, `op registry` (`ir.opdef(name)`, `ir.register_opdef`, `ir.has_opdef`, `ir.op_names`), `verify(module) -> None` (raises `core.VerificationError`), `serialize_module/deserialize_module` (versioned, self-describing payload with integrity hash — `IR_FORMAT_VERSION`), `pretty_print(module)`. **The `ir` registry is the CANONICAL op-definition source (119 op names incl. the `return` terminator; the dist collective is `broadcast_collective` to avoid clashing with the shape op `broadcast`). `ops` consumes `ir.opdef()` and must NOT maintain a parallel op-definition table — any missing arity/attr spec is fixed in `ir`, not duplicated.** Effect kinds: `pure`, `write`, `read`, `collective`, `callback`.
120
+ - **`ops`** exports: every function listed above + `runtime_call`; op functions build IR into the **active builder** from `trace.current_builder()`; raise `TraceError` when no trace is active or a concrete `Tensor` operand appears; operator handlers registered into `core`. `external_call` builds the `external_call` op (see "External kernels").
121
+ - **`trace`** exports: `defn`, `trace`, `Graph` (attrs `module`, `input_specs`, `output_tree`, `static_values`, `source_locations`; methods `print()`, `verify()`, `save/load`, `flatten_inputs(args) -> flat_tensors`, `unflatten_outputs(flat) -> structured`, `validate_inputs(args) -> flat_tensors`), `cond`, `while_loop`, `scan`, `current_builder()` / builder-stack context, and `Defn` (stores fn + `__evoxc_defn__` marker). The Graph constructor accepts a prebuilt module so transforms can build new graphs.
122
+ - **`block`** exports: `block(...)`, `BlockOp`, `get_block`, `BlockError`, `BatchingPolicy`. `BlockOp` attrs: `name`, `input_specs`, `output_specs`, `attribute_schema` (alias `attributes`), `effects`, `batching_policy`; methods `impl(backend_name)`, `batching_rule(fn)`, `jvp_rule(fn)`, `vjp_rule(fn)`, `portable(fn)`, `__call__(*symbolic_or_static)` (builds a BlockCall op; static args specialize). Factory form `block(name, inputs=[...], outputs=[...], ...)` and decorator form over an `@evoxc.defn` (name defaults to fn name; `result=`/`outputs=` may declare output specs; portable impls MUST be `@evoxc.defn` functions). Rules register into `transforms.*_rules` under `block:<name>` keys — `transforms` never imports `block`.
123
+ - **`transforms`** exports: `vectorize`, `vmap`, `batch_functions`, `grad`, `jvp`, `vjp`, and the merge report types `BatchReport`/`SwitchRecord` (attached to a merged graph as `graph.batch_report` — documented transform metadata, ignored by persistence). Batching rules register per-op via `transforms.batching_rules`; derivative rules via `transforms.vjp_rules` (plus `jvp_rules`, `register_batched_aux_remap`). Result graphs contain only ordinary ops (the numpy backend needs NO special vectorize/autodiff runtime support), and `batch_functions` is numpy-backend validated end-to-end: its output is an ordinary STATIC-shaped graph (the function axis is a concrete leading dim), so compiler backends need no new support either.
124
+ - **`backends`** exports: `Backend` ABC — `name: str`, `capabilities: Capabilities` (fields `dynamic_shapes`, `dtypes`, `collectives`, `runtime_calls`, `external_calls`, `custom_blocks`, `async_collectives`, `sparse_ops`, `rng_bit_generator`), `lower(graph, options) -> LoweredProgram`, `compile(lowered, options) -> CompiledArtifact`, `load(artifact, device) -> backend executable`; **backend `Executable` protocol** — `run(flat_input_tensors) -> flat_output_tensors`, `.functions`, `.device`, optional `.save(path)`/`.load(...)` (must save artifact + reconstruct explicitly if handles are device-specific), and optional `.synchronize()` (NOT part of the structural `runtime_checkable` protocol, so a backend without it is fine; backends whose `run()` already blocks — `numpy`, `iree` — omit it or provide a documented no-op, while `xla` implements it by awaiting outstanding PJRT device-complete events). **`LoweredProgram`** (`.text()`, `.save/.load`, `.backend`, `.signature`) and **`CompiledArtifact`** (`.save/.load`, `.backend`, `.signature`, `.target`) are owned by `backends`; `Signature` fields: `input_tree`, `output_tree`, `input_specs`, `output_specs`, `static_values`, `output_static_values`. Also `register/get(name)`, `numpy_backend` (its LoweredProgram wraps a serializable program, CompiledArtifact wraps serialized IR), `stablehlo` (export utility, also the shared lowering input for compiler backends), and the **pluggable compiler adapters** in `evoxc.backends.adapters` — `iree`, `xla` (PJRT C API via ctypes over a user-provided plugin `.so`, no jax/jaxlib), `tvm` (jaxlib only for its bundled MLIR bindings; `jax` is never imported) — optional and lazily activated on first `get(name)`/`lower(..., backend=name)`; iree serves `cpu`/`cuda`/`rocm`/`hip`/`vulkan` devices (vulkan = its Vulkan/SPIR-V HAL — see "Device kinds"), xla/tvm serve `cpu`/`cuda`/`rocm`; a missing dependency raises an explicit `BackendError` (pip hint for iree/tvm, `EVOXC_PJRT_PLUGIN`/`plugin_path` guidance for xla), and `import evoxc` never imports adapter deps.
125
+ - **`dist`** exports: `group(name, ranks, backend=None)`, `rank()`, `world_size()`, `all_reduce`, `all_gather`, `reduce_scatter`, `all_to_all`, `broadcast`, `collective_permute`. Collectives build `Collective`-effect ops (kind + group attr) with local-tensor shapes (e.g. 4-rank all_gather axis=0: `[256,1024] → [1024,1024]`). Imports `core`/`ir`/`trace` (builds ops via the active-builder hook; `trace` duck-types `Group` for static snapshotting without importing `dist`).
126
+ - **`sparse`** exports the surface above; imports `core`/`ir`/`trace`/`ops`/`transforms` ONLY (never `pipeline` — `evoxc.evaluate` lazy-imports it inside the function). Batching/vjp/jvp rules register one-way into `transforms`' public registries at `import evoxc.sparse` time. No new IR value kind — sparse tensors are pytree composites over ordinary tensor values plus static leaves.
127
+ - **`external`** (`evoxc/external.py`) exports: `register_external_kernel(name, callable_, backend=None, device_resident=False) -> ExternalKernel`, `unregister_external_kernel(name)`, `get_external_kernel(name, backend=None)` (callable-only), `get_external_kernel_entry(name, backend=None) -> (callable | None, device_resident)` (the mode-aware internal lookup), `register_portable(name, fn)`, `get_portable(name)`, and class `ExternalKernel` (see "External kernels"). Rule registration + portable-decomposition fallbacks live in `evoxc/external_rules.py`, a self-contained mirror of `evoxc/block/rules.py` that also holds the shared pass-through batching-rule factory behind the batched-variant sugar. Imports NOTHING from evoxc at module level (stdlib only; only the numpy backend, the frontend op docstrings, and the fallback rules reference it lazily).
128
+ - **`pipeline`** (`evoxc/pipeline.py`) exports: `lower/compile/load/run/bind/build/evaluate`; `Executable` (user-facing wrapper: backend executable + input/output TreeSpec + signature for validation; `.functions`, `.device`, `.save/.load`, `.synchronize()` delegating to the backend), and `BoundExecutable` from `bind`. Internal hot-path caching (no observable behavior): each wrapper lazily caches an input plan and an output plan, so `run` validates structure and leaves in one pass over the raw arguments and falls back to the slow path on any structural divergence, keeping error messages byte-identical.
129
+ - **`persist`** exports: `save_object(path, payload_type, payload_fields, backend_info=None, signature_info=None)` / `load_object(path, expected_payload_type=None) -> LoadedObject` over a container format (magic header `b"EVOXCPERS"` + format version `EVOXC_FORMAT_VERSION` + JSON metadata + payload + SHA-256 integrity); `encode_value/decode_value` (envelope codec covering numpy arrays via base64 npy, dtype, slice, Dim, DimExpr, Device, TensorSpec, TreeSpec, containers); `Cache` interface + `FileCache(directory)` with `get(key_components, compute_fn=None)` (alias `get_or_compute`). Imports `evoxc.core` ONLY.
130
+
131
+ ## Value-model details (binding)
132
+
133
+ - **Errors**: all public errors derive from `EVOXCError` (in `core`): `TraceError`, `ShapeError`, `TransformError`, `BackendError`, `PersistenceError`, `DeviceError`, `DTypeError`, `VerificationError`, `BlockError`. No API silently swallows or works around errors; messages include the source location (`model.py:83`) whenever a graph location exists.
134
+ - **Shapes**: `Dim(name)` symbolic; `DimExpr` supports `+ - * // % min max` over dims/ints; `TensorSpec.shape` = tuple of `Dim|DimExpr|int|None` (`None` = runtime-dynamic, unchecked). Rank is always known at trace time. Shape inference is `ir`/`ops`'s job via `DimExpr` arithmetic.
135
+ - **`Tensor`** — a local physical tensor whose `device` is always physically true. (a) ndarray-backed (v1 default): the data IS host memory, so `device` is always `Device("cpu", 0)` — constructing one with any other `device=` raises `DeviceError`. (b) device-payload-backed: `data` is the payload object and `device` is the payload's device (an explicit `device=` must agree with it). **Host access is explicit**: `.numpy()` on ndarray-backed data returns the same array (zero-copy); on a cpu-kind payload it materializes a lazy FRESH host copy per call; on a non-cpu payload it raises `DeviceError` — there is no implicit device-to-host transfer (`t.to(core.Device("cpu", 0)).numpy()` is the explicit readback). `__dlpack__`/`__dlpack_device__` are zero-copy for host data; on device payloads they raise kind-aware `DeviceError`s (cpu-kind: "`.numpy()` first"; non-cpu-kind: "transfer via `t.to(...)` first"). `__eq__` is metadata-only whenever a payload is involved. **`Tensor.to(device)` is the ONLY transfer API**: equal device → `self` (no copy); `to(cpu)` on a payload = the explicit D2H fresh host copy; `to(non-cpu)` consults the device-transfer provider registry for that kind (per-backend slots filled by each adapter's `register()` under its own name, plus the legacy flat DEFAULT slot where `evoxc.backends` installs the lazy iree cuda thunk — vulkan has no thunk, the iree adapter's `register()` fills BOTH its per-backend and the flat slot for it; the owning backend's slot wins, then the flat default; no provider for the kind → `DeviceError`); direct payload→non-cpu copies are not implemented in v1 (`DeviceError` suggesting the two-hop `t.to(cpu).to(target)`). Mutable `data` access is documented as unsupported for graph constants.
136
+ - **Run boundary (no implicit device↔host transfers)**: `evoxc.run`/`evoxc.bind` reject any tensor leaf whose `device` differs from the executable's device with a `DeviceError` naming the input tree path, both devices, "no implicit device", and `t.to(` — BEFORE backend dispatch. A non-cpu executable therefore rejects host numpy inputs and raw ndarrays: host inputs must be explicitly placed (`x.to(Device("cuda", 0))`, `x.to(Device("vulkan", 0))`, …). Run outputs stay device-resident (never auto-copied); read back via `t.to(cpu).numpy()`. llvm-cpu runs keep feeding/reading host data (their tensors are cpu:0).
137
+ - **`SymbolicTensor`**: fields `value` (ir.Value), `dtype`, `shape` (tuple of `DimExpr|int`), `location`; SSA identity = `value.id`. Must NOT define `numpy`, `data_ptr`, `__dlpack__`, `__array__`.
138
+ - **`Graph` trace semantics**: parameters become `Function` block args; static Python values specialize and are recorded in `static_values` (run validates them); a closure-captured `Tensor` used in ops → `TraceError` ("make it an explicit input or use evoxc.constant"); `evoxc.constant` creates a Constant op and warns above `EVOXC_LARGE_CONSTANT_BYTES`.
139
+ - **Staged sugar rules**: `evoxc.build`/`evoxc.evaluate`/`evoxc.build_cached` docstrings must state their exact expansion; no other composition APIs exist in core.
140
+
141
+ ## Serialization contract (binding)
142
+
143
+ Formats are versioned via constants (`EVOXC_FORMAT_VERSION`). Artifacts are self-describing: backend name/version, target, input/output signature (TreeSpec + specs), static values, required custom ops, IR format version. `Graph.save` → `.evoxcgraph` (portable JSON container); `LoweredProgram` numpy → serialized program; stablehlo → `.mlir` text; `CompiledArtifact` → `.evoxcartifact`; `Executable.save` → backend-dependent (numpy saves the artifact plus an explicit note that it is reconstructed at load). Loading with a mismatched backend/device/ABI → `PersistenceError`, never a silent recompile.
144
+
145
+ ## Routing table
146
+
147
+ | Path | Area |
148
+ |---|---|
149
+ | `./core/` | Value model: dtypes, Dim/DimExpr, TensorSpec, Tensor, SymbolicTensor, Device, TreeSpec + pytree sugar, device helpers, errors, operator-handler hook |
150
+ | `./ir/` | EvoXIR: SSA structures, the canonical op-definition registry, builder, shape inference, verify, serialize, locations, effects |
151
+ | `./ops/` | Frontend tensor ops + `runtime_call`/`external_call` (+ per-op shape/dtype inference); `random.py` holds the `evoxc.random` frontend (re-exported via `evoxc/random.py`) |
152
+ | `./numpy/` | `evoxc.numpy` (enp) namespace incl. `linalg` — thin sugar over `ops` |
153
+ | `./trace/` | `defn`, `trace`, `Graph`, `cond`/`while_loop`/`scan`, builder context |
154
+ | `./block/` | Custom blocks: declaration, impl registry, batching/derivative rules |
155
+ | `./external.py` | External-kernel registry + `ExternalKernel` handle (see "External kernels"); the `external:<name>` rules + decomposition fallbacks live in `./external_rules.py` |
156
+ | `./transforms/` | `vectorize`, `vmap`, `batch_functions`, `grad`, `jvp`, `vjp` + rule registries |
157
+ | `./backends/` | Backend interface, registry, numpy interpreter, stablehlo exporter, compiler-adapter framework, external-call splitting |
158
+ | `./dist/` | Groups + explicit collectives |
159
+ | `./sparse/` | Sparse tensors: value model (SparseTensor/CSRTensor/CSCTensor/SparseTensorSpec), creators/converters, graph ops, batching/vjp/jvp rules |
160
+ | `./pipeline.py` | Orchestration: `lower/compile/load/run/bind/build/evaluate` + user-facing `Executable`/`BoundExecutable` wrappers |
161
+ | `./persist/` | Save/load container format, explicit cache |
162
+ | `./io.py` | Explicit async host-data IO sugar: `prefetch`/`sink`/`AsyncCopy`/`wait_all` over `Tensor.to` (see "evoxc.io") |
163
+ | `./build_cache.py` | Memoized build sugar: `build_cached` + `CompileCache` LRU (see "Memoized build sugar") |
164
+ | `./bench/` | Conformance & benchmark harness for example evoxc programs (numpy + optional lazy torch references) |
165
+
166
+ Sibling: `../tests/` → test suite (read-only from here; escalate test-related writes to root — it owns the per-suite inventory and test-count registry).
167
+
168
+ ## evoxc.bench — conformance & benchmark harness (user-facing tool)
169
+
170
+ `evoxc.bench` is a standalone harness subpackage, deliberately NOT re-exported on the top-level `evoxc` namespace (use `import evoxc.bench`). It runs curated example `@evoxc.defn` graphs through the explicit pipeline (`evoxc.build` + `evoxc.run`, default numpy backend) and compares results against pure-numpy references — and, optionally, PyTorch references.
171
+ Public API: `conformance(examples=None, *, use_torch=None, tolerance=None, rtol=1e-5, atol=1e-5, seed=0) -> ConformanceReport`, `benchmark(examples=None, *, use_torch=None, repeats=20, warmup=2, seed=0) -> BenchmarkReport`, `list_examples()`, `list_tags()`, `get_example(name)`, the report types (`ExampleResult`, `ConformanceReport`, `BenchmarkReport`, `print_report`), and the CLI `python -m evoxc.bench`. Examples live in `./bench/examples/` in three groups (`op` / `block` / `e2e`) with per-example numpy references, optional lazily-built torch references, sub-group `tags`, and an optional Python-level `runner` for multi-run procedures (e2e training loops); the `--examples` filter accepts names, categories AND tags (precedence: category → exact name → tag). Registry and harness contract: `./bench/CONTEXT.md`.
172
+ **torch-optionality (binding):** `import evoxc` / `import evoxc.bench` MUST always succeed without torch — torch never appears at module scope anywhere in this subpackage (same discipline as `./backends/adapters/`); it is probed/imported lazily inside function bodies (`./bench/_torch.py`). When absent, torch comparisons are skipped (`torch_pass=None`/`torch_available=False` in auto mode), and `use_torch=True` raises a clear `ImportError` mentioning `pip install evoxc[bench]` — never a raw `ModuleNotFoundError`.
173
+
174
+ ## evoxc.io — explicit async host-data IO (user-facing module)
175
+
176
+ `evoxc.io` (module `evoxc/io.py`; stdlib + `evoxc.core` imports ONLY) is explicit copy-queue sugar over `Tensor.to`: it schedules the SAME explicit transfers `Tensor.to` performs synchronously onto a background worker thread, so they run off the calling thread. No hidden staging and no overlap guarantees beyond caller-relative asynchrony: ONE process-global FIFO daemon worker thread (lazily started at the first submission) executes every scheduled copy strictly in issue order — a v1 limitation (true same-device overlap needs runtime async-engine support; see Known Issue #12 in `./backends/adapters/CONTEXT.md`). The worker never dies and never raises: per-copy failures are stored on the handle and re-raised by every `wait()`/`result()`/`wait_all()`.
177
+ - `prefetch(host_tensor, device) -> AsyncCopy` — host→device, run through the registered device-transfer provider; the source must be an ndarray-backed `core.Tensor` on `Device("cpu", 0)` (a raw ndarray → `TypeError` telling you to wrap it; a payload-backed host tensor, or a source already at the target, → `DeviceError`; a non-`core.Device` target → `TypeError`).
178
+ - `sink(device_tensor) -> AsyncCopy` — device→host, via the payload host-copy path (an ndarray-backed source, or a cpu-kind payload, → `DeviceError` pointing at `t.numpy()` / "no download needed").
179
+ - class `AsyncCopy` — `.device` (the target for prefetch, the source for sink), `.direction` (exactly `"host_to_device"` or `"device_to_host"`), `.done` (non-blocking poll), `.wait(timeout=None)` (blocks until the copy finishes and re-raises any stored failure VERBATIM on every call; a timeout raises `TimeoutError` and NEVER cancels the copy — wait again to retry), `.result(timeout=None)` (= `wait()` + the copied tensor). No destructor: GC never auto-waits, and a dropped handle's copy completes independently.
180
+ - `wait_all(timeout=None)` — waits for every copy outstanding at call time in issue order, raising the first stored failure.
181
+ Schedule-time validation is synchronous on the calling thread; runtime failures surface verbatim at `wait()`/`result()`/`wait_all()`. Re-entry guards: scheduling or waiting from the worker thread would deadlock, so `prefetch()`/`sink()`/`AsyncCopy.wait()`/`wait_all()` there raise `RuntimeError`. Non-cpu-kind copies trigger a lazy, best-effort, one-time CUDA/ROCm primary-context bootstrap on the worker (a throwaway iree HAL device with the adapter's exact 1-based `device_id = index + 1` mapping, on the iree DRIVER name — `rocm`/`hip` → `hip`, else the kind as-is; kept alive in `_bootstrap_devices`; every bootstrap failure is swallowed so it can never mask the copy's own error). Numpy-only environments never import iree. The `atexit` hook drains in-flight copies best-effort and stops the worker cleanly; interpreter exit never blocks.
182
+
183
+ ## Memoized build sugar (evoxc.build_cache)
184
+
185
+ `evoxc.build_cached(fn, *specs, backend=None, device=None, cache=None, **options) -> Executable` (module `evoxc/build_cache.py`) is documented shorthand for a MEMOIZED `build` — no other behavior: the exact `trace → lower → compile → load` composition runs at most once per distinct cache key, and a hit returns the SAME fully loaded `Executable` with zero pipeline work. Purpose: a true-JIT-style helper for meta-level loops (NAS / genetic programming / genetic algorithms) whose outer loop produces a DIFFERENT static program each iteration (e.g. a random expression tree encoded as a tensor), decodes it, traces + compiles a fresh graph at runtime, and runs it in an inner loop; the returned executable is a NORMAL one (same-device device-resident run loops work unchanged) and static args stay in the run signature, validated at the run boundary.
186
+ - **Cache key** — computed BEFORE any tracing as the tagged tuple `(("fn", id(fn)), ("specs", specs), ("backend", resolved_backend.name), ("device", resolved_device), ("options", _canonicalize_options(resolved_options)))`; the entry pins `fn` as its keepalive so `id(fn)` can never alias a later object. The full specs tree (structure AND static content) is encoded via `persist.encode_value`, so each distinct static "program" value = a distinct graph = a distinct entry, while a runtime tensor in a program slot is an ordinary graph input keyed ONCE on its `TensorSpec` — never specialized per value. Options are canonicalized order-insensitively so semantically-equal option sets key identically; unset `backend`/`device` resolve exactly as in `build` and participate in the key. Process-env knobs the compiler stages read themselves (`EVOXC_OPT_LEVEL`, `EVOXC_EIGH_ALGORITHM`, `EVOXC_SPLIT_REDUCTION`, `EVOXC_IREE_*`, `EVOXC_XLA_*`, `EVOXC_TVM_*`) are NOT part of the key — clear the cache (or pass a fresh `CompileCache`) when changing them. An unencodable static leaf raises a pre-cache `TypeError` naming the key component path (e.g. `specs[2]`, `specs[3]['w']`) and its type, pointing at `persist.encode_value`'s coverage and at plain `evoxc.build` for unkeyable calls.
187
+ - **Failure bookkeeping (binding)** — fn validation, backend/device resolution, cache-type checks and encodability all fire BEFORE any cache access; env-resolution failures count NO miss and insert nothing; post-key stage failures count a miss, insert nothing, and re-raise untouched. Only a fully loaded Executable is ever inserted — never a cached failure, never an eager fallback.
188
+ - class `CompileCache(Cache)` — in-memory thread-safe LRU (default `maxsize=128`; a non-positive or non-int `maxsize` → `ValueError`): `get`/`put`/`contains`/`clear`/`get_or_compute` plus public `hits`/`misses` (`clear` resets them); the compute function runs OUTSIDE the lock and the first insert wins on races; LRU eviction pops the oldest entry. In-memory only (executables hold device handles/vmfb/compiled code — never persisted). `cache=None` selects the module-level default (a fresh instance isolates callers); there is deliberately NO `cache=False` escape — plain `evoxc.build` is the no-cache path. `cache` must be a `CompileCache` or `None` and `fn` a callable/`@evoxc.defn` function — a `Graph` argument raises a `TypeError` directing to the explicit `lower`/`compile`/`load` pipeline.
189
+
190
+ ## External kernels (binding interface contract)
191
+
192
+ A kernel-agnostic escape hatch for plugging custom (e.g. triton) kernels into `defn` graphs to bypass compiler weaknesses. **No triton (or any kernel) code lives in evoxc** — the mechanism only declares, registers, and dispatches; the kernel itself is written against this interface in a different repo.
193
+
194
+ **1. Graph side — `evoxc.external_call(name, *operands, result=...)`** (frontend op in `evoxc/ops/external.py`, IR op `external_call`, effect `callback`):
195
+ - `name`: non-empty `str`, the STATIC kernel identifier — it specializes the graph exactly like any static parameter. Registration is a RUN-TIME concern: tracing does NOT require the kernel to be registered; running does.
196
+ - `*operands`: `SymbolicTensor` or Python scalars (auto-promoted to 0-d constants). No static (Python) parameters in v1.
197
+ - `result`: a `core.TensorSpec` (single output) or a non-empty tuple/list of them — the graph's DECLARED output contract. Specs may contain symbolic dims (resolved against runtime input bindings) or `None` (runtime-dynamic, unchecked). Returns a `SymbolicTensor` or a tuple of them.
198
+ - Errors: `TraceError` outside a trace / for concrete `Tensor` operands; `TypeError` for a bad `name` or `result`. Works inside `cond`/`while_loop`/`scan` bodies on the numpy backend.
199
+
200
+ **2. Run-time side — the registry (`evoxc/external.py`, stdlib-only module-level imports)**:
201
+ - `register_external_kernel(name, callable_, backend=None, device_resident=False) -> ExternalKernel` — process-global, PER-BACKEND registry: each name maps to backend slots (`None` = the DEFAULT slot, used by any backend with no exact slot); registration OVERWRITES the slot's callable AND mode (last wins — hot-reload). `device_resident=True` (explicit opt-in) registers a DEVICE kernel and REQUIRES an explicit per-backend slot (`TypeError` with `backend=None` — the default slot is also dispatched by the numpy backend, which passes host arrays); in v1 only iree consumes the flag. `TypeError` for a non-str/empty name, a name containing the reserved suffix `_EVOXC_BATCH_SUFFIX` (`"__evoxc_batched"`, reserved for `batch_variant` — register the base name), a non-callable kernel, a non-bool `device_resident`, or a non-None/non-str backend.
202
+ - class `ExternalKernel` (handle; attr `name`; every method returns `fn` so it is decorator-friendly): `impl(backend, fn=None, device_resident=False)` per-backend registration; `portable(fn)` (= `register_portable`); `batching_rule(fn)`/`vjp_rule(fn)`/`jvp_rule(fn)` registering transform rules under `external:<name>`.
203
+ - **Declarative batched-variant sugar.** `batch_variant(fn=None, *, backend=None, device_resident=False)` registers `fn` under the DERIVED name `f"{name}__evoxc_batched"` (same slot/`device_resident` semantics as `impl`) and installs the shared pass-through batching rule under BOTH `external:<name>` and `external:<derived>` (what a nested-vmap second pass re-resolves); `batch_invariant()` (returns `self`) declares the kernel invariant to extra leading mapped axes and installs that rule under `external:<name>` only.
204
+ - `register_portable(name, fn)` — the OPTIONAL graph decomposition; `fn` MUST be an `@evoxc.defn` function (`__evoxc_defn__` validated at registration; reserved suffix rejected), traced LAZILY when a fallback rule fires. It pre-registers fallback rules under `external:<name>`: the vjp fallback always, the batching fallback only when no explicit batching rule exists yet (explicit rules win; last registration wins). `get_portable(name)` returns it or `None`. `unregister_external_kernel(name)` removes all kernel slots, the portable, and their derived form (`KeyError` if neither was ever registered) and does NOT touch the `transforms` registries (rules are graph-level and survive). Slot resolution (both lookups, exact backend slot → default slot → `None`) is specified in "Cross-module contracts".
205
+ - **Callable signature (binding). HOST mode (default)**: `fn(*np_arrays) -> ndarray | core.Tensor | tuple/list of them`, whose count/dtype/shape MUST match the specs declared by the invoking `external_call` (count/dtype → `BackendError`, shape → `ShapeError`, anything else → `BackendError`, never a guess). **DEVICE mode** (`device_resident=True`, iree only in v1): `fn(*tensors)` receives the boundary's device-resident `core.Tensor`s (`.data` is an `IreeDevicePayload`) DIRECTLY (never `.numpy()`-staged) and may return device `core.Tensor`s, duck-typed payloads (`shape`/`dtype`/`device`/`to_host()`), raw iree `DeviceArray`s, numpy arrays, or mixes; results are validated METADATA-ONLY (never host-copied). Both modes share ONE validation implementation (`evoxc/backends/external_validate.py`).
206
+
207
+ **Execution semantics (v1)**: the numpy interpreter dispatches by name at the op's position in block op order via `get_external_kernel_entry(name, "numpy")` — a `device_resident=True` slot raises an explicit `BackendError` there (host arrays cannot honor device-resident semantics; register a host-mode numpy slot or run on a compiler backend) and an unknown name → `BackendError` naming the kernel and pointing at `register_external_kernel`. **External-kernel boundaries are the ONLY sanctioned host↔device staging points** — plain runs never stage.
208
+
209
+ **Transforms**: rules live under the namespaced key `external:<name>`; without explicit rules a registered PORTABLE drives `vmap`/`vectorize`/`grad`/`jvp`/`vjp` through the pre-registered decomposition fallbacks (`evoxc/external_rules.py`), else `TransformError` naming the op (never a silent fallback). The shared pass-through batching rule rebuilds each mapped `external_call` with the `target_name` attribute (the DERIVED name for batched variants) and the batched operand stack AS-IS — result types gain the leading batch dims, `"result_specs"` re-encoded as `ir.ValueType`s, result axes `MappedAxes(range(k))`.
210
+
211
+ **Persistence**: the registry is NEVER serialized (artifacts carry only `name`); `Graph.save`/`load` work and a saved graph's process must re-register its kernels first; the numpy `compile()` records kernel names in `required_custom_ops` (self-description only — resolved LAZILY at run time; block names stay load-time validated).
212
+
213
+ **Compiler backends**: the iree adapter declares `Capabilities.external_calls=True`, SPLITS the graph at `lower()` into segment programs + a kernel-call plan, and dispatches each boundary in the kernel's registered mode (host staging via `Tensor.to(cpu)`, or zero-host-round-trip device dispatch) — mode-aware result-dim gates and payload interop in `./backends/CONTEXT.md`. Backends without host-dispatch (xla/tvm) inline a registered portable with a `UserWarning`, else raise an explicit `BackendError` naming the op + backend; stablehlo direct export still defers (`DEFERRED_OPS`).
214
+
215
+ Minimal usage:
216
+ ```python
217
+ evoxc.register_external_kernel("relu_custom", my_kernel) # default (host) slot
218
+ evoxc.register_external_kernel("relu_cuda", my_kernel, backend="iree", device_resident=True)
219
+
220
+ @evoxc.defn
221
+ def model(x, w):
222
+ return evoxc.dot(evoxc.external_call("relu_custom", x,
223
+ result=evoxc.TensorSpec((N, D), evoxc.float32)), w)
224
+
225
+ evoxc.evaluate(model, x_np, w_np, backend="iree") # llvm-cpu split + host dispatch
226
+ exe = evoxc.build(model, spec_x, spec_w, backend="iree", device=evoxc.Device("cuda", 0))
227
+ host = evoxc.run(exe, x_cuda, w_cuda)[0].to(evoxc.Device("cpu", 0)).numpy() # explicit D2H
228
+ ```
229
+
230
+ ## Test strategy
231
+
232
+ pytest, CPU only; unit tests per module in `../tests/<module>/`, plus the staging/design-principle compliance suite `../tests/test_spec_compliance.py` (closure-capture errors, `SymbolicTensor` purity, bind-as-sugar, vmap≡vectorize sugar, collective local shapes, serialization round-trips, explicit placement, DLPack interop via `importorskip`).
233
+ The per-suite inventory (file list, test counts, known skips/gates) is owned by `../tests/CONTEXT.md`.
234
+
235
+ ## Full-model forward (Llama / GPT-2 transformers) — readiness map
236
+
237
+ One-graph full transformer forward is feasible on **iree** (llvm-cpu/cuda/rocm); `xla` needs fully static shapes + `dot_precision="HIGHEST"` (TF32); **tvm cannot run it** (single-function/single-output, no `gather`/control flow).
238
+
239
+ - **Absent — must be composed:** `rsqrt` (use `divide(1.0, sqrt(x))` or `power(x, -0.5)`), `softmax`, `layer_norm`, `rms_norm`, `log_softmax`, `iota`, `einsum`, `silu`, `logistic`. Mask primitive is `evoxc.select(pred, a, b)` (`where` exists only as `evoxc.numpy.where`); index generation is `evoxc.arange` (Constant op, static bounds only). Canonical compositions: `ops/CONTEXT.md`.
240
+ - **`evoxc.gelu` is the exact erf form** (not HF's tanh approximation) — and `erf`/`gelu` are both exporter `DEFERRED_OPS`, so a GPT-2-style GELU FFN cannot be lowered on any compiler adapter; use the tanh-approx formula (`tanh`/`power` export) or stay on numpy. Llama SiLU is fine (`sigmoid` → `stablehlo.logistic`).
241
+ - **Also deferred** (`backends/stablehlo/ops.py`): `cumsum`, `cumprod`, `tril`, `triu`, `flip`, `roll`, `nan_to_num`, `diagonal`, `solve`, linalg factorizations, `runtime_call`/`external_call`/`block_call`, all `sparse_*`. Build causal masks from `arange` compares broadcast together — never an `(S,S)` `evoxc.constant` (`_constant_text` inlines the payload).
242
+ - **`gather` IS exportable** (single-axis; static operand + index SHAPES, runtime index VALUES) ⇒ `evoxc.gather(embed_table, ids, axis=0)` works on iree. `evoxc.slice` requires static lengths — there is no dynamic slice.
243
+ - **Batched `dot` works**: `(B,H,S,D) × (B,H,D,S)` with matched static batch dims emits one `dot_general`; contracting dims are fixed to lhs-last × rhs-second-last. Symbolic reshape / symbolic batch *broadcast* defer, so attention head reshapes need static shapes.
244
+ - **Weights**: pass `{"w1": TensorSpec((in, out), float32), ...}` as ONE positional defn arg (dict pytree; keys sorted, order-insensitive, no input-count limit). Cost ≈2–3.5 µs/leaf per `run` (400 leaves ≈ 1 ms), and non-cpu executables require pre-placed device tensors. Never `evoxc.constant` a weight (export inlines the payload).
245
+ - **Unmeasured**: compile-time / vmfb scaling for thousands of ops + 100+ inputs (largest validated graph ≈11 inputs). Capture weights inside `while` bodies rather than carrying them (iree `AffinityAnalysis` SEGV at ≥3–4 carries with `select`).
246
+
247
+ ## Notes for agents
248
+
249
+ - Keep modules thin and single-purpose; files under ~1000 lines (split along declared boundaries instead).
250
+ - Shared capability goes to the lowest common ancestor module per the contracts above — do not duplicate (e.g. numpy kernels live ONLY in `backends/numpy`).
251
+ - `evoxc/__init__.py` re-exports this exact surface; when adding a public name, update `__init__.py` and this contract together.
252
+ - Keep this file to the API contract + routing table: new per-feature detail belongs in the owning child node's CONTEXT.md plus a routing-table row here.
253
+ - **`run`'s per-call host cost is leaf-driven, not graph-driven** — per-IO leaf ≈2–3.5 µs, per-op ≈0 (pytree nesting irrelevant), `_prepare_flat_inputs`/`_unflatten_outputs` ≈24–31 µs with the backend invoke dominating; both halves are plan-driven and plans cache metadata only, never values (per-leaf dtype/shape/device + pre-sized output slots, one tuple compare for all-static shapes, path strings only on the failure branch, `core.Tensor` outputs passed through untouched), and no validation or error message is ever skipped.
254
+ - **Measured at 12 in/12 out** (`evoxc.run`, warm best-of-240; compare deltas, absolute levels drift ~10 % on a shared MI300X VF): iree/rocm −17.7 µs (−12.8 %), xla/rocm −7.2 µs (−6.0 %), iree llvm-cpu −16.5 µs (−17.1 %), numpy/cpu −0.9 µs (control; pipeline share alone 33.8 → 28.1 µs); per-output slope iree 5.3 → 4.4, xla 4.6 → 4.2, llvm-cpu 3.8 → 2.7 µs.
255
+ - The full stage ladder, bare-metal bounds and the remaining levers (PJRT async execute events; `core.unflatten` ≈4.7 µs of the ≈5 µs unflatten) live in `./backends/adapters/CONTEXT.md` Known Issue 14; don't re-derive them.
evoxc/__init__.py ADDED
@@ -0,0 +1,301 @@
1
+ """evoxc — EvoX Compiler.
2
+
3
+ A minimal, explicit, compiler-neutral tensor graph compiler and runtime.
4
+
5
+ The public surface is the contract documented in this package's CONTEXT.md
6
+ (read it). Everything here is an explicit staging step or a transparent
7
+ composition of explicit steps — nothing silently traces, compiles, moves, or
8
+ communicates.
9
+
10
+ Typical explicit workflow::
11
+
12
+ @evoxc.defn
13
+ def f(x, w):
14
+ return evoxc.dot(x, w)
15
+
16
+ graph = evoxc.trace(f, evoxc.TensorSpec((B, D), evoxc.float32), evoxc.TensorSpec((D, H), evoxc.float32))
17
+ graph = evoxc.vmap(graph, ...) # optional
18
+ lowered = evoxc.lower(graph)
19
+ artifact = evoxc.compile(lowered)
20
+ executable = evoxc.load(artifact, device="cpu")
21
+ y = evoxc.run(executable, x, w)
22
+
23
+ Convenience shorthands (documented compositions only)::
24
+
25
+ exe = evoxc.build(f, *specs, device="cpu") # trace→lower→compile→load
26
+ y = evoxc.evaluate(f, x, w) # derive specs → build → run
27
+
28
+ Pytree utilities (pure sugar over flatten/unflatten — no new semantics):
29
+
30
+ evoxc.tree_map(fn, *trees) # map over leaves, structure-validated
31
+ evoxc.tree_leaves(tree) # all leaves in pre-order
32
+ evoxc.tree_structure(tree) # the TreeSpec of a tree
33
+ evoxc.tree_flatten(tree) # (leaves, treespec)
34
+ evoxc.tree_unflatten(leaves, spec) # rebuild a tree from leaves + spec
35
+ """
36
+ from __future__ import annotations
37
+
38
+ from importlib.metadata import PackageNotFoundError as _PackageNotFoundError
39
+ from importlib.metadata import version as _distribution_version
40
+
41
+ # pyproject.toml's `[project].version` is the SINGLE source of truth for the
42
+ # version — this package only reads it back from the installed distribution
43
+ # metadata, so the two can never drift.
44
+ try:
45
+ __version__ = _distribution_version("evoxc")
46
+ except _PackageNotFoundError: # a bare source checkout: no installed distribution
47
+ __version__ = "0.0.0+unknown"
48
+
49
+ # --- Value model (evoxc.core) ------------------------------------------------
50
+ from . import core # noqa: F401
51
+ from .core import ( # noqa: F401
52
+ BackendError,
53
+ DTypeError,
54
+ Device,
55
+ DeviceError,
56
+ Dim,
57
+ DimExpr,
58
+ EVOXCError,
59
+ PersistenceError,
60
+ ShapeError,
61
+ SymbolicTensor,
62
+ Tensor,
63
+ TensorSpec,
64
+ TraceError,
65
+ TransformError,
66
+ TreeSpec,
67
+ VerificationError,
68
+ bool_,
69
+ complex128,
70
+ complex64,
71
+ devices,
72
+ dim,
73
+ dtype,
74
+ empty,
75
+ flatten,
76
+ float16,
77
+ float32,
78
+ float64,
79
+ from_dlpack,
80
+ from_numpy,
81
+ full,
82
+ int8,
83
+ int16,
84
+ int32,
85
+ int64,
86
+ ones,
87
+ register_pytree_node,
88
+ replicate_tensor,
89
+ split_tensor,
90
+ tensor,
91
+ tree_flatten,
92
+ tree_leaves,
93
+ tree_map,
94
+ tree_structure,
95
+ tree_unflatten,
96
+ uint8,
97
+ uint16,
98
+ uint32,
99
+ uint64,
100
+ unflatten,
101
+ zeros,
102
+ )
103
+
104
+ # --- Tensor operations (evoxc.ops) -------------------------------------------
105
+ from . import ops # noqa: F401
106
+ from .ops import ( # noqa: F401
107
+ abs,
108
+ acos,
109
+ add,
110
+ argmax,
111
+ argmin,
112
+ argsort,
113
+ bitwise_and,
114
+ bitwise_left_shift,
115
+ bitwise_or,
116
+ bitwise_right_shift,
117
+ bitwise_xor,
118
+ broadcast,
119
+ cast,
120
+ clamp,
121
+ ceil,
122
+ cholesky,
123
+ concatenate,
124
+ constant,
125
+ conv,
126
+ cos,
127
+ cumprod,
128
+ cumsum,
129
+ diag,
130
+ diagonal,
131
+
132
+ divide,
133
+ dot,
134
+ eigh,
135
+ equal,
136
+ erf,
137
+ exp,
138
+ eye,
139
+ flip,
140
+ floor,
141
+
142
+ gather,
143
+ gelu,
144
+ greater,
145
+ greater_equal,
146
+ isnan,
147
+ less,
148
+ less_equal,
149
+ linspace,
150
+ log,
151
+ log1p,
152
+ logical_and,
153
+ logical_not,
154
+ logical_or,
155
+ matmul,
156
+ matrix_exp,
157
+ matrix_rank,
158
+ max,
159
+ maximum,
160
+ mean,
161
+ median,
162
+ min,
163
+ minimum,
164
+ multiply,
165
+ nan_to_num,
166
+ nansum,
167
+
168
+ negate,
169
+ norm,
170
+ not_equal,
171
+ pad,
172
+ power,
173
+ prod,
174
+ qr,
175
+ reduce_max,
176
+ reduce_mean,
177
+ reduce_min,
178
+ reduce_prod,
179
+ reduce_sum,
180
+ relu,
181
+ remainder,
182
+ reshape,
183
+ roll,
184
+ round,
185
+
186
+ runtime_call,
187
+ scatter,
188
+ select,
189
+ sigmoid,
190
+ sign,
191
+ sin,
192
+ slice,
193
+ sort,
194
+ solve,
195
+ sqrt,
196
+ square,
197
+ stack,
198
+ std,
199
+ stop_gradient,
200
+ subtract,
201
+ sum,
202
+ svd,
203
+ tan,
204
+ tanh,
205
+ tile,
206
+ topk,
207
+ # NOTE: the matrix-trace op is NOT exported at the top level — `evoxc.trace`
208
+ # is the tracing function (foundational API). The op lives at
209
+ # `evoxc.ops.trace`.
210
+
211
+ transpose,
212
+ tril,
213
+ triu,
214
+ var,
215
+ external_call,
216
+ )
217
+
218
+ # --- Tracing (evoxc.trace) ---------------------------------------------------
219
+ # NOTE: `evoxc.trace` (the function) intentionally shadows the `evoxc.trace`
220
+ # submodule as an attribute — `import evoxc.trace` / `from evoxc.trace import ...`
221
+ # still work through the import system. Same applies to `evoxc.numpy` below.
222
+ from . import trace # noqa: F401 (submodule)
223
+ from .trace import Defn, Graph, cond, defn, scan, trace, while_loop # noqa: F401
224
+
225
+ # --- Graph transforms (evoxc.transforms) -------------------------------------
226
+ from . import transforms # noqa: F401
227
+ from .transforms import ( # noqa: F401
228
+ BatchReport,
229
+ SwitchRecord,
230
+ batch_functions,
231
+ grad,
232
+ jvp,
233
+ vectorize,
234
+ vjp,
235
+ vmap,
236
+ )
237
+
238
+ # --- Backends (evoxc.backends) -----------------------------------------------
239
+ from . import backends # noqa: F401
240
+ from .backends import ( # noqa: F401
241
+ Backend,
242
+ Capabilities,
243
+ CompiledArtifact,
244
+ LoweredProgram,
245
+ numpy_backend,
246
+ )
247
+
248
+ # --- Distributed collectives (evoxc.dist) ------------------------------------
249
+ from . import dist # noqa: F401
250
+
251
+ # --- Sparse tensors (evoxc.sparse) -------------------------------------------
252
+ from . import sparse # noqa: F401
253
+
254
+ # --- Custom blocks (evoxc.block) ---------------------------------------------
255
+ from . import block # noqa: F401 (submodule)
256
+ from .block import BlockOp, block, get_block # noqa: F401
257
+
258
+ # --- External kernels (evoxc.external) ----------------------------------------
259
+ from . import external # noqa: F401 (submodule; the kernel registry)
260
+ from .external import ( # noqa: F401
261
+ ExternalKernel,
262
+ get_external_kernel,
263
+ get_portable,
264
+ register_external_kernel,
265
+ register_portable,
266
+ unregister_external_kernel,
267
+ )
268
+
269
+ # --- NumPy-like namespace (evoxc.numpy) --------------------------------------
270
+ from . import numpy # noqa: F401
271
+ from . import numpy as enp # noqa: F401 (documented alias)
272
+ from .numpy import arange # noqa: F401 (GRAPH creation op — same object as
273
+ # enp.arange; top-level evoxc.zeros/ones/full/empty are the CONCRETE core
274
+ # creators, arange has no concrete counterpart)
275
+
276
+ # --- Key-based functional RNG (evoxc.random) ----------------------------------
277
+ from . import random # noqa: F401 (submodule; the evoxc.random API surface)
278
+
279
+ # --- Host data IO (evoxc.io) -------------------------------------------------
280
+ from . import io # noqa: F401 (submodule; the evoxc.io.prefetch/sink/AsyncCopy/wait_all surface)
281
+
282
+ # --- Persistence / cache (evoxc.persist) -------------------------------------
283
+ from . import persist # noqa: F401
284
+ from .persist import Cache, FileCache # noqa: F401
285
+
286
+ # --- Execution pipeline (evoxc.pipeline) -------------------------------------
287
+ from . import pipeline # noqa: F401
288
+ from .pipeline import ( # noqa: F401
289
+ BoundExecutable,
290
+ Executable,
291
+ bind,
292
+ build,
293
+ compile,
294
+ evaluate,
295
+ load,
296
+ lower,
297
+ run,
298
+ )
299
+
300
+ # --- Memoized build sugar (evoxc.build_cache) ---------------------------------
301
+ from .build_cache import CompileCache, build_cached # noqa: F401