This repository provides a native Ruby extension for fast matrix/tensor operations, packaged as the tensor gem. It runs matrix multiplication on CPU by default and can dispatch selected products to Apple Neural Engine (ANE) on Apple Silicon.
- Build the extension and gem:
ruby extconf.rbmakegem build tensor.gemspec
- Install locally:
gem install tensor-0.2.0.gem
In Ruby:
require "tensor"This defines a top-level Tensor class backed by the C extension (an order-2 tensor). Matrix is provided as a backwards-compatible alias.
m1 = Tensor.new(2, 2, dtype: "float32")
m2 = Tensor.new(2, 2, dtype: "float32")
product = m1.multiply(m2) # or m1.matmul(m2)
relu = product.relu
softmax = product.softmax
loss, grad = softmax.cross_entropy_loss([0, 1])- Supported dtypes for most math ops:
"float32","float64". - Integer dtypes (
"int16","int8") are supported for storage, indexing, and conversion, but many numeric operations will raiseArgumentErrorif used with integer matrices.
left = Tensor.from_arrays([[1, 2, 3], [4, 5, 6]], 32)
right = Tensor.from_arrays([[2, 3], [4, 5], [6, 7]], 32)
left.matmul(right) # CPU, also available as backend: :cpu
left.matmul(right, backend: :ane) # Opt in on Apple Silicon
Tensor.cpu_backend # :accelerate, :openblas, or :portable
Tensor.ane_available? # Whether the private runtime is availableCPU products use Accelerate on macOS, OpenBLAS when detected on other
platforms, or the portable C kernel. The multiply and matmul names share
the same options. Both inputs must be rank 2 with matching floating point dtypes.
The ANE path uses Apple's private Neural Engine API and IOSurface buffers. Both operands are runtime inputs. It accepts float32 tensors, computes in float16, and returns float32 storage. Use the CPU for float64, exceptional values, or when tighter numeric agreement is needed. ANE requests may fail on unsupported macOS versions or shapes. Each dimension is limited to 2048 and rounded up internally. The process retains up to eight compiled shapes. Explicit ANE requests raise on failure, so a caller can choose when to retry on the CPU. The CPU path remains the default for small matrices and for portable scripts. No GPU is required.
Configure with ruby extconf.rb --disable-ane to omit the ANE bridge. For a
hardware test after building, run TENSOR_REQUIRE_ANE=1 OMP_NUM_THREADS=1 ruby -I. test/test_tensor.rb.
The default suite also checks the error path when ANE is unavailable.
Thanks to @mechramc and the Orion contributors.
TensorGem adapted Orion's private ANE model loading and request evaluation
sequence from core/ane_runtime.m.
TensorGem adds its own matrix multiplication program, shape cache, and Ruby
interface. Orion's MIT notice, which credits Murai Labs, is included in
LICENSE-Orion.
- Create tensors by shape:
Tensor.zeros(shape: [batch, channels, height, width], dtype: "float32")t.shape #=> [b, c, h, w],t.rank,t.size.
- Build from nested Ruby arrays:
Tensor.from_array(nested, "float32")wherenestedis a rectangular N-D array.
- N-D indexing:
t[batch, channel, i, j]to get/set a scalar element (negative indices supported).t.to_areturns nested arrays matchingt.shape.
For now, higher-order tensors primarily support storage, indexing, and conversion; linear algebra and neural-network operations (e.g., matmul, softmax, cross_entropy_loss) are defined for 2D tensors, and batched N-D versions can be added next.
- The C code uses OpenMP (
#pragma omp parallel for) for:- Portable matrix multiplication (
multiply/matmul) - Element-wise ops (
subtract,hadamard,scale, ReLU, ReLU grad) - Cross-entropy loss and gradient
- Portable matrix multiplication (
- The number of threads is chosen as:
OMP_NUM_THREADS(if set by your environment/OpenMP runtime), otherwiseomp_get_max_threads()at runtime, or a fallback of 16 when OpenMP is not available.
To force single-threaded execution (for debugging or deterministic benchmarking), set:
export OMP_NUM_THREADS=1To allow more parallelism (on a machine with many cores), set for example:
export OMP_NUM_THREADS=8Note: the extension currently runs heavy OpenMP regions under Ruby’s Global VM Lock (GVL), so long-running operations can block other Ruby threads even though native work is parallelised internally. Use separate Ruby processes (e.g., via Process.fork or job systems) for true multi-process parallelism.
- Ruby with development headers (e.g., via
rbenv/rvmandruby-build). - A C toolchain:
- macOS: Xcode Command Line Tools (
xcode-select --install). - Linux:
gcc,make, and standard build tools.
- macOS: Xcode Command Line Tools (
- Optional but recommended:
- OpenMP runtime (
libompon macOS,libgomp/libompon Linux) for multi-threaded kernels. - OpenBLAS for CPU matrix multiplication on platforms without Accelerate.
- OpenMP runtime (
On macOS with Homebrew:
brew install libompThe extension uses the macOS system Accelerate framework without an OpenBLAS dependency. Linux builds can pick up OpenBLAS via pkg-config or OPENBLAS_DIR.