Skip to content
serkanaltuntasPublic

About

A Python-first tensor runtime with CPU, Metal, and CUDA backends and an experimental kernel compiler.

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

162 Commits

Folders and files

Repository files navigation

tensor.cx

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.

Documentation Map

Development Setup

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 uv

Use uv for Python environments and commands:

uv venv
source .venv/bin/activate
uv pip install -e ".[dev]"
uv run pytest

On a machine without Metal, or when validating the CPU-only path:

CMAKE_ARGS="-DTENSORCX_ENABLE_METAL=OFF" uv pip install -e ".[dev]"
uv run pytest

To 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.py

The 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 prototype setup

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 pytest

52 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.

Verification

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-failure

GitHub 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.py

To 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.py

Use 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 2

Current Status

Phase 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)

Behavior notes

  • Constructors, including randn, validate the requested device before materializing input data or allocating random arrays.
  • empty contents are unspecified; use zeros/ones for initialized storage. CUDA empty allocates directly without a CPU buffer, upload or fill kernel; see factory semantics and measurements.
  • cx.testing.assert_allclose requires 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, int32 and bool. Float inputs are narrowed to float32, so values may lose precision or overflow to inf.
  • 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.
  • int32 add/subtract/multiply/negate overflow wraps (defined two's-complement), matching NumPy and identical on CPU and Metal.
  • sum, max, and mean accept axis=None (default: all axes), one integer or an axis sequence such as (0, -1). keepdims=True retains every selected axis with size 1. An empty selection () copies. Sum over a zero-size selected axis returns zeros, mean returns NaNs, and max raises ValueError. Multi-axis mean sums each group then divides once; dtype limits are unchanged.
  • x.transpose(axes=None) / cx.transpose(x, axes=None) and x.T permute axes into a new contiguous buffer on the same device, including identity/scalar copies. x.squeeze(axis=None) and x.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, and cx.split return 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, and x[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 @ b support 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/sqrt support float32; abs, min, argmax, clip, and topk support float32/int32 on CPU/Metal/CUDA. Indices are int32 with deterministic first-index ties; topk returns (values, indices). See math and selection.
  • Inference adds float32 linear, affine normalization, int32-indexed embedding, and attention / scaled_dot_product_attention on 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 linear custom 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.
  • softmax requires an explicit axis, preserves the input shape, supports negative axes, and uses max-subtraction for numerical stability.
  • rmsnorm requires an explicit axis, preserves the input shape, supports negative axes, and accepts eps with default 1e-5. It computes x / sqrt(mean(x*x, axis, keepdims=True) + eps) with optional keyword weight.
  • layernorm requires an explicit axis, preserves the input shape, supports negative axes, and accepts eps with default 1e-5. It computes (x - mean) / sqrt(variance + eps), with mean and variance taken along axis as keepdims=True, with optional keyword weight and bias.
  • mean, exp, gelu, silu, softmax, rmsnorm, and layernorm currently support float32 tensors only; int32 inputs are rejected instead of being implicitly cast. gelu uses the common tanh approximation.
  • cx.experimental.kernel is a Phase 7 experimental parser/emitter/compiler launch scaffold. It exposes parse_ir(), text-only emit_msl(), and compile(target="metal") for an in-memory metallib artifact when Apple Metal command-line tools are available. The returned CompiledKernel can validate Metal library load/function lookup with validate_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 (bounded for/accumulator) kernels with launch(...); 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 through BackendExecution; 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 under cx.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. Optional cx.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.

Naming

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

About

A Python-first tensor runtime with CPU, Metal, and CUDA backends and an experimental kernel compiler.

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages