tensor 0.1.1 → 0.2.0
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.
- checksums.yaml +4 -4
- data/LICENSE-Orion +21 -0
- data/README.md +119 -0
- data/extconf.rb +21 -47
- data/ruby_matrix.c +84 -5
- data/tensor_ane.h +11 -0
- data/tensor_ane.m +192 -0
- metadata +7 -3
- data/AGENTS.md +0 -38
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 3d77b035713014f0d56c71f7cffc7bfb645d0eb44244a02c5ec9e72afbc9ea5c
|
|
4
|
+
data.tar.gz: ef5f3b47ff6013214039b28c34c826a2f1dbf7cab05b6c2b074fc1c5a69a4bdc
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 8f8bd13f097063c454e3f1bab76f33d0c0d9d3fb1a01b1f26f565e62b90d660b0d161b1b10ffe44c64b6ec9bb9e311ec52d6705ccf38b8e1eede369c77cad3bd
|
|
7
|
+
data.tar.gz: a35dd8aaa3d940d873cd1cc39a919597b8571e170ccf36b9b0e80ff3174fe4a0d3ab161508760e2dfea6f23639766876abc287dcfc0b0219981b053549cc6388
|
data/LICENSE-Orion
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Murai Labs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# Tensor Gem (Native Matrix/Tensor Extension)
|
|
2
|
+
|
|
3
|
+
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.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
- Build the extension and gem:
|
|
8
|
+
- `ruby extconf.rb`
|
|
9
|
+
- `make`
|
|
10
|
+
- `gem build tensor.gemspec`
|
|
11
|
+
- Install locally:
|
|
12
|
+
- `gem install tensor-0.2.0.gem`
|
|
13
|
+
|
|
14
|
+
In Ruby:
|
|
15
|
+
|
|
16
|
+
```ruby
|
|
17
|
+
require "tensor"
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
This defines a top-level `Tensor` class backed by the C extension (an order-2 tensor). `Matrix` is provided as a backwards-compatible alias.
|
|
21
|
+
|
|
22
|
+
## Basic Usage
|
|
23
|
+
|
|
24
|
+
```ruby
|
|
25
|
+
m1 = Tensor.new(2, 2, dtype: "float32")
|
|
26
|
+
m2 = Tensor.new(2, 2, dtype: "float32")
|
|
27
|
+
|
|
28
|
+
product = m1.multiply(m2) # or m1.matmul(m2)
|
|
29
|
+
relu = product.relu
|
|
30
|
+
softmax = product.softmax
|
|
31
|
+
loss, grad = softmax.cross_entropy_loss([0, 1])
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
- Supported dtypes for most math ops: `"float32"`, `"float64"`.
|
|
35
|
+
- Integer dtypes (`"int16"`, `"int8"`) are supported for storage, indexing, and conversion, but many numeric operations will raise `ArgumentError` if used with integer matrices.
|
|
36
|
+
|
|
37
|
+
## Matrix multiplication backends
|
|
38
|
+
|
|
39
|
+
```ruby
|
|
40
|
+
left = Tensor.from_arrays([[1, 2, 3], [4, 5, 6]], 32)
|
|
41
|
+
right = Tensor.from_arrays([[2, 3], [4, 5], [6, 7]], 32)
|
|
42
|
+
|
|
43
|
+
left.matmul(right) # CPU, also available as backend: :cpu
|
|
44
|
+
left.matmul(right, backend: :ane) # Opt in on Apple Silicon
|
|
45
|
+
Tensor.cpu_backend # :accelerate, :openblas, or :portable
|
|
46
|
+
Tensor.ane_available? # Whether the private runtime is available
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
CPU products use Accelerate on macOS, OpenBLAS when detected on other
|
|
50
|
+
platforms, or the portable C kernel. The `multiply` and `matmul` names share
|
|
51
|
+
the same options. Both inputs must be rank 2 with matching floating point dtypes.
|
|
52
|
+
|
|
53
|
+
The ANE path uses Orion's direct private API and IOSurface buffers. Both operands
|
|
54
|
+
are runtime inputs. It accepts float32 tensors, computes in float16, and returns
|
|
55
|
+
float32 storage. Use the CPU for float64, exceptional values, or when tighter
|
|
56
|
+
numeric agreement is needed. ANE requests may fail on unsupported macOS versions
|
|
57
|
+
or shapes. Each dimension is limited to 2048 and rounded up internally. The
|
|
58
|
+
process retains up to eight compiled shapes. Explicit ANE requests raise on
|
|
59
|
+
failure, so a caller can choose when to retry on the CPU. The CPU path remains
|
|
60
|
+
the default for small matrices and for portable scripts. No GPU is required.
|
|
61
|
+
|
|
62
|
+
Configure with `ruby extconf.rb --disable-ane` to omit the ANE bridge. For a
|
|
63
|
+
hardware test after building, run `TENSOR_REQUIRE_ANE=1 OMP_NUM_THREADS=1 ruby -I. test/test_tensor.rb`.
|
|
64
|
+
The default suite also checks the error path when ANE is unavailable.
|
|
65
|
+
|
|
66
|
+
## N-D Tensor API
|
|
67
|
+
|
|
68
|
+
- Create tensors by shape:
|
|
69
|
+
- `Tensor.zeros(shape: [batch, channels, height, width], dtype: "float32")`
|
|
70
|
+
- `t.shape #=> [b, c, h, w]`, `t.rank`, `t.size`.
|
|
71
|
+
- Build from nested Ruby arrays:
|
|
72
|
+
- `Tensor.from_array(nested, "float32")` where `nested` is a rectangular N-D array.
|
|
73
|
+
- N-D indexing:
|
|
74
|
+
- `t[batch, channel, i, j]` to get/set a scalar element (negative indices supported).
|
|
75
|
+
- `t.to_a` returns nested arrays matching `t.shape`.
|
|
76
|
+
|
|
77
|
+
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.
|
|
78
|
+
|
|
79
|
+
## Single- vs Multi-threaded Execution (OpenMP)
|
|
80
|
+
|
|
81
|
+
- The C code uses OpenMP (`#pragma omp parallel for`) for:
|
|
82
|
+
- Portable matrix multiplication (`multiply` / `matmul`)
|
|
83
|
+
- Element-wise ops (`subtract`, `hadamard`, `scale`, ReLU, ReLU grad)
|
|
84
|
+
- Cross-entropy loss and gradient
|
|
85
|
+
- The number of threads is chosen as:
|
|
86
|
+
- `OMP_NUM_THREADS` (if set by your environment/OpenMP runtime), otherwise
|
|
87
|
+
- `omp_get_max_threads()` at runtime, or a fallback of 16 when OpenMP is not available.
|
|
88
|
+
|
|
89
|
+
To force single-threaded execution (for debugging or deterministic benchmarking), set:
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
export OMP_NUM_THREADS=1
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
To allow more parallelism (on a machine with many cores), set for example:
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
export OMP_NUM_THREADS=8
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Note: 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.
|
|
102
|
+
|
|
103
|
+
## Build Requirements
|
|
104
|
+
|
|
105
|
+
- Ruby with development headers (e.g., via `rbenv`/`rvm` and `ruby-build`).
|
|
106
|
+
- A C toolchain:
|
|
107
|
+
- macOS: Xcode Command Line Tools (`xcode-select --install`).
|
|
108
|
+
- Linux: `gcc`, `make`, and standard build tools.
|
|
109
|
+
- Optional but recommended:
|
|
110
|
+
- OpenMP runtime (`libomp` on macOS, `libgomp`/`libomp` on Linux) for multi-threaded kernels.
|
|
111
|
+
- OpenBLAS for CPU matrix multiplication on platforms without Accelerate.
|
|
112
|
+
|
|
113
|
+
On macOS with Homebrew:
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
brew install libomp
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
The extension uses the macOS system Accelerate framework without an OpenBLAS dependency. Linux builds can pick up OpenBLAS via `pkg-config` or `OPENBLAS_DIR`.
|
data/extconf.rb
CHANGED
|
@@ -62,9 +62,8 @@ if is_apple_clang
|
|
|
62
62
|
if Dir.exist?(libomp_prefix)
|
|
63
63
|
$INCFLAGS << " -I#{libomp_prefix}/include"
|
|
64
64
|
$LDFLAGS << " -L#{libomp_prefix}/lib"
|
|
65
|
-
$CFLAGS << " -Xpreprocessor -fopenmp"
|
|
66
|
-
$LDFLAGS << " -lomp"
|
|
67
65
|
openmp_enabled = have_library('omp')
|
|
66
|
+
$CFLAGS << " -Xpreprocessor -fopenmp" if openmp_enabled
|
|
68
67
|
puts "LLVM OpenMP support #{openmp_enabled ? 'enabled' : 'not found'}"
|
|
69
68
|
unless openmp_enabled
|
|
70
69
|
puts "To enable: brew install libomp"
|
|
@@ -89,50 +88,10 @@ else
|
|
|
89
88
|
end
|
|
90
89
|
end
|
|
91
90
|
|
|
92
|
-
#
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
explicit_openblas = ENV['OPENBLAS_DIR']
|
|
97
|
-
if explicit_openblas && Dir.exist?(explicit_openblas)
|
|
98
|
-
openblas_root = explicit_openblas
|
|
99
|
-
elsif on_macos
|
|
100
|
-
openblas_versions = Dir.glob("/opt/homebrew/Cellar/openblas/*").sort
|
|
101
|
-
openblas_root = openblas_versions.last
|
|
102
|
-
else
|
|
103
|
-
openblas_root = nil
|
|
104
|
-
end
|
|
105
|
-
|
|
106
|
-
if openblas_root && Dir.exist?(openblas_root)
|
|
107
|
-
openblas_include_path = File.join(openblas_root, "include")
|
|
108
|
-
openblas_lib_path = File.join(openblas_root, "lib")
|
|
109
|
-
$INCFLAGS << " -I#{openblas_include_path}"
|
|
110
|
-
$LDFLAGS << " -L#{openblas_lib_path}"
|
|
111
|
-
$LIBPATH << openblas_lib_path
|
|
112
|
-
puts "Using OpenBLAS from #{openblas_root}"
|
|
113
|
-
elsif explicit_openblas
|
|
114
|
-
puts "OPENBLAS_DIR=#{explicit_openblas} was set but does not exist; ignoring."
|
|
115
|
-
end
|
|
116
|
-
|
|
117
|
-
# Check for BLAS support using pkg-config (cross-platform)
|
|
118
|
-
puts "Checking for BLAS (OpenBLAS) support..."
|
|
119
|
-
if pkg_config("openblas")
|
|
120
|
-
puts "BLAS support found via pkg-config! Enabling BLAS optimizations."
|
|
121
|
-
elsif openblas_lib_path && Dir.exist?(openblas_lib_path)
|
|
122
|
-
puts "pkg-config failed to find OpenBLAS. Using manual configuration from #{openblas_lib_path}."
|
|
123
|
-
$LDFLAGS << " -lopenblas"
|
|
124
|
-
else
|
|
125
|
-
puts "OpenBLAS not found. Continuing without BLAS-specific optimizations."
|
|
126
|
-
if on_linux
|
|
127
|
-
puts "On Debian/Ubuntu: sudo apt-get install libopenblas-dev"
|
|
128
|
-
puts "On Fedora/RHEL: sudo dnf install openblas-devel"
|
|
129
|
-
end
|
|
130
|
-
puts "Or set OPENBLAS_DIR to your OpenBLAS installation root (with include/ and lib/)."
|
|
131
|
-
end
|
|
132
|
-
|
|
133
|
-
# Clean up incompatible OpenMP flags from pkg-config when using Apple's clang
|
|
134
|
-
if is_apple_clang
|
|
135
|
-
$CFLAGS = $CFLAGS.to_s.gsub(/\s-fopenmp\b/, "")
|
|
91
|
+
# Accelerate is the CPU BLAS on macOS. Look for OpenBLAS elsewhere.
|
|
92
|
+
unless on_macos
|
|
93
|
+
dir_config('openblas', ENV['OPENBLAS_DIR'])
|
|
94
|
+
pkg_config('openblas')
|
|
136
95
|
end
|
|
137
96
|
|
|
138
97
|
# Check for math library
|
|
@@ -149,7 +108,7 @@ elsif is_arm && have_header('arm_neon.h')
|
|
|
149
108
|
$CFLAGS << " -DHAVE_ARM_NEON_H"
|
|
150
109
|
puts "ARM NEON support found on macOS! Enabling NEON optimizations."
|
|
151
110
|
else
|
|
152
|
-
$CFLAGS << " -DHAVE_ARM_NEON_H
|
|
111
|
+
$CFLAGS << " -DHAVE_ARM_NEON_H"
|
|
153
112
|
puts "ARM NEON support found! Enabling NEON optimizations."
|
|
154
113
|
end
|
|
155
114
|
$defs << "-DHAVE_ARM_NEON_H"
|
|
@@ -182,5 +141,20 @@ puts "LDFLAGS: #{$LDFLAGS}"
|
|
|
182
141
|
puts "INCFLAGS: #{$INCFLAGS}"
|
|
183
142
|
puts "Definitions: #{$defs.join(' ')}"
|
|
184
143
|
|
|
144
|
+
# Use the system CPU BLAS on macOS. Compile the optional ANE bridge only on arm64.
|
|
145
|
+
$srcs = ['ruby_matrix.c']
|
|
146
|
+
if on_macos
|
|
147
|
+
$LDFLAGS << " -framework Accelerate"
|
|
148
|
+
$defs << "-DTENSOR_ACCELERATE"
|
|
149
|
+
if is_arm && enable_config('ane', true)
|
|
150
|
+
$srcs << 'tensor_ane.m'
|
|
151
|
+
$CFLAGS << " -fobjc-arc"
|
|
152
|
+
$LDFLAGS << " -framework Foundation -framework IOSurface"
|
|
153
|
+
$defs << "-DTENSOR_ANE"
|
|
154
|
+
end
|
|
155
|
+
elsif have_header('cblas.h') && have_library('openblas', 'cblas_sgemm')
|
|
156
|
+
$defs << "-DTENSOR_OPENBLAS"
|
|
157
|
+
end
|
|
158
|
+
|
|
185
159
|
# Create the makefile for the native extension (tensor_ext)
|
|
186
160
|
create_makefile('tensor_ext')
|
data/ruby_matrix.c
CHANGED
|
@@ -3,6 +3,18 @@
|
|
|
3
3
|
#include <stdlib.h>
|
|
4
4
|
#include <string.h>
|
|
5
5
|
#include <stdint.h>
|
|
6
|
+
#include <limits.h>
|
|
7
|
+
#include <stdbool.h>
|
|
8
|
+
|
|
9
|
+
#if defined(TENSOR_ACCELERATE)
|
|
10
|
+
#include <Accelerate/Accelerate.h>
|
|
11
|
+
#elif defined(TENSOR_OPENBLAS)
|
|
12
|
+
#include <cblas.h>
|
|
13
|
+
#endif
|
|
14
|
+
|
|
15
|
+
#ifdef TENSOR_ANE
|
|
16
|
+
#include "tensor_ane.h"
|
|
17
|
+
#endif
|
|
6
18
|
|
|
7
19
|
#ifdef _OPENMP
|
|
8
20
|
#include <omp.h>
|
|
@@ -96,6 +108,10 @@ Matrix *matrix_new(size_t rows, size_t cols, DataType dtype) {
|
|
|
96
108
|
rb_raise(rb_eArgError, "Rows and columns must be greater than zero");
|
|
97
109
|
}
|
|
98
110
|
|
|
111
|
+
if (rows > SIZE_MAX / cols) {
|
|
112
|
+
rb_raise(rb_eRangeError, "Matrix element count overflows size_t");
|
|
113
|
+
}
|
|
114
|
+
|
|
99
115
|
Matrix *matrix = malloc(sizeof(Matrix));
|
|
100
116
|
if (!matrix) {
|
|
101
117
|
rb_raise(rb_eNoMemError, "Failed to allocate memory for matrix");
|
|
@@ -146,8 +162,11 @@ void matrix_free(Matrix *matrix) {
|
|
|
146
162
|
}
|
|
147
163
|
}
|
|
148
164
|
|
|
149
|
-
// Matrix multiplication with OpenMP
|
|
150
|
-
Matrix *matrix_multiply(const Matrix *a, const Matrix *b) {
|
|
165
|
+
// Matrix multiplication with CPU BLAS or the portable OpenMP/scalar kernel.
|
|
166
|
+
static Matrix *matrix_multiply(const Matrix *a, const Matrix *b, bool use_ane) {
|
|
167
|
+
if (a->rank != 2 || b->rank != 2) {
|
|
168
|
+
rb_raise(rb_eArgError, "matmul requires two rank-2 tensors");
|
|
169
|
+
}
|
|
151
170
|
if (a->cols != b->rows || a->dtype != b->dtype) {
|
|
152
171
|
rb_raise(rb_eArgError, "Incompatible matrix dimensions or data types");
|
|
153
172
|
}
|
|
@@ -157,6 +176,30 @@ Matrix *matrix_multiply(const Matrix *a, const Matrix *b) {
|
|
|
157
176
|
}
|
|
158
177
|
|
|
159
178
|
Matrix *result = matrix_new(a->rows, b->cols, a->dtype);
|
|
179
|
+
if (use_ane) {
|
|
180
|
+
const char *error = "ANE backend was not built. Use backend: :cpu";
|
|
181
|
+
#ifdef TENSOR_ANE
|
|
182
|
+
error = a->dtype == DTYPE_FLOAT32
|
|
183
|
+
? tensor_ane_matmul(a->data, b->data, result->data, a->rows, a->cols, b->cols)
|
|
184
|
+
: "ANE matmul requires float32 tensors (float16 computation)";
|
|
185
|
+
#endif
|
|
186
|
+
if (!error) return result;
|
|
187
|
+
matrix_free(result);
|
|
188
|
+
rb_raise(rb_eRuntimeError, "%s", error);
|
|
189
|
+
}
|
|
190
|
+
#if defined(TENSOR_ACCELERATE) || defined(TENSOR_OPENBLAS)
|
|
191
|
+
if (a->rows <= INT_MAX && a->cols <= INT_MAX && b->cols <= INT_MAX) {
|
|
192
|
+
int rows = (int)a->rows, inner = (int)a->cols, columns = (int)b->cols;
|
|
193
|
+
if (a->dtype == DTYPE_FLOAT64) {
|
|
194
|
+
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, rows, columns, inner,
|
|
195
|
+
1.0, a->data, inner, b->data, columns, 0.0, result->data, columns);
|
|
196
|
+
} else {
|
|
197
|
+
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, rows, columns, inner,
|
|
198
|
+
1.0f, a->data, inner, b->data, columns, 0.0f, result->data, columns);
|
|
199
|
+
}
|
|
200
|
+
return result;
|
|
201
|
+
}
|
|
202
|
+
#endif
|
|
160
203
|
size_t num_threads = get_num_threads();
|
|
161
204
|
|
|
162
205
|
if (a->dtype == DTYPE_FLOAT64) {
|
|
@@ -578,15 +621,48 @@ VALUE rb_matrix_set_element(int argc, VALUE *argv, VALUE self) {
|
|
|
578
621
|
}
|
|
579
622
|
|
|
580
623
|
// Ruby method for matrix multiplication
|
|
581
|
-
VALUE rb_matrix_multiply(VALUE
|
|
624
|
+
static VALUE rb_matrix_multiply(int argc, VALUE *argv, VALUE self) {
|
|
625
|
+
VALUE other, options;
|
|
626
|
+
rb_scan_args(argc, argv, "1:", &other, &options);
|
|
627
|
+
bool use_ane = false;
|
|
628
|
+
if (!NIL_P(options)) {
|
|
629
|
+
ID keys[] = { rb_intern("backend") };
|
|
630
|
+
VALUE backend;
|
|
631
|
+
rb_get_kwargs(options, keys, 0, 1, &backend);
|
|
632
|
+
use_ane = backend == ID2SYM(rb_intern("ane"));
|
|
633
|
+
if (!use_ane && backend != Qundef && backend != ID2SYM(rb_intern("cpu"))) {
|
|
634
|
+
rb_raise(rb_eArgError, "backend must be :cpu or :ane");
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
if (!rb_obj_is_kind_of(other, rb_tensor_class)) {
|
|
638
|
+
rb_raise(rb_eTypeError, "matmul requires a Tensor operand");
|
|
639
|
+
}
|
|
582
640
|
Matrix *a, *b;
|
|
583
641
|
Data_Get_Struct(self, Matrix, a);
|
|
584
642
|
Data_Get_Struct(other, Matrix, b);
|
|
585
643
|
|
|
586
|
-
Matrix *result = matrix_multiply(a, b);
|
|
644
|
+
Matrix *result = matrix_multiply(a, b, use_ane);
|
|
587
645
|
return Data_Wrap_Struct(rb_tensor_class, NULL, matrix_free, result);
|
|
588
646
|
}
|
|
589
647
|
|
|
648
|
+
static VALUE rb_tensor_ane_available(VALUE klass) {
|
|
649
|
+
#ifdef TENSOR_ANE
|
|
650
|
+
return tensor_ane_available() ? Qtrue : Qfalse;
|
|
651
|
+
#else
|
|
652
|
+
return Qfalse;
|
|
653
|
+
#endif
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
static VALUE rb_tensor_cpu_backend(VALUE klass) {
|
|
657
|
+
#if defined(TENSOR_ACCELERATE)
|
|
658
|
+
return ID2SYM(rb_intern("accelerate"));
|
|
659
|
+
#elif defined(TENSOR_OPENBLAS)
|
|
660
|
+
return ID2SYM(rb_intern("openblas"));
|
|
661
|
+
#else
|
|
662
|
+
return ID2SYM(rb_intern("portable"));
|
|
663
|
+
#endif
|
|
664
|
+
}
|
|
665
|
+
|
|
590
666
|
// Ruby method for matrix subtraction
|
|
591
667
|
VALUE rb_matrix_subtract(VALUE self, VALUE other) {
|
|
592
668
|
Matrix *a, *b;
|
|
@@ -1340,9 +1416,12 @@ void Init_tensor_ext() {
|
|
|
1340
1416
|
rb_define_singleton_method(rb_tensor_class, "zeros", rb_tensor_zeros, -1);
|
|
1341
1417
|
rb_define_singleton_method(rb_tensor_class, "from_array", rb_tensor_from_array, -1);
|
|
1342
1418
|
|
|
1419
|
+
rb_define_singleton_method(rb_tensor_class, "ane_available?", rb_tensor_ane_available, 0);
|
|
1420
|
+
rb_define_singleton_method(rb_tensor_class, "cpu_backend", rb_tensor_cpu_backend, 0);
|
|
1421
|
+
|
|
1343
1422
|
// Instance Methods
|
|
1344
1423
|
rb_define_method(rb_tensor_class, "initialize", rb_matrix_initialize, -1);
|
|
1345
|
-
rb_define_method(rb_tensor_class, "multiply", rb_matrix_multiply, 1);
|
|
1424
|
+
rb_define_method(rb_tensor_class, "multiply", rb_matrix_multiply, -1);
|
|
1346
1425
|
rb_define_method(rb_tensor_class, "subtract", rb_matrix_subtract, 1);
|
|
1347
1426
|
rb_define_method(rb_tensor_class, "relu", rb_matrix_relu, 0);
|
|
1348
1427
|
rb_define_method(rb_tensor_class, "relu_grad", rb_matrix_relu_grad, 0);
|
data/tensor_ane.h
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
#ifndef TENSOR_ANE_H
|
|
2
|
+
#define TENSOR_ANE_H
|
|
3
|
+
|
|
4
|
+
#include <stdbool.h>
|
|
5
|
+
#include <stddef.h>
|
|
6
|
+
|
|
7
|
+
bool tensor_ane_available(void);
|
|
8
|
+
const char *tensor_ane_matmul(const float *left, const float *right, float *output,
|
|
9
|
+
size_t rows, size_t inner, size_t columns);
|
|
10
|
+
|
|
11
|
+
#endif
|
data/tensor_ane.m
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// The private ANE model and request sequence is adapted from Orion
|
|
2
|
+
// (core/ane_runtime.m, revision 4dcc1c2a626c). See LICENSE-Orion.
|
|
3
|
+
#import "tensor_ane.h"
|
|
4
|
+
#import <Foundation/Foundation.h>
|
|
5
|
+
#import <IOSurface/IOSurface.h>
|
|
6
|
+
#import <objc/message.h>
|
|
7
|
+
#import <dlfcn.h>
|
|
8
|
+
#import <math.h>
|
|
9
|
+
#import <unistd.h>
|
|
10
|
+
|
|
11
|
+
enum { MAX_PROGRAMS = 8, MAX_ATTEMPTS = 16, MAX_DIMENSION = 2048 };
|
|
12
|
+
typedef struct {
|
|
13
|
+
size_t rows, inner, columns;
|
|
14
|
+
CFTypeRef model;
|
|
15
|
+
CFTypeRef directory;
|
|
16
|
+
} Program;
|
|
17
|
+
|
|
18
|
+
// Calls run under Ruby's GVL. Never reuse an inherited ANE connection after fork.
|
|
19
|
+
static pid_t owner;
|
|
20
|
+
static Class descriptor_class, model_class, request_class, surface_class;
|
|
21
|
+
static Program programs[MAX_PROGRAMS];
|
|
22
|
+
static size_t program_count, compile_attempts;
|
|
23
|
+
|
|
24
|
+
static void cleanup(void) {
|
|
25
|
+
if (owner != getpid()) return;
|
|
26
|
+
@autoreleasepool {
|
|
27
|
+
for (size_t i = 0; i < program_count; i++) {
|
|
28
|
+
Program *program = &programs[i];
|
|
29
|
+
id model = (__bridge id)program->model;
|
|
30
|
+
((BOOL (*)(id, SEL, unsigned int, NSError **))objc_msgSend)
|
|
31
|
+
(model, @selector(unloadWithQoS:error:), 21, NULL);
|
|
32
|
+
[[NSFileManager defaultManager] removeItemAtPath:
|
|
33
|
+
(__bridge NSString *)program->directory error:nil];
|
|
34
|
+
CFRelease(program->directory);
|
|
35
|
+
CFRelease(program->model);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
bool tensor_ane_available(void) {
|
|
41
|
+
if (owner) return owner == getpid() && request_class != Nil;
|
|
42
|
+
owner = getpid();
|
|
43
|
+
if (!dlopen("/System/Library/PrivateFrameworks/AppleNeuralEngine.framework/AppleNeuralEngine",
|
|
44
|
+
RTLD_NOW | RTLD_LOCAL)) return false;
|
|
45
|
+
descriptor_class = NSClassFromString(@"_ANEInMemoryModelDescriptor");
|
|
46
|
+
model_class = NSClassFromString(@"_ANEInMemoryModel");
|
|
47
|
+
surface_class = NSClassFromString(@"_ANEIOSurfaceObject");
|
|
48
|
+
Class request = NSClassFromString(@"_ANERequest");
|
|
49
|
+
if (![descriptor_class respondsToSelector:@selector(modelWithMILText:weights:optionsPlist:)] ||
|
|
50
|
+
![model_class respondsToSelector:@selector(inMemoryModelWithDescriptor:)] ||
|
|
51
|
+
![model_class instancesRespondToSelector:@selector(hexStringIdentifier)] ||
|
|
52
|
+
![model_class instancesRespondToSelector:@selector(compileWithQoS:options:error:)] ||
|
|
53
|
+
![model_class instancesRespondToSelector:@selector(loadWithQoS:options:error:)] ||
|
|
54
|
+
![model_class instancesRespondToSelector:@selector(evaluateWithQoS:options:request:error:)] ||
|
|
55
|
+
![model_class instancesRespondToSelector:@selector(unloadWithQoS:error:)] ||
|
|
56
|
+
![surface_class respondsToSelector:@selector(objectWithIOSurface:)] ||
|
|
57
|
+
![request respondsToSelector:@selector(requestWithInputs:inputIndices:outputs:outputIndices:weightsBuffer:perfStats:procedureIndex:)])
|
|
58
|
+
return false;
|
|
59
|
+
if (atexit(cleanup) != 0) return false;
|
|
60
|
+
request_class = request;
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
static id load_program(size_t rows, size_t inner, size_t columns) {
|
|
65
|
+
for (size_t i = 0; i < program_count; i++) {
|
|
66
|
+
Program *entry = &programs[i];
|
|
67
|
+
if (entry->rows == rows && entry->inner == inner && entry->columns == columns)
|
|
68
|
+
return (__bridge id)entry->model;
|
|
69
|
+
}
|
|
70
|
+
// Orion observed a process-wide compile limit. Keep a small, bounded cache.
|
|
71
|
+
if (program_count == MAX_PROGRAMS || compile_attempts == MAX_ATTEMPTS) return nil;
|
|
72
|
+
NSString *left = [NSString stringWithFormat:@"[1,1,%zu,%zu]", rows, inner];
|
|
73
|
+
NSString *right = [NSString stringWithFormat:@"[1,1,%zu,%zu]", inner, columns];
|
|
74
|
+
NSString *out = [NSString stringWithFormat:@"[1,1,%zu,%zu]", rows, columns];
|
|
75
|
+
NSString *mil = [NSString stringWithFormat:
|
|
76
|
+
@"program(1.3)\n[buildInfo = dict<string,string>({{\"coremltools-version\",\"9.0\"}})]\n"
|
|
77
|
+
"{ func main<ios18>(tensor<fp32,%@> a, tensor<fp32,%@> b) {\n"
|
|
78
|
+
"string h=const()[name=string(\"h\"),val=string(\"fp16\")];\n"
|
|
79
|
+
"tensor<fp16,%@> a16=cast(dtype=h,x=a)[name=string(\"a16\")];\n"
|
|
80
|
+
"tensor<fp16,%@> b16=cast(dtype=h,x=b)[name=string(\"b16\")];\n"
|
|
81
|
+
"bool no=const()[name=string(\"no\"),val=bool(false)];\n"
|
|
82
|
+
"tensor<fp16,%@> c16=matmul(transpose_x=no,transpose_y=no,x=a16,y=b16)"
|
|
83
|
+
"[name=string(\"tensor_matmul_%d\")];\n"
|
|
84
|
+
"string f=const()[name=string(\"f\"),val=string(\"fp32\")];\n"
|
|
85
|
+
"tensor<fp32,%@> c=cast(dtype=f,x=c16)[name=string(\"c\")];\n"
|
|
86
|
+
"} -> (c); }", left, right, left, right, out, (int)owner, out];
|
|
87
|
+
NSData *data = [mil dataUsingEncoding:NSUTF8StringEncoding];
|
|
88
|
+
id descriptor = ((id (*)(Class, SEL, id, id, id))objc_msgSend)
|
|
89
|
+
(descriptor_class, @selector(modelWithMILText:weights:optionsPlist:), data, @{}, nil);
|
|
90
|
+
if (!descriptor) return nil;
|
|
91
|
+
id model = ((id (*)(Class, SEL, id))objc_msgSend)
|
|
92
|
+
(model_class, @selector(inMemoryModelWithDescriptor:), descriptor);
|
|
93
|
+
if (!model) return nil;
|
|
94
|
+
NSString *identifier = ((id (*)(id, SEL))objc_msgSend)(model, @selector(hexStringIdentifier));
|
|
95
|
+
if (!identifier.length) return nil;
|
|
96
|
+
NSString *directory = [NSTemporaryDirectory() stringByAppendingPathComponent:identifier];
|
|
97
|
+
NSFileManager *files = [NSFileManager defaultManager];
|
|
98
|
+
if (![files createDirectoryAtPath:directory withIntermediateDirectories:NO attributes:nil error:nil])
|
|
99
|
+
return nil;
|
|
100
|
+
BOOL written = [data writeToFile:[directory stringByAppendingPathComponent:@"model.mil"] atomically:YES];
|
|
101
|
+
if (written) compile_attempts++;
|
|
102
|
+
if (!written || !((BOOL (*)(id, SEL, unsigned int, id, NSError **))objc_msgSend)
|
|
103
|
+
(model, @selector(compileWithQoS:options:error:), 21, @{}, NULL) ||
|
|
104
|
+
!((BOOL (*)(id, SEL, unsigned int, id, NSError **))objc_msgSend)
|
|
105
|
+
(model, @selector(loadWithQoS:options:error:), 21, @{}, NULL)) {
|
|
106
|
+
[files removeItemAtPath:directory error:nil];
|
|
107
|
+
return nil;
|
|
108
|
+
}
|
|
109
|
+
programs[program_count++] = (Program){rows, inner, columns,
|
|
110
|
+
CFBridgingRetain(model), CFBridgingRetain(directory)};
|
|
111
|
+
return model;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
static IOSurfaceRef make_surface(size_t count) {
|
|
115
|
+
size_t bytes = count * sizeof(float);
|
|
116
|
+
return IOSurfaceCreate((__bridge CFDictionaryRef)@{
|
|
117
|
+
(id)kIOSurfaceWidth: @(bytes), (id)kIOSurfaceHeight: @1,
|
|
118
|
+
(id)kIOSurfaceBytesPerElement: @1, (id)kIOSurfaceBytesPerRow: @(bytes),
|
|
119
|
+
(id)kIOSurfaceAllocSize: @(bytes)
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
static bool write_input(IOSurfaceRef surface, const float *data, size_t rows,
|
|
124
|
+
size_t columns, size_t stride, size_t padded_rows) {
|
|
125
|
+
if (IOSurfaceLock(surface, 0, NULL) != kIOReturnSuccess) return false;
|
|
126
|
+
float *dest = IOSurfaceGetBaseAddress(surface);
|
|
127
|
+
memset(dest, 0, padded_rows * stride * sizeof(float));
|
|
128
|
+
for (size_t row = 0; row < rows; row++)
|
|
129
|
+
memcpy(dest + row * stride, data + row * columns, columns * sizeof(float));
|
|
130
|
+
return IOSurfaceUnlock(surface, 0, NULL) == kIOReturnSuccess;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
static bool evaluate(id model, IOSurfaceRef left, IOSurfaceRef right, IOSurfaceRef output) {
|
|
134
|
+
id (*wrap)(Class, SEL, IOSurfaceRef) = (void *)objc_msgSend;
|
|
135
|
+
id a = wrap(surface_class, @selector(objectWithIOSurface:), left);
|
|
136
|
+
id b = wrap(surface_class, @selector(objectWithIOSurface:), right);
|
|
137
|
+
id c = wrap(surface_class, @selector(objectWithIOSurface:), output);
|
|
138
|
+
if (!a || !b || !c) return false;
|
|
139
|
+
id request = ((id (*)(Class, SEL, id, id, id, id, id, id, id))objc_msgSend)
|
|
140
|
+
(request_class, @selector(requestWithInputs:inputIndices:outputs:outputIndices:weightsBuffer:perfStats:procedureIndex:),
|
|
141
|
+
@[a, b], @[@0, @1], @[c], @[@0], nil, nil, @0);
|
|
142
|
+
return request && ((BOOL (*)(id, SEL, unsigned int, id, id, NSError **))objc_msgSend)
|
|
143
|
+
(model, @selector(evaluateWithQoS:options:request:error:), 21, @{}, request, NULL);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
static size_t padded(size_t dimension) {
|
|
147
|
+
return dimension < 128 ? 128 : (dimension + 31) & ~(size_t)31;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
static bool fp16_range(const float *data, size_t count) {
|
|
151
|
+
for (size_t i = 0; i < count; i++)
|
|
152
|
+
if (!isfinite(data[i]) || fabsf(data[i]) > 65504.0f) return false;
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const char *tensor_ane_matmul(const float *left, const float *right, float *output,
|
|
157
|
+
size_t rows, size_t inner, size_t columns) {
|
|
158
|
+
if (rows > MAX_DIMENSION || inner > MAX_DIMENSION || columns > MAX_DIMENSION)
|
|
159
|
+
return "ANE matmul supports dimensions up to 2048";
|
|
160
|
+
if (!fp16_range(left, rows * inner) || !fp16_range(right, inner * columns))
|
|
161
|
+
return "ANE matmul inputs must be finite and fit in float16";
|
|
162
|
+
size_t m = padded(rows), k = padded(inner), n = padded(columns);
|
|
163
|
+
const char *failure = "ANE matmul failed. Use backend: :cpu on this system or shape";
|
|
164
|
+
IOSurfaceRef a = NULL, b = NULL, c = NULL;
|
|
165
|
+
@autoreleasepool {
|
|
166
|
+
@try {
|
|
167
|
+
if (!tensor_ane_available()) return "ANE runtime unavailable. Use backend: :cpu";
|
|
168
|
+
id model = load_program(m, k, n);
|
|
169
|
+
if (!model) return "ANE program unavailable or its cache is full. Use backend: :cpu";
|
|
170
|
+
a = make_surface(m * k);
|
|
171
|
+
b = make_surface(k * n);
|
|
172
|
+
c = make_surface(m * n);
|
|
173
|
+
if (!a || !b || !c ||
|
|
174
|
+
!write_input(a, left, rows, inner, k, m) ||
|
|
175
|
+
!write_input(b, right, inner, columns, n, k) ||
|
|
176
|
+
!evaluate(model, a, b, c) ||
|
|
177
|
+
IOSurfaceLock(c, kIOSurfaceLockReadOnly, NULL) != kIOReturnSuccess)
|
|
178
|
+
return failure;
|
|
179
|
+
const float *data = IOSurfaceGetBaseAddress(c);
|
|
180
|
+
for (size_t row = 0; row < rows; row++)
|
|
181
|
+
memcpy(output + row * columns, data + row * n, columns * sizeof(float));
|
|
182
|
+
if (IOSurfaceUnlock(c, kIOSurfaceLockReadOnly, NULL) != kIOReturnSuccess) return failure;
|
|
183
|
+
return fp16_range(output, rows * columns) ? NULL : "ANE matmul output exceeded float16 range";
|
|
184
|
+
} @catch (NSException *exception) {
|
|
185
|
+
return failure;
|
|
186
|
+
} @finally {
|
|
187
|
+
if (a) CFRelease(a);
|
|
188
|
+
if (b) CFRelease(b);
|
|
189
|
+
if (c) CFRelease(c);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: tensor
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.2.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Pankaj Doharey
|
|
@@ -18,10 +18,13 @@ extensions:
|
|
|
18
18
|
- extconf.rb
|
|
19
19
|
extra_rdoc_files: []
|
|
20
20
|
files:
|
|
21
|
-
-
|
|
21
|
+
- LICENSE-Orion
|
|
22
|
+
- README.md
|
|
22
23
|
- extconf.rb
|
|
23
24
|
- lib/tensor.rb
|
|
24
25
|
- ruby_matrix.c
|
|
26
|
+
- tensor_ane.h
|
|
27
|
+
- tensor_ane.m
|
|
25
28
|
homepage: https://rubygems.org/gems/tensor
|
|
26
29
|
licenses:
|
|
27
30
|
- MIT
|
|
@@ -42,5 +45,6 @@ required_rubygems_version: !ruby/object:Gem::Requirement
|
|
|
42
45
|
requirements: []
|
|
43
46
|
rubygems_version: 4.0.1
|
|
44
47
|
specification_version: 4
|
|
45
|
-
summary: Fast tensor/matrix operations for Ruby
|
|
48
|
+
summary: Fast tensor/matrix operations for Ruby with native CPU and optional Apple
|
|
49
|
+
Neural Engine backends
|
|
46
50
|
test_files: []
|
data/AGENTS.md
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
# Repository Guidelines
|
|
2
|
-
|
|
3
|
-
## Project Structure & Module Organization
|
|
4
|
-
|
|
5
|
-
- Core C extension lives in `ruby_matrix.c` at the repo root.
|
|
6
|
-
- Build configuration is handled by `extconf.rb`, which generates the `Makefile`.
|
|
7
|
-
- Build artifacts include `ruby_matrix.bundle`, `ruby_matrix.o`, and other compiled outputs; treat these as generated files.
|
|
8
|
-
|
|
9
|
-
## Build, Test, and Development Commands
|
|
10
|
-
|
|
11
|
-
- `ruby extconf.rb` – generate a fresh `Makefile` for the Ruby C extension (preferred over editing `Makefile` directly).
|
|
12
|
-
- `make` – compile the extension, enabling OpenMP and OpenBLAS when available.
|
|
13
|
-
- `make clean` – remove compiled artifacts before rebuilding or changing toolchain settings.
|
|
14
|
-
- After building, validate in a host Ruby project or with a small script that exercises matrix operations and ReLU on sample data.
|
|
15
|
-
|
|
16
|
-
## Coding Style & Naming Conventions
|
|
17
|
-
|
|
18
|
-
- C code uses 4-space indentation, braces on the same line, and descriptive names (`Matrix`, `matrix_multiply`, `matrix_relu_grad`, etc.).
|
|
19
|
-
- Prefer clear, explicit error handling via `rb_raise` with actionable messages.
|
|
20
|
-
- Keep configuration changes in `extconf.rb` (OpenMP, OpenBLAS, include/library paths); do not hand-edit the generated `Makefile`.
|
|
21
|
-
- Avoid introducing one-letter variables in new code; keep naming consistent with existing functions and types.
|
|
22
|
-
|
|
23
|
-
## Testing Guidelines
|
|
24
|
-
|
|
25
|
-
- There is no standalone test suite in this repository; rely on the consuming Ruby project’s tests and targeted smoke scripts.
|
|
26
|
-
- When adding behavior, include a minimal Ruby script (e.g., under `test/` or `examples/` if created) that constructs small matrices and verifies key operations.
|
|
27
|
-
- Aim to keep new behavior covered by at least one fast, deterministic check that can run locally after `make`.
|
|
28
|
-
|
|
29
|
-
## Commit & Pull Request Guidelines
|
|
30
|
-
|
|
31
|
-
- Use concise, imperative commit messages (e.g., “Optimize float32 multiply path”, “Fix NEON detection on ARM”).
|
|
32
|
-
- Keep changes focused: separate performance tuning, API changes, and build-system adjustments into distinct commits when possible.
|
|
33
|
-
- In PR descriptions, summarize the change, note any performance impact or dependency changes (e.g., new `libomp`/OpenBLAS requirements), and describe how you validated the build.
|
|
34
|
-
|
|
35
|
-
## Security & Configuration Tips
|
|
36
|
-
|
|
37
|
-
- This extension depends on system libraries like OpenMP (`libomp`) and OpenBLAS; prefer configuration via `extconf.rb` and environment variables rather than hardcoded absolute paths.
|
|
38
|
-
- Avoid embedding machine-specific paths in committed files; keep paths generic and documented so the extension can build on similar environments.
|