tensor 0.1.0 → 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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ab1431a30c46e725f4719be6d7af3f06f77720741f858448528f23528452baea
4
- data.tar.gz: 2282380204a6d8b8a839365b265cb48443dd16e1e6206bff1d6d7c68af573421
3
+ metadata.gz: 3d77b035713014f0d56c71f7cffc7bfb645d0eb44244a02c5ec9e72afbc9ea5c
4
+ data.tar.gz: ef5f3b47ff6013214039b28c34c826a2f1dbf7cab05b6c2b074fc1c5a69a4bdc
5
5
  SHA512:
6
- metadata.gz: 785a6cf18705e00c2bad28b89a1b2682b139f2423f3ba683fdfef5f2bf3204b4f1a5681c47d2734f8235585bc36e20d2c80790e0abfbf0ee5f625e2384728361
7
- data.tar.gz: 7cdea95dba2a3169e10d8b1d425ada3bb06113dfca07d63287d7cc54f9014a025d31adb8a445375c5f9b00c96d5ae0532d39c39d588211f5308a36caa9743596
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
@@ -6,11 +6,23 @@ $VERBOSE = true
6
6
 
7
7
  host_os = RbConfig::CONFIG['host_os']
8
8
  on_macos = host_os =~ /darwin/
9
+ on_linux = host_os =~ /linux/
10
+
11
+ # Brief dependency summary for users on all platforms
12
+ puts "\n== tensor native extension build =="
13
+ puts "Host OS: #{host_os}"
14
+ puts "This extension can use (optionally):"
15
+ puts " - OpenMP (libomp/libgomp) for multi-threading"
16
+ puts " - OpenBLAS (openblas) for BLAS optimizations"
17
+ puts "Environment overrides:"
18
+ puts " - OPENBLAS_DIR : root with include/ and lib/ for OpenBLAS"
19
+ puts " - OMP_INCLUDE_DIR / OMP_LIB_DIR: OpenMP headers/libs"
20
+ puts " - PKG_CONFIG : path to pkg-config\n"
9
21
 
10
22
  # Debug environment variables
11
23
  puts "PKG_CONFIG_PATH: #{ENV['PKG_CONFIG_PATH']}"
12
- puts "PATH: #{ENV['PATH']}"
13
- puts "pkg-config location: #{`which pkg-config`.chomp}"
24
+ puts "PATH: #{ENV['PATH']}"
25
+ puts "pkg-config: #{`which pkg-config`.chomp}"
14
26
 
15
27
  # Set absolute path to pkg-config if needed (primarily for Homebrew on macOS)
16
28
  if on_macos && ENV['PKG_CONFIG'].to_s.empty?
@@ -31,72 +43,55 @@ is_x86 = RbConfig::CONFIG['host_cpu'] =~ /x86|x64|i386/
31
43
  # Detect if we're using Apple's clang
32
44
  is_apple_clang = RbConfig::CONFIG['CC'] =~ /^clang/ && RUBY_PLATFORM =~ /darwin/
33
45
 
34
- # OpenMP support for macOS
46
+ # OpenMP support (optional)
47
+ omp_include_dir = ENV['OMP_INCLUDE_DIR']
48
+ omp_lib_dir = ENV['OMP_LIB_DIR']
49
+
50
+ if omp_include_dir && !omp_include_dir.empty?
51
+ $INCFLAGS << " -I#{omp_include_dir}"
52
+ end
53
+ if omp_lib_dir && !omp_lib_dir.empty?
54
+ $LDFLAGS << " -L#{omp_lib_dir}"
55
+ end
56
+
57
+ openmp_enabled = false
58
+
35
59
  if is_apple_clang
36
- puts "Detected Apple's clang, using LLVM OpenMP..."
37
- # Use LLVM's OpenMP
60
+ puts "Detected Apple's clang, trying LLVM OpenMP..."
38
61
  libomp_prefix = "/opt/homebrew/opt/libomp"
39
62
  if Dir.exist?(libomp_prefix)
40
63
  $INCFLAGS << " -I#{libomp_prefix}/include"
41
64
  $LDFLAGS << " -L#{libomp_prefix}/lib"
42
- $CFLAGS << " -Xpreprocessor -fopenmp"
43
- $LDFLAGS << " -lomp"
44
- have_library('omp')
45
- puts "LLVM OpenMP support enabled"
65
+ openmp_enabled = have_library('omp')
66
+ $CFLAGS << " -Xpreprocessor -fopenmp" if openmp_enabled
67
+ puts "LLVM OpenMP support #{openmp_enabled ? 'enabled' : 'not found'}"
68
+ unless openmp_enabled
69
+ puts "To enable: brew install libomp"
70
+ end
46
71
  else
47
- puts "Warning: OpenMP not found. Some optimizations will be disabled."
48
- puts "To enable OpenMP: brew install libomp"
72
+ puts "LLVM libomp not found under /opt/homebrew/opt/libomp."
73
+ puts "To enable OpenMP on macOS: brew install libomp"
49
74
  end
50
75
  else
51
76
  # Standard OpenMP support for non-Apple compilers
52
77
  if have_library('omp') || have_library('gomp')
53
78
  $CFLAGS << " -fopenmp"
54
79
  $LDFLAGS << " -fopenmp"
55
- puts "OpenMP support enabled"
80
+ openmp_enabled = true
81
+ puts "OpenMP support enabled via -fopenmp"
56
82
  else
57
- puts "Warning: OpenMP not found. Some optimizations will be disabled."
83
+ puts "OpenMP library (libomp/libgomp) not found."
84
+ if on_linux
85
+ puts "On Debian/Ubuntu: sudo apt-get install libomp-dev (or ensure gcc's libgomp is available)."
86
+ puts "On Fedora/RHEL: sudo dnf install libgomp"
87
+ end
58
88
  end
59
89
  end
60
90
 
61
- # Optional OpenBLAS support
62
- openblas_include_path = nil
63
- openblas_lib_path = nil
64
-
65
- if on_macos
66
- # Allow overriding OpenBLAS location, otherwise try Homebrew cellars
67
- explicit_openblas = ENV['OPENBLAS_DIR']
68
- if explicit_openblas && Dir.exist?(explicit_openblas)
69
- openblas_root = explicit_openblas
70
- else
71
- openblas_versions = Dir.glob("/opt/homebrew/Cellar/openblas/*").sort
72
- openblas_root = openblas_versions.last
73
- end
74
-
75
- if openblas_root && Dir.exist?(openblas_root)
76
- openblas_include_path = File.join(openblas_root, "include")
77
- openblas_lib_path = File.join(openblas_root, "lib")
78
- $INCFLAGS << " -I#{openblas_include_path}"
79
- $LDFLAGS << " -L#{openblas_lib_path}"
80
- $LIBPATH << openblas_lib_path
81
- else
82
- puts "OpenBLAS not found under /opt/homebrew/Cellar; BLAS optimizations may be disabled."
83
- end
84
- end
85
-
86
- # Check for BLAS support using pkg-config (cross-platform)
87
- puts "Checking for BLAS support..."
88
- if pkg_config("openblas")
89
- puts "BLAS support found via pkg-config! Enabling BLAS optimizations."
90
- elsif openblas_lib_path && Dir.exist?(openblas_lib_path)
91
- puts "pkg-config failed to find OpenBLAS. Using manual configuration from #{openblas_lib_path}."
92
- $LDFLAGS << " -lopenblas"
93
- else
94
- puts "OpenBLAS not found. Continuing without BLAS-specific optimizations."
95
- end
96
-
97
- # Clean up incompatible OpenMP flags from pkg-config when using Apple's clang
98
- if is_apple_clang
99
- $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')
100
95
  end
101
96
 
102
97
  # Check for math library
@@ -113,7 +108,7 @@ elsif is_arm && have_header('arm_neon.h')
113
108
  $CFLAGS << " -DHAVE_ARM_NEON_H"
114
109
  puts "ARM NEON support found on macOS! Enabling NEON optimizations."
115
110
  else
116
- $CFLAGS << " -DHAVE_ARM_NEON_H -mfpu=neon"
111
+ $CFLAGS << " -DHAVE_ARM_NEON_H"
117
112
  puts "ARM NEON support found! Enabling NEON optimizations."
118
113
  end
119
114
  $defs << "-DHAVE_ARM_NEON_H"
@@ -127,9 +122,11 @@ $CFLAGS << " -fno-common -pipe"
127
122
  $CFLAGS << " -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT"
128
123
 
129
124
  # Additional include and library paths
130
- $INCFLAGS << " -I/opt/homebrew/include"
125
+ if on_macos
126
+ $INCFLAGS << " -I/opt/homebrew/include"
127
+ $LDFLAGS << " -L/opt/homebrew/lib"
128
+ end
131
129
  $INCFLAGS << " -I/usr/local/include"
132
- $LDFLAGS << " -L/opt/homebrew/lib"
133
130
  $LDFLAGS << " -L/usr/local/lib"
134
131
 
135
132
  # Ensure proper linking for neural network operations
@@ -144,5 +141,20 @@ puts "LDFLAGS: #{$LDFLAGS}"
144
141
  puts "INCFLAGS: #{$INCFLAGS}"
145
142
  puts "Definitions: #{$defs.join(' ')}"
146
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
+
147
159
  # Create the makefile for the native extension (tensor_ext)
148
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 self, VALUE other) {
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,10 +1,10 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: tensor
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
- - Your Name
7
+ - Pankaj Doharey
8
8
  bindir: bin
9
9
  cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
@@ -12,16 +12,19 @@ dependencies: []
12
12
  description: A native Ruby C extension providing parallelized matrix and neural-network
13
13
  style tensor operations.
14
14
  email:
15
- - you@example.com
15
+ - pankajdoharey@gmail.com
16
16
  executables: []
17
17
  extensions:
18
18
  - extconf.rb
19
19
  extra_rdoc_files: []
20
20
  files:
21
- - AGENTS.md
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
@@ -40,7 +43,8 @@ required_rubygems_version: !ruby/object:Gem::Requirement
40
43
  - !ruby/object:Gem::Version
41
44
  version: '0'
42
45
  requirements: []
43
- rubygems_version: 3.6.9
46
+ rubygems_version: 4.0.1
44
47
  specification_version: 4
45
- summary: Fast tensor/matrix operations for Ruby using OpenMP and OpenBLAS
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.