tensor.cx is an independent Python-first accelerator runtime and kernel compiler
project, starting with Apple Metal. Install and import it as tensorcx.
tensor.cx is currently a research/runtime engineering project, not a general-purpose machine-learning framework. Its purpose is to build a compact tensor runtime with a backend-neutral C++ core, a Python API, a mandatory CPU reference path, and accelerator backends that can be validated operation by operation. Apple Metal is the first accelerator backend; a small CUDA prototype is also available. An optional Linux Vulkan/SPIR-V backend now supports GPU copies, factories, basic arithmetic, casts and contiguous indexing/shape/join operations, comparisons/masks, boolean reductions and numeric sum/max/mean/min/argmax, float32 vector/batched matmul and log/sqrt/abs/clip/topk, activations, normalization and inference, plus opt-in profiling, allocation diagnostics and bounded reuse and explicit guarded MLIR/SPIR-V kernels. Opt-in CUDA/Vulkan shared allocations use compatible external memory and semaphores on a matching physical GPU. ROCm and broader MLIR-based lowering remain longer-term directions.
The project is useful today as:
- a small Python tensor runtime for CPU and Apple Metal experiments
- a reference implementation for backend abstraction, operation dispatch, and CPU-vs-device correctness testing
- a foundation for future custom kernel compilation work
It is intentionally not a PyTorch, JAX, TensorFlow, MLX, Triton, or training framework replacement. Autograd, distributed training, broad dtype coverage, async streams, ROCm, and production compiler integration are not part of the current runtime.
The first milestone was deliberately small:
Python API -> C++20 core -> Metal backend -> static MSL add kernel -> correct result
That milestone has been achieved. The current runtime now includes CPU and Metal tensor operations, matmul, reductions, selected neural-network primitives, an experimental Metal kernel DSL, a hardened backend execution ABI, and a completed Phase 10 MLIR decision prototype. Phase 9 CUDA is complete: the optional backend supports discovery, float32/int32 copies, and float32 elementwise operations, matmul, reductions and normalization on a validated NVIDIA host. Native int32 fill, arithmetic and sum/max are also supported. Explicit experimental MLIR CPU compile/launch is available for guarded float32 elementwise kernels on Linux x86_64 with external LLVM 21.1.8 tools. See the usage and limitations.
docs/PYTORCH_PERFORMANCE_REVIEW.md: measured CPU/CUDA PyTorch latency gaps, source-backed causes and proposed optimization work (Turkish report; shared-host limits).docs/NAMING.md: tensor.cx branding and migration from the pre-release Cortex Runtime names.docs/TENSOR_API.md: arithmetic/scalars, broadcasting, casts, transpose, shared-storage shape views, and reductionkeepdimscontracts.website/: Astro + Starlight product site and curated user guides for tensor.cx.CONTRIBUTING.md: contributions, validation and publication hygiene.SECURITY.md: private vulnerability reporting and trust boundaries.THIRD_PARTY_NOTICES.md: notices included in source and wheels.PROJECT.md: source of truth for project purpose, roadmap, phase status, acceptance criteria, and major engineering decisions.docs/ROADMAP.md: short status summary, what works today, what is intentionally deferred, and next known decisions.docs/ARCHITECTURE.md: runtime layers, backend boundaries, dispatch model, error taxonomy, and core invariants.docs/BACKENDS.md: backend ABI, execution contract, buffer ownership, launch metadata, and future backend expectations.docs/METAL_BACKEND.md: Apple Metal-specific implementation notes and current limitations.docs/VULKAN_BACKEND.md: optional Linux Vulkan setup, supported arithmetic, device selection and real-GPU validation limits.docs/CUDA_PHASE9_ENVIRONMENT.md: CUDA environment decision gate and Phase 9 validation requirements.docs/PHASE_SEQUENCING_DECISION.md: rationale and guardrails for completing Phase 10 before Phase 9.docs/KERNEL_DSL.md: experimental kernel DSL scope, supported subset, and non-goals.docs/MLIR_DECISION.md: Phase 10 MLIR decision record and prototype result.docs/MLIR_RUNTIME_INTEGRATION_DECISION.md: CPU-first runtime integration, setup, and acceptance evidence.docs/MLIR_CUDA_INTEGRATION_DECISION.md: CUDA add/subtract/multiply compile/launch usage, ABI/toolchain scope and sm_52 validation.docs/MLIR_CUDA_EXPRESSIONS_DECISION.md: bounded local/nested expression support and its numerical/ownership contract.docs/MLIR_DIVISION.md: float32 kernel division, CPU/CUDA IEEE checks and direct MSL limits.docs/MLIR_SELECT.md: float32 kernel comparisons, internal boolean locals and explicit value selection.docs/MLIR_SQRT.md: guarded float32 kernel square root, strict CPU/CUDA lowering and numerical limits.docs/MLIR_ABS.md: float32 kernel absolute value, sign-bit semantics and retained signature/ownership limits.docs/MLIR_LOG.md: guarded float32 natural logarithm, domain rules and bounded numerical error.docs/MLIR_RSQRT.md: guarded float32 reciprocal square root, signed-zero/domain rules and relative-error acceptance.docs/MLIR_SILU.md: guarded float32 SiLU, stable negative tails, signed zeros and target-specific numerical scope.docs/MLIR_SIGMOID.md: guarded float32 stable logistic function, tail/underflow acceptance and target limits.docs/MLIR_TANH.md: guarded float32 hyperbolic tangent, signed-zero/saturation rules and sm_52-compatible lowering.docs/MLIR_EXP.md: guarded float32 exp, bounded numerical error and target/cache policies.docs/MLIR_MINMAX.md: guarded float32 minimum/maximum, NaN/zero rules and target-specific lowering.docs/CUDA_INT32.md: native int32 factories, wrapping arithmetic and signed sum/max validation.docs/CUDA_PRODUCT_COMPLETION.md: active CUDA product completion work and remaining evidence.docs/CUDA_PERFORMANCE.md: reproducible CUDA/MLIR compile, copy, primitive and end-to-end benchmarks with CPU parity.docs/CUDA_FUSION_EXPERIMENT.md: balanced native/separate-MLIR/manual-fused comparisons with separate CUDA diagnostics.docs/CUDA_OUTPUT_COPY_ELISION.md: proved full-write CUDA template-copy removal, legacy compatibility and paired measurements.docs/PORTABLE_WHEELS.md: separate CPU/Vulkan manylinux wheels for CPython 3.11–3.13, local/manual CI builds and current release limits.docs/DISTRIBUTION.md: source archive and wheel validation, fresh installation, external dependencies and supported hosts.docs/DEVICE_TRANSFERS.md: explicit host-staged device placement and independent same-device copies.docs/SHARED_STORAGE.md: explicit shared allocation, CUDA/Vulkan ownership, DLPack boundaries and lifetime.docs/DIAGNOSTICS.md:tensorcx-doctor, declared operation/dtype capabilities, installation and CPU/CUDA memory snapshots.docs/COMPILATION_CACHE.md: persistent experimental CPU/CUDA/Metal/Vulkan artifacts, compatibility keys, private storage and compile/launch profiling.docs/CUDA_CONTINUOUS_VALIDATION.md: exact-commit CUDA acceptance and Nightblade's opt-in local push gate.docs/VULKAN_CONTINUOUS_VALIDATION.md: exact-commit real-GPU Vulkan/MLIR acceptance and optional combined CUDA sharing.experiments/opencl/: standalone NVIDIA GPU and PoCL CPU execution probes; not a production OpenCL backend.experiments/vulkan/: separate Mesa lavapipe software execution/readback probe with mandatory CPU references.docs/CUDA_PRIMITIVES_VALIDATION.md: CUDA primitive semantics, CPU parity and a runnable inference example.
For a checkout with local LLVM/MLIR configured in an ignored .env, use
uv run --env-file .env --no-sync ... from the repository root to load its
TENSORCX_LLVM_BIN in each invocation. Bare uv run does not load this file
automatically. Keep machine-specific paths out of Git; see TASKS.md for the
local environment record. Ordinary CPU tensor operations do not require LLVM.
tensor.cx is developed first on Apple Silicon macOS. The default build uses
TENSORCX_ENABLE_METAL=AUTO: it enables Metal when the Apple Metal command-line
tools are available and otherwise falls back to a CPU-only build.
command -v uvUse uv for Python environments and commands:
uv venv
source .venv/bin/activate
uv pip install -e ".[dev]"
uv run pytestOn a machine without Metal, or when validating the CPU-only path:
CMAKE_ARGS="-DTENSORCX_ENABLE_METAL=OFF" uv pip install -e ".[dev]"
uv run pytestTo require Metal and fail clearly if the command-line tools are missing:
CMAKE_ARGS="-DTENSORCX_ENABLE_METAL=ON" uv pip install -e ".[dev]"Run the basic local benchmark with:
uv run python benchmarks/bench_elementwise.py
uv run python benchmarks/bench_copy.py
uv run python benchmarks/bench_matmul.pyThe copy and elementwise benchmarks use the Phase 4 element-count sizes by
default: 1K, 16K, 256K, 1M, and 16M float32 elements. The matmul benchmark uses
matrix triplets such as 16x16x16, 32x64x16, and 64x64x64.
A local Apple Silicon sample run is committed at
benchmarks/sample_phase4_apple_silicon.txt. The Phase 5 matmul sample is at
benchmarks/sample_phase5_matmul_apple_silicon.txt.
CUDA is opt-in (TENSORCX_ENABLE_CUDA=OFF by default); CPU-only and Apple builds
need no CUDA toolkit. CUDA-enabled extensions require libcuda.so.1 at import;
the GPU-free CI container supplies a Toolkit stub for validation only. On a CUDA host with a supported C++20 compiler and nvcc:
CMAKE_ARGS="-DTENSORCX_ENABLE_METAL=OFF -DTENSORCX_ENABLE_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=52" uv pip install -e ".[dev]"
TENSORCX_REQUIRE_BACKENDS=cuda TENSORCX_REQUIRE_BACKEND_CAPABILITIES=cuda:copy,cuda:tensor_factories_float32,cuda:binary_ops_float32 uv run pytest52 is Nightblade's GTX 980 Ti target, validated with CUDA 12.4 and GCC 13.
Select an architecture supported by your GPU and installed toolkit; select
CC, CXX, and CUDAHOSTCXX if the default host compiler is incompatible.
Full Nightblade commands and C++ checks:
docs/CUDA_PHASE9_VALIDATION.md.
x = cx.ones((257,), device="cuda")
y = (x + x) * x
print(y.cpu().numpy()[:3]) # [2. 2. 2.]The prototype exposes only device index 0. float32 add/subtract/multiply/divide
support broadcast-compatible shapes with matching dtypes; Python/NumPy real scalars, negation,
rank-0 and empty contiguous tensors work. Copies preserve
float32/int32/bool, and astype converts explicitly between them on the device.
Float32 matmul (auto/custom), sum/max/mean, exp/GELU/SiLU,
softmax, RMSNorm and LayerNorm are implemented; see semantics and validation.
Transpose supports float32/int32/bool and returns a contiguous device copy; squeeze
and expand_dims share storage without copying, like reshape.
Int32 fill, wrapping add/subtract/multiply/scalars/negate and sum/max are also
implemented; division and mean require float32. See the int32 contract.
Broad generated CUDA kernels remain outside the supported subset. A separate
explicit MLIR compiler supports guarded float32 add/subtract/multiply/divide on the validated sm_52
host; see usage and requirements. Operations are
synchronous and release the Python GIL during execution. CUDA is registered
only when its compiled backend and a usable device are available. CPU remains
the default for constructors; best_device() can select CUDA when available.
The CUDA build CI job uses a pinned CUDA 12.4 container on a CPU-only hosted runner. It checks compile/link and unavailable-device fallback; it does not claim GPU execution. Run strict CUDA tests on a real host as described above.
CPU-only CI runs on GitHub Actions with Metal disabled:
CMAKE_ARGS="-DTENSORCX_ENABLE_METAL=OFF" uv pip install -e ".[dev]"
uv run pytest
NANOBIND_DIR="$(uv run python -c 'import nanobind; print(nanobind.cmake_dir())')"
PYTHON_EXECUTABLE="$(uv run python -c 'import sys; print(sys.executable)')"
cmake -S . -B build/cpp-tests -DTENSORCX_ENABLE_METAL=OFF -DTENSORCX_BUILD_TESTS=ON -Dnanobind_DIR="${NANOBIND_DIR}" -DPython_EXECUTABLE="${PYTHON_EXECUTABLE}"
cmake --build build/cpp-tests
ctest --test-dir build/cpp-tests --output-on-failureGitHub Actions also runs macOS Metal-on build jobs with MPSGraph enabled and disabled. Hosted runners may still skip runtime Metal tests when a usable Metal device is unavailable, but those jobs catch Apple framework compile/link breaks.
Local Metal verification should be run on Apple Silicon macOS:
xcode-select -p
xcrun -sdk macosx --find metal
xcrun -sdk macosx --find metallib
CMAKE_ARGS="-DTENSORCX_ENABLE_METAL=ON" uv pip install -e ".[dev]"
uv run pytest
uv run python benchmarks/bench_elementwise.py
uv run python benchmarks/bench_copy.py
uv run python benchmarks/bench_matmul.pyTo verify that custom Metal matmul works without the optimized primitive path:
CMAKE_ARGS="-DTENSORCX_ENABLE_METAL=ON -DTENSORCX_ENABLE_MPSGRAPH=OFF" uv pip install -e ".[dev]"
uv run pytest tests/python/test_matmul.pyUse a smaller benchmark smoke test while iterating:
uv run python benchmarks/bench_elementwise.py --sizes 1024 --repeats 2
uv run python benchmarks/bench_copy.py --sizes 1024 --repeats 2
uv run python benchmarks/bench_matmul.py --sizes 16x16x16 --repeats 2Phase 7 is complete. The experimental kernel DSL under cx.experimental can
parse a restricted Python kernel into backend-neutral IR, emit text MSL, compile
that MSL into an in-memory Metal library artifact, validate the generated
function through native Metal library lookup, and launch float32 elementwise
and rowwise-reduction (bounded for/accumulator) kernels on Metal, with
Kernel.reference(...) as the CPU reference execution path. Phase 8 is complete: the backend ABI, shared
primitive/kernel contract validators, and null backend scaffold exist, and CPU
fill, add/multiply, unary transforms, reductions, and matmul route through
CpuBackend::execute. Metal add/multiply, unary transforms, axis/norm
transforms, reductions, matmul, and fill now also route through
MetalBackend::execute; the experimental generated-kernel launch path also
enters Metal through BackendExecution. Phase 9 is complete on Nightblade:
CUDA discovery, copies, and float32 fill/add/multiply use the existing registries
and execution contract. Setup and validation are in
docs/CUDA_PHASE9_ENVIRONMENT.md and docs/CUDA_PHASE9_VALIDATION.md.
Phase 10 (MLIR exploration) is complete and
ran ahead of Phase 9 under a documented sequencing exception: the decision
record docs/MLIR_DECISION.md answers "yes" — the experimental add kernel
lowers tensor.cx IR → MLIR → native code and matches the CPU reference
(experiments/mlir/) — the follow-up integration decision defines the now-implemented
optional compiled CPU path. LLVM/MLIR remains an external toolchain used only
by explicit compilation; the bounded experimental CUDA path also requires the
validated CUDA toolchain. Phase 5 provides
CPU reference matmul, a correctness-first custom Metal matmul kernel, and an
optimized Metal primitive path. Phase 6 adds sum, max, mean, exp,
gelu, silu, softmax, rmsnorm, and layernorm on CPU and Metal. The
custom matmul kernel remains available through
cx.matmul(a, b, backend="custom"); backend="optimized" uses the Apple
optimized primitive path when it is enabled.
import tensorcx as cx
print(cx.devices())
x = cx.tensor([1, 2, 3], device="cpu")
y = cx.tensor([4, 5, 6], device="cpu")
z = x + y
print(z.numpy())
# [5 7 9]
device = cx.best_device()
x = cx.ones((1_000_000,), dtype=cx.float32, device=device)
y = cx.ones((1_000_000,), dtype=cx.float32, device=device)
z = x + y
print(z.cpu().numpy()[:5])
# [2. 2. 2. 2. 2.]
a = cx.randn((2, 3), device="metal", seed=1)
b = cx.randn((3, 4), device="metal", seed=2)
c = cx.matmul(a, b)
print(c.shape)
# (2, 4)
r = cx.mean(c, axis=1)
m = c.max(axis=0)
s = cx.softmax(c, axis=1)
rms = cx.rmsnorm(c, axis=1)
ln = cx.layernorm(c, axis=1)
e = cx.gelu(cx.silu(cx.exp(r)))
print(r.cpu().numpy().shape)
# (2,)
print(m.cpu().numpy().shape)
# (4,)
print(e.cpu().numpy().shape)
# (2,)
print(s.cpu().numpy().shape)
# (2, 4)
print(rms.cpu().numpy().shape)
# (2, 4)
print(ln.cpu().numpy().shape)
# (2, 4)- Constructors, including
randn, validate the requested device before materializing input data or allocating random arrays. emptycontents are unspecified; usezeros/onesfor initialized storage. CUDAemptyallocates directly without a CPU buffer, upload or fill kernel; see factory semantics and measurements.cx.testing.assert_allcloserequires equal shapes (including scalar rank). If either input has an integer or boolean dtype, it compares values exactly; floating-point tolerances apply only when both inputs are floating point.- Supported dtypes are
float32,int32andbool. Float inputs are narrowed tofloat32, so values may lose precision or overflow toinf. - Arithmetic accepts broadcast-compatible tensors or real scalars on either
side, without dtype promotion or device transfer. Division requires float32.
astype(dtype, copy=True)explicitly converts float32/int32/bool on the same device; float-to-int truncates toward zero and rejects non-finite/out-of-range values. See the full contract. int32add/subtract/multiply/negate overflow wraps (defined two's-complement), matching NumPy and identical on CPU and Metal.sum,max, andmeanacceptaxis=None(default: all axes), one integer or an axis sequence such as(0, -1).keepdims=Trueretains every selected axis with size 1. An empty selection()copies. Sum over a zero-size selected axis returns zeros, mean returns NaNs, and max raisesValueError. Multi-axis mean sums each group then divides once; dtype limits are unchanged.x.transpose(axes=None)/cx.transpose(x, axes=None)andx.Tpermute axes into a new contiguous buffer on the same device, including identity/scalar copies.x.squeeze(axis=None)andx.expand_dims(axis)(also top-level functions) share storage; float32/int32/bool work on CPU, Metal and CUDA.- Basic
x[key]indexing/slicing,cx.concat,cx.stack, andcx.splitreturn independent contiguous copies on CPU/Metal/CUDA (float32/int32/bool). Negative steps, integer indices, ellipsis and new axes are supported; boolean Tensor masks are supported separately; advanced integer indexing and indexed assignment are not. Split accepts equal section counts or NumPy-style cut indices; see the contract. - Comparisons (
==,!=,<,<=,>,>=) return bool tensors. Boolean logic (&,|,^,~),where,any/all, andx[mask]execute natively on CPU/Metal/CUDA. Masks match leading dimensions; full masks flatten the selected elements. See the contract. cx.matmul(a, b)/a @ bsupport float32 vectors, matrices and broadcasted batch axes on CPU/Metal/CUDA. Contracting dimensions must match; no dtype promotion or device transfer occurs. See matmul semantics.log/sqrtsupport float32;abs,min,argmax,clip, andtopksupport float32/int32 on CPU/Metal/CUDA. Indices are int32 with deterministic first-index ties;topkreturns(values, indices). See math and selection.- Inference adds float32
linear, affine normalization, int32-indexedembedding, andattention/scaled_dot_product_attentionon CPU/Metal/CUDA. Attention supports broadcasted batches and boolean/additive/causal masks; see the contracts and limits. - DLPack storage exchange on CPU/CUDA device 0 for contiguous float32/int32/bool,
plus an optional inference-only PyTorch
linearcustom op; see ownership, installation and limits. x.reshape(shape)/cx.reshape(x, shape)create a contiguous view sharing the native buffer; one dimension may be-1..numpy()still copies.softmaxrequires an explicitaxis, preserves the input shape, supports negative axes, and uses max-subtraction for numerical stability.rmsnormrequires an explicitaxis, preserves the input shape, supports negative axes, and acceptsepswith default1e-5. It computesx / sqrt(mean(x*x, axis, keepdims=True) + eps)with optional keywordweight.layernormrequires an explicitaxis, preserves the input shape, supports negative axes, and acceptsepswith default1e-5. It computes(x - mean) / sqrt(variance + eps), with mean and variance taken alongaxisaskeepdims=True, with optional keywordweightandbias.mean,exp,gelu,silu,softmax,rmsnorm, andlayernormcurrently supportfloat32tensors only;int32inputs are rejected instead of being implicitly cast.geluuses the common tanh approximation.cx.experimental.kernelis a Phase 7 experimental parser/emitter/compiler launch scaffold. It exposesparse_ir(), text-onlyemit_msl(), andcompile(target="metal")for an in-memory metallib artifact when Apple Metal command-line tools are available. The returnedCompiledKernelcan validate Metal library load/function lookup withvalidate_metal_function()when the native extension is built with Metal support and a Metal runtime is available, and can launch float32 elementwise and rowwise-reduction (boundedfor/accumulator) kernels withlaunch(...);Kernel.reference(...)runs the same IR on CPU tensors as the reference path. Calling a decorated kernel compiles and launches through the same experimental path. Non-empty launches enter the Metal backend throughBackendExecution; zero-thread launches validate the Metal function and return as no-ops. The launch path is synchronous, Metal-only, one-output, exact-shape, and still undercx.experimental.- Opt-in bounded
cx.memory_pool("cuda")reuses idle exact-size owned buffers within a current-thread scope, preserving synchronous operations and excluding DLPack-exposed storage; see the memory pool contract. - Opt-in Vulkan pools reuse staging/buffers and one completed command frame; physical-byte limits and diagnostics differ from CUDA.
- Opt-in
cx.profile()separates CPU/CUDA/Vulkan native allocation, copy, execution and existing wait regions using host timings; Metal is not instrumented. Optionalcx.profile(device_timing=True)adds separate CUDA kernel event intervals and Vulkan copy/compute timestamps; host and device durations are not combined. See runtime profiling. - Execution is synchronous, but native backend calls release the Python GIL, so
operations issued from multiple Python threads run concurrently in the native
layer and stay correct (shared caches are mutex-guarded; see
docs/METAL_BACKEND.md). There is still no async/stream API.
Product brand: tensor.cx
Python package/import: tensorcx
Documentation alias: import tensorcx as cx
Python extension module: tensorcx._core
C++ source root: cpp/tensorcx/
C++ namespace: tensorcx