diff --git a/.executorch-version b/.executorch-version new file mode 100644 index 0000000..dc1e644 --- /dev/null +++ b/.executorch-version @@ -0,0 +1 @@ +1.6.0 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..3a5c12b --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,152 @@ +name: CI + +on: + push: + branches: [master, main] + pull_request: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + name: Test (${{ matrix.os }}, Ruby ${{ matrix.ruby }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-24.04 + ruby: "3.2" + - os: ubuntu-24.04 + ruby: "3.3" + - os: ubuntu-24.04 + ruby: "3.4" + - os: ubuntu-24.04-arm + ruby: "3.4" + - os: macos-15 + ruby: "3.2" + - os: macos-15 + ruby: "3.4" + + steps: + - uses: actions/checkout@v4 + + - uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + + - name: Install uv + uses: astral-sh/setup-uv@v5 + with: + enable-cache: true + cache-dependency-glob: "test/fixtures/pyproject.toml" + + - name: Cache ExecuTorch C++ SDK + uses: actions/cache@v4 + with: + path: ~/.cache/executorch-ruby + key: sdk-${{ matrix.os }}-${{ runner.arch }}-${{ hashFiles('.executorch-version', 'lib/executorch/sdk.rb') }} + + - name: Fetch ExecuTorch SDK & compile native extension + run: | + bundle exec rake sdk:fetch + bundle exec rake compile + + - name: Export deterministic .pte / .ptd test fixtures + run: | + uv run --project test/fixtures python test/fixtures/export_fixtures.py --out test/fixtures/models + + - name: Run full test suite (zero skips allowed) + run: | + set -o pipefail + bundle exec rake test TESTOPTS="-v" | tee test_output.txt + grep -qE "0 failures, 0 errors, 0 skips" test_output.txt + + sanitizers: + name: ASan + UBSan (ubuntu-24.04, Ruby 3.4) + runs-on: ubuntu-24.04 + timeout-minutes: 25 + + steps: + - uses: actions/checkout@v4 + + - uses: ruby/setup-ruby@v1 + with: + ruby-version: "3.4" + bundler-cache: true + + - name: Install uv + uses: astral-sh/setup-uv@v5 + with: + enable-cache: true + cache-dependency-glob: "test/fixtures/pyproject.toml" + + - name: Cache ExecuTorch C++ SDK + uses: actions/cache@v4 + with: + path: ~/.cache/executorch-ruby + key: sdk-ubuntu-24.04-${{ runner.arch }}-${{ hashFiles('.executorch-version', 'lib/executorch/sdk.rb') }} + + - name: Compile with ASan + UBSan + env: + EXECUTORCH_SANITIZE: "1" + run: | + bundle exec rake sdk:fetch + bundle exec rake compile + + - name: Export fixtures + run: | + uv run --project test/fixtures python test/fixtures/export_fixtures.py --out test/fixtures/models + + - name: Run tests under ASan + UBSan + run: | + ASAN_LIB=$(g++ -print-file-name=libasan.so) + UBSAN_LIB=$(g++ -print-file-name=libubsan.so) + LD_PRELOAD="${ASAN_LIB}:${UBSAN_LIB}" \ + ASAN_OPTIONS="detect_leaks=0:use_sigaltstack=0:halt_on_error=1" \ + UBSAN_OPTIONS="print_stacktrace=1:halt_on_error=1" \ + bundle exec rake test TESTOPTS="-v" + + package-smoke: + name: Platform Gem Smoke (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + os: [ubuntu-24.04, macos-15] + + steps: + - uses: actions/checkout@v4 + + - uses: ruby/setup-ruby@v1 + with: + ruby-version: "3.4" + bundler-cache: true + + - name: Build platform fat gem & source gem + run: | + bundle exec rake sdk:fetch + bundle exec rake package_platform + gem build executorch.gemspec -o pkg/executorch-source.gem + + - name: Smoke-test isolated platform gem install (no SDK cache required) + run: | + rm -rf ~/.cache/executorch-ruby + GEM_HOME=$(mktemp -d) + export GEM_HOME + export PATH="$GEM_HOME/bin:$PATH" + gem install --local --no-document pkg/executorch-*-*.gem + ruby -rexecutorch -e ' + raise "missing XNNPACK" unless Executorch.backends.include?("XnnpackBackend") + t = Executorch::Tensor.new([[1.0, 2.0], [3.0, 4.0]]) + raise "bad roundtrip" unless t.to_a == [[1.0, 2.0], [3.0, 4.0]] + puts "OK: #{Executorch::VERSION} / SDK #{Executorch.executorch_version} / #{Executorch.backends.inspect}" + ' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..32b932c --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,197 @@ +name: Release + +on: + push: + tags: + - "v*" + workflow_dispatch: + inputs: + dry_run: + description: "Build & verify all gems without pushing to RubyGems" + type: boolean + default: true + +permissions: + contents: read + +jobs: + verify-metadata: + runs-on: ubuntu-24.04 + outputs: + version: ${{ steps.ver.outputs.version }} + publish: ${{ steps.ver.outputs.publish }} + steps: + - uses: actions/checkout@v4 + + - uses: ruby/setup-ruby@v1 + with: + ruby-version: "3.4" + + - name: Verify version and CHANGELOG consistency + id: ver + run: | + VERSION=$(ruby -Ilib -rexecutorch/version -e 'puts Executorch::VERSION') + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + grep -Fq "## [$VERSION]" CHANGELOG.md || { + echo "CHANGELOG.md is missing heading: ## [$VERSION]" + exit 1 + } + if [[ "${GITHUB_REF}" == refs/tags/v* ]]; then + TAG_VER="${GITHUB_REF#refs/tags/v}" + if [[ "$TAG_VER" != "$VERSION" ]]; then + echo "Tag v$TAG_VER does not match Executorch::VERSION ($VERSION)" + exit 1 + fi + echo "publish=true" >> "$GITHUB_OUTPUT" + elif [[ "${{ inputs.dry_run }}" == "false" ]]; then + echo "publish=true" >> "$GITHUB_OUTPUT" + else + echo "publish=false" >> "$GITHUB_OUTPUT" + fi + + build-platform-gems: + needs: verify-metadata + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-24.04 + platform: x86_64-linux + - os: ubuntu-24.04-arm + platform: aarch64-linux + - os: macos-15 + platform: arm64-darwin + + steps: + - uses: actions/checkout@v4 + + - name: Install uv + uses: astral-sh/setup-uv@v5 + + - name: Export fixtures for pre-release verification + run: | + uv run --project test/fixtures python test/fixtures/export_fixtures.py --out test/fixtures/models + + - name: Build fat extension for Ruby 3.2, 3.3, 3.4 + run: | + mkdir -p staged_lib + echo "matrix=${{ matrix.platform }}" + + - name: Compile Ruby 3.2 extension + uses: ruby/setup-ruby@v1 + with: + ruby-version: "3.2" + bundler-cache: true + - run: | + EXECUTORCH_BUNDLE_VENDOR=1 bundle exec rake sdk:fetch compile + bundle exec rake test + mkdir -p staged/3.2 + cp lib/executorch/executorch.* staged/3.2/ + + - name: Compile Ruby 3.3 extension + uses: ruby/setup-ruby@v1 + with: + ruby-version: "3.3" + bundler-cache: true + - run: | + EXECUTORCH_BUNDLE_VENDOR=1 bundle exec rake clean compile + bundle exec rake test + mkdir -p staged/3.3 + cp lib/executorch/executorch.* staged/3.3/ + + - name: Compile Ruby 3.4 extension & assemble fat gem + uses: ruby/setup-ruby@v1 + with: + ruby-version: "3.4" + bundler-cache: true + - run: | + EXECUTORCH_BUNDLE_VENDOR=1 bundle exec rake clean compile + bundle exec rake test + mkdir -p lib/executorch/3.2 lib/executorch/3.3 lib/executorch/3.4 + cp staged/3.2/executorch.* lib/executorch/3.2/ + cp staged/3.3/executorch.* lib/executorch/3.3/ + mv lib/executorch/executorch.* lib/executorch/3.4/ + ruby -e ' + require "rubygems/package" + spec = Gem::Specification.load("executorch.gemspec") + spec.platform = Gem::Platform.new("${{ matrix.platform }}") + spec.extensions = [] + spec.files = ( + spec.files.reject { |f| f.start_with?("ext/") } + + Dir["lib/executorch/3.*/*"] + + Dir["lib/executorch/vendor/*"] + ).uniq.sort + FileUtils.mkdir_p("pkg") + out = Gem::Package.build(spec) + FileUtils.mv(out, File.join("pkg", File.basename(out))) + ' + # Isolated smoke test without SDK cache + rm -rf ~/.cache/executorch-ruby + GEM_HOME=$(mktemp -d) + GEM_HOME="$GEM_HOME" gem install --local --no-document pkg/executorch-*-${{ matrix.platform }}.gem + GEM_HOME="$GEM_HOME" ruby -rexecutorch -e ' + raise "missing XNNPACK" unless Executorch.backends.include?("XnnpackBackend") + puts "Verified fat gem: #{Executorch::VERSION} (#{Executorch.backends.inspect})" + ' + + - uses: actions/upload-artifact@v4 + with: + name: gem-${{ matrix.platform }} + path: pkg/*.gem + + build-source-gem: + needs: verify-metadata + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: "3.4" + - run: | + mkdir -p pkg + gem build executorch.gemspec -o "pkg/executorch-${{ needs.verify-metadata.outputs.version }}.gem" + - uses: actions/upload-artifact@v4 + with: + name: gem-source + path: pkg/*.gem + + publish: + needs: [verify-metadata, build-platform-gems, build-source-gem] + if: needs.verify-metadata.outputs.publish == 'true' + runs-on: ubuntu-24.04 + environment: release + permissions: + contents: write + id-token: write + + steps: + - uses: actions/checkout@v4 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: "3.4" + + - uses: actions/download-artifact@v4 + with: + path: dist + merge-multiple: true + + - name: Configure RubyGems Trusted Publishing (OIDC) + uses: rubygems/configure-rubygems-credentials@v1 + + - name: Push verified gems to RubyGems + run: | + for g in dist/*.gem; do + echo "Pushing $g" + gem push "$g" + done + + - name: Create GitHub Release + if: startsWith(github.ref, 'refs/tags/v') + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + gh release create "${GITHUB_REF_NAME}" dist/*.gem \ + --title "v${{ needs.verify-metadata.outputs.version }}" \ + --generate-notes diff --git a/.gitignore b/.gitignore index 9097d09..12cd495 100644 --- a/.gitignore +++ b/.gitignore @@ -1,35 +1,32 @@ -# Bundler -/.bundle/ -/vendor/bundle/ -/vendor/executorch/ -Gemfile.lock +*.gem +*.rbc +/.config +/coverage/ +/InstalledFiles +/pkg/ +/spec/reports/ +/spec/examples.txt +/test/tmp/ +/test/version_tmp/ +/tmp/ +/vendor/ +/lib/executorch/vendor/ +/lib/executorch/3.*/ +/test/fixtures/models/ # Build artifacts -/tmp/ -/pkg/ -*.gem -*.so -*.bundle -*.o -*.a -Makefile -mkmf.log +ext/executorch/Makefile +ext/executorch/mkmf.log +ext/executorch/*.o +ext/executorch/*.so +ext/executorch/*.bundle +lib/executorch/*.so +lib/executorch/*.bundle -# IDE -.idea/ +# Bundler / IDE +.bundle/ +Gemfile.lock +.DS_Store *.swp *.swo -.vscode/ - -# macOS -.DS_Store - -# Test models (generated) -test/support/models/*.pte - -# Generated documentation -/doc/ -/rdoc/ - -# Coverage -/coverage/ +*~ diff --git a/CHANGELOG.md b/CHANGELOG.md index 625ced1..284d2ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,46 +2,32 @@ All notable changes to this project will be documented in this file. -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [0.1.0] - 2024-12-27 +## [1.0.0] - 2026-11-19 + +Complete from-scratch rewrite targeting ExecuTorch 1.6.0 and Ruby >= 3.2. + +### Breaking Changes + +- Replaced `Executorch::Model` with `Executorch::Module` (`Module.open`, `Module.from_bytes`, `#call`, `#forward`, `#execute`, `#meta`, `#load_method`, `#unload_method`, `#close`). +- Canonical tensor dtype symbols are now explicit-width (`:float32`, `:float64`, `:float16`, `:bfloat16`, `:uint8`, `:int8`, `:int16`, `:uint16`, `:int32`, `:uint32`, `:int64`, `:uint64`, `:bool`). Short aliases (`:float`, `:double`, `:int`, `:long`, etc.) remain accepted on input. +- Raised minimum Ruby version to `>= 3.2.0`. +- Removed `rice` dependency and leaked internal methods (`_original_to_a`, `Tensor.create`, `Tensor.from_array`, `NATIVE_VERSION`, `NativeError`). ### Added -- `Executorch::Model` - Load and execute `.pte` models - - `Model.new(path)` - Load model from file - - `#predict(inputs)` - Run inference (recommended) - - `#forward(inputs)` - Run inference (PyTorch-style alias) - - `#call(inputs)` - Run inference (Ruby-style, makes model callable) - - `#execute(method_name, inputs)` - Execute named method - - `#method_names` - List available methods - - `#loaded?` - Check if model is loaded -- `Executorch::Tensor` - Multi-dimensional array support - - `Tensor.new(nested_data)` - Create from nested array (shape inferred) - - `Tensor.new(flat_data, shape:, dtype:)` - Create from flat array with explicit shape - - Supported dtypes: `:float`, `:double`, `:int`, `:long` - - `#to_a` - Convert to nested Ruby array matching shape - - `#flat_to_a` - Convert to flat Ruby array - - `#shape`, `#dim`, `#numel`, `#dtype` - Inspection methods -- Build configuration via `--with-executorch-dir` flag or `EXECUTORCH_DIR` environment variable - - `bundle config set --local build.executorch --with-executorch-dir=/path` (recommended) - - `EXECUTORCH_DIR=/path bundle install` (for CI) - - `EXECUTORCH_EXTRA_LIBS` for additional backend libraries -- Test models and export script - -### Known Limitations - -- Bool tensors (`:bool` dtype) not yet supported for creation -- No prebuilt binaries - requires ExecuTorch built from source -- macOS and Linux only (no Windows) - -### Design Decisions - -- Tensors are cloned when passed to inference methods for memory safety (slight performance overhead) -- dtype symbols use short names (`:int`, `:long`) rather than explicit sizes (`:int32`, `:int64`) -- EValue (ExecuTorch's internal tagged union) is not exposed; scalar outputs are auto-converted to Ruby types - -## [Unreleased] - -_No unreleased changes._ +- Two-layer `noexcept` C++17 core beneath a direct Ruby C-API seam — eliminates `rb_raise` `longjmp`-past-destructor UB by construction. +- Strict symbol visibility (`-fvisibility=hidden` + ELF version script / macOS `-exported_symbol,_Init_executorch`) preventing ODR collisions with `torch.rb`, `onnxruntime-ruby`, or `ruby-vips`. +- GVL release (`rb_thread_call_without_gvl`) during module load, method load, and execution, paired with per-method thread-safety mutexes and `RB_GC_GUARD`. +- Native memory pressure reporting (`dsize` + `rb_gc_adjust_memory_usage`) and deterministic `#close` / block-form `Module.open`. +- Support for all 13 numeric/boolean dtypes, 0-D scalar tensors (`Tensor#item`), non-contiguous / `NHWC` `dim_order` normalization, value equality (`Tensor#==`), `Tensor.zeros`/`ones`/`full`, `Tensor.from_bytes`/`#to_bytes`, zero-copy `IO::Buffer` (`Tensor.from_buffer`/`#to_buffer`), pre-allocated `out:` output reuse, and optional `Numo::NArray`/`Torch::Tensor` adapters. +- `Module.open` defaults to `:mmap` (supporting `Pathname`, all `LoadMode`s, and external `.ptd` `data_files`), plus `Module.from_bytes` (`BufferDataLoader`) and `MethodMeta` / `TensorInfo` introspection. +- Runtime introspection (`Executorch.backends`, `.kernel_count`, `.num_threads`, `.num_threads=`, `.executorch_version`), PAL initialization (`runtime_init`), and thread-local PAL error log capture attached to typed `Executorch::Error` subclasses (`LoadError`, `MethodNotFoundError`, `OperatorMissingError`, `DelegateError`, `ShapeError`, `DTypeError`, `ExecutionError`, `MemoryError`, `ClosedError`). +- Automatic SHA-256-verified official ExecuTorch 1.6.0 C++ SDK fetcher (`lib/executorch/sdk.rb`) with XNNPACK, optimized kernels, and quantized kernels out of the box, plus CI-gated fat platform gem packaging and OIDC release workflows. +- Deterministic `.pte`/`.ptd` test fixture export pipeline (`test/fixtures/export_fixtures.py`) and comprehensive correctness, ASan/UBSan, GC stress, concurrency, and adversarial safety test suites (0 skipped tests). + +## [0.1.0] - 2025-11-16 + +Initial prototype release. diff --git a/Gemfile b/Gemfile index 4a46472..8eb46f1 100644 --- a/Gemfile +++ b/Gemfile @@ -1,8 +1,9 @@ +# frozen_string_literal: true + source "https://rubygems.org" gemspec -group :development do - gem "rake-compiler" - gem "minitest", "~> 5.0" -end +gem "minitest", "~> 5.25" +gem "rake", "~> 13.2" +gem "rake-compiler", "~> 1.2" diff --git a/README.md b/README.md index 5b9050d..1ddc8c1 100644 --- a/README.md +++ b/README.md @@ -1,198 +1,204 @@ -# ExecuTorch Ruby +# Executorch for Ruby -Run PyTorch models in Ruby. +[![CI](https://github.com/benngarcia/executorch-ruby/actions/workflows/ci.yml/badge.svg)](https://github.com/benngarcia/executorch-ruby/actions/workflows/ci.yml) +[![Gem Version](https://badge.fury.io/rb/executorch.svg)](https://rubygems.org/gems/executorch) +[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE.txt) -[ExecuTorch](https://pytorch.org/executorch/) is Meta's lightweight runtime for deploying PyTorch models on edge devices. This gem provides Ruby bindings so you can run exported models (`.pte` files) directly in your Ruby applications. +Run PyTorch models natively in Ruby via Meta's [ExecuTorch](https://pytorch.org/executorch/) (`1.6.0`) runtime — with **zero Python at inference time**, **zero runtime gem dependencies**, and **precompiled native gems** that install in seconds. -## Quick Start +## Why ExecuTorch in Ruby? -```ruby -require "executorch" +- **`gem install executorch` just works:** Precompiled platform gems bundle the official ExecuTorch 1.6.0 C++ runtime, XNNPACK, optimized CPU kernels, and quantized kernels (+ CoreML & MLX on Apple Silicon) in a ~5 MB package. No CMake, Python, Buck2, or 40-minute source builds. +- **Built for production Ruby servers (Puma, Sidekiq, Falcon):** + - **Releases the GVL** during model load and inference so background Ruby threads and web workers never stall, with per-method thread-safety locks. + - **Defaults to `mmap`** for copy-on-write weight sharing across forked workers. + - **GC-aware & deterministic cleanup:** Reports native memory to Ruby's GC (`dsize` + `rb_gc_adjust_memory_usage`) and supports `#close` / block-form `Module.open`. +- **C++17 speed without Rice overhead:** Direct Ruby C API over a `noexcept` C++17 core (`~6.3 µs` zero-copy forward floor; `~30.5 µs` XNNPACK Conv2d CNN; strict symbol hiding exporting only `Init_executorch` so it co-loads safely alongside `torch.rb`, `onnxruntime`, or `ruby-vips`). +- **Complete ExecuTorch surface:** `MethodMeta` introspection, multi-method `.pte` programs, external `.ptd` weights, in-memory `Module.from_bytes`, all 13 numeric/bool dtypes (including `:float16`, `:bfloat16`, `:uint8`, `:bool`), zero-copy `IO::Buffer`, pre-allocated `out:` output reuse, and typed `Executorch::Error` exceptions with captured PAL diagnostics. -# Load a model -model = Executorch::Model.new("model.pte") +## Platform & Delegate Support -# Create input tensor -input = Executorch::Tensor.new([[1.0, 2.0, 3.0]]) +| Platform | Precompiled Gem | Included Delegates & Kernels | +|---|---|---| +| `x86_64-linux` | Yes | XNNPACK, Optimized CPU, Quantized | +| `aarch64-linux` | Yes | XNNPACK (KleidiAI), Optimized CPU, Quantized, TorchAO | +| `arm64-darwin` (Apple Silicon) | Yes | XNNPACK, CoreML, MLX, Optimized CPU, Quantized, TorchAO | +| Source fallback (`ruby`) | Yes | Auto-fetches SHA-256-verified ExecuTorch 1.6.0 SDK (or uses `--with-executorch-dir`) | -# Run inference -output = model.predict([input]).first -puts output.to_a # => [[3.0, 5.0, 7.0]] -``` +Requires **Ruby `>= 3.2`**. ## Installation -**Requirements:** Ruby 3.0+, macOS or Linux, C++17 compiler +Add to your `Gemfile`: -### Step 1: Build ExecuTorch +```ruby +gem "executorch", "~> 1.0" +``` -ExecuTorch must be built from source. Follow the [official guide](https://pytorch.org/executorch/stable/getting-started-setup.html), or use these commands: +Or install directly: ```bash -git clone https://github.com/pytorch/executorch.git -cd executorch -./install_requirements.sh - -cmake -B cmake-out \ - -DCMAKE_INSTALL_PREFIX=vendor/executorch \ - -DEXECUTORCH_BUILD_EXTENSION_MODULE=ON \ - -DEXECUTORCH_BUILD_EXTENSION_DATA_LOADER=ON \ - -DEXECUTORCH_BUILD_EXTENSION_TENSOR=ON \ - -DCMAKE_BUILD_TYPE=Release - -cmake --build cmake-out -j4 -cmake --install cmake-out +gem install executorch ``` -### Step 2: Install the Gem +## Quick Start: PyTorch to Ruby in 60 Seconds -Tell Bundler where ExecuTorch is installed (only needed once per project): +### 1. Export a PyTorch model to `.pte` (once, in Python) -```bash -bundle config set --local build.executorch --with-executorch-dir=vendor/executorch -``` +```python +import torch +from executorch.backends.xnnpack.partition.xnnpack_partitioner import XnnpackPartitioner +from executorch.exir import to_edge_transform_and_lower -Add to your Gemfile: +class AddMul(torch.nn.Module): + def forward(self, x): + return x * 2.0 + 1.0 -```ruby -gem "executorch" +example_input = (torch.tensor([[1.0, 2.0, 3.0]], dtype=torch.float32),) +exported = torch.export.export(AddMul().eval(), example_input) +et_program = to_edge_transform_and_lower( + exported, partitioner=[XnnpackPartitioner()] +).to_executorch() + +with open("model.pte", "wb") as f: + et_program.write_to_file(f) ``` -Then: +### 2. Run it natively in Ruby (no Python required) -```bash -bundle install -``` +```ruby +require "executorch" -> **CI/CD:** Use the environment variable instead: `EXECUTORCH_DIR=/path/to/executorch bundle install` +# Defaults to :mmap (CoW-friendly across forked Puma workers). +# Accepts String or Pathname; block form closes deterministically. +Executorch::Module.open("model.pte") do |mod| + meta = mod.meta(:forward) + p meta.backends # => ["XnnpackBackend"] + p meta.inputs # => [#] + + input = Executorch::Tensor.new([[1.0, 2.0, 3.0]]) + output = mod.call(input) + p output.to_a # => [[3.0, 5.0, 7.0]] +end +``` ## Usage -### Tensors +### Zero-copy `IO::Buffer` and pre-allocated output reuse -Create tensors from nested arrays (shape is inferred): +For hot inference loops (images, audio, embeddings), avoid array boxing and per-call allocations completely: ```ruby -# 2D tensor, shape [2, 3] -tensor = Executorch::Tensor.new([[1.0, 2.0, 3.0], - [4.0, 5.0, 6.0]]) +Executorch.num_threads = 2 # Prevent oversubscription in multi-worker Puma servers + +in_buf = IO::Buffer.for([1.0, 2.0, 3.0].pack("f*")) +out_buf = IO::Buffer.new(12) -# With explicit dtype -tensor = Executorch::Tensor.new([[1, 2], [3, 4]], dtype: :long) +input = Executorch::Tensor.from_buffer(in_buf, shape: [1, 3], dtype: :float32) +output = Executorch::Tensor.from_buffer(out_buf, shape: [1, 3], dtype: :float32) -# Inspect -tensor.shape # => [2, 3] -tensor.dtype # => :float -tensor.to_a # => [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]] +Executorch::Module.open("model.pte") do |mod| + mod.call(input, out: output) # Releases GVL; writes directly into out_buf + p out_buf.get_string.unpack("f*") # => [3.0, 5.0, 7.0] +end ``` -Or from flat arrays with explicit shape: +### Multi-method models, external `.ptd` weights, and in-memory loading ```ruby -tensor = Executorch::Tensor.new([1.0, 2.0, 3.0, 4.0], shape: [2, 2]) +# Multi-method .pte (e.g. encode / decode, prefill / decode) +Executorch::Module.open("autoencoder.pte") do |mod| + z = mod.execute(:encode, x).first + reconstructed = mod.execute(:decode, z).first +end + +# External .ptd weights (LLMs and larger models) +Executorch::Module.open("model.pte", data_files: ["weights.ptd"], load_mode: :mmap_mlock) do |mod| + logits = mod.call(tokens) +end + +# Load straight from memory (e.g. S3 / ActiveStorage) without a tempfile +mod = Executorch::Module.from_bytes(pte_bytes) +mod.close ``` -**Supported dtypes:** `:float` (default), `:double`, `:int`, `:long` +### Tensors, dtypes & ecosystem adapters -### Models +Canonical dtypes: `:float32`, `:float64`, `:float16`, `:bfloat16`, `:uint8`, `:int8`, `:int16`, `:uint16`, `:int32`, `:uint32`, `:int64`, `:uint64`, `:bool`. Short aliases (`:float`, `:double`, `:half`, `:byte`, `:char`, `:short`, `:int`, `:long`) are accepted on input. ```ruby -model = Executorch::Model.new("model.pte") - -# Run inference (all equivalent) -outputs = model.predict([input]) -outputs = model.forward([input]) -outputs = model.call([input]) - -# Introspection -model.loaded? # => true -model.method_names # => ["forward"] +t = Executorch::Tensor.new([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) +t.shape # => [2, 3] +t.dtype # => :float32 +t.nbytes # => 24 +t.to_a # => [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]] + +# 0-D scalar tensors +scalar = Executorch::Tensor.new(42.5, dtype: :float32) +scalar.shape # => [] +scalar.item # => 42.5 + +# Binary I/O & factories +raw = t.to_bytes +t2 = Executorch::Tensor.from_bytes(raw, shape: [2, 3], dtype: :float32) +t == t2 # => true + +zeros = Executorch::Tensor.zeros([2, 3], dtype: :float32) +ones = Executorch::Tensor.ones([2, 3], dtype: :int64) ``` -## Exporting Models +Optional adapters are built in for `Numo::NArray` (`Tensor.from_numo` / `Tensor#to_numo`) and `Torch::Tensor` (`Tensor.from_torch`). -Export PyTorch models to `.pte` format: +### Runtime introspection & typed errors -```python -import torch -from executorch.exir import to_edge - -class MyModel(torch.nn.Module): - def forward(self, x): - return x * 2 + 1 - -model = MyModel() -example_input = torch.randn(1, 3) - -exported = torch.export.export(model, (example_input,)) -et_program = to_edge(exported).to_executorch() - -with open("model.pte", "wb") as f: - et_program.write_to_file(f) +```ruby +Executorch.backends # => ["XnnpackBackend"] +Executorch.kernel_count # => 263 +Executorch.num_threads # => 24 +Executorch.executorch_version # => "1.6.0" ``` -## Troubleshooting +All runtime failures inherit from `Executorch::Error < StandardError` (`LoadError`, `MethodNotFoundError`, `OperatorMissingError`, `DelegateError`, `ShapeError`, `DTypeError`, `ExecutionError`, `MemoryError`, `ClosedError`) and expose `#code` (ExecuTorch error code) and `#pal_log` (captured PAL diagnostics). -
-"ExecuTorch installation not found" +### Using a custom ExecuTorch installation -Verify your installation and configure the path: +If you built ExecuTorch yourself (shared or static), point `extconf.rb` at its absolute prefix: ```bash -ls vendor/executorch/include/executorch # Should exist -bundle config set --local build.executorch --with-executorch-dir=vendor/executorch +bundle config set --local build.executorch --with-executorch-dir=/absolute/path/to/executorch ``` -
-
-"module.h header not found" +Or pass `EXECUTORCH_DIR=/absolute/path/to/executorch`. Set `EXECUTORCH_NO_DOWNLOAD=1` to disable automatic SDK fetching. -ExecuTorch was built without required extensions. Rebuild with: +## Upgrading from 0.1.x -```bash -cmake -B cmake-out \ - -DEXECUTORCH_BUILD_EXTENSION_MODULE=ON \ - -DEXECUTORCH_BUILD_EXTENSION_DATA_LOADER=ON \ - -DEXECUTORCH_BUILD_EXTENSION_TENSOR=ON \ - ... -``` -
- -
-"undefined symbol" at runtime - -Try linking additional libraries: - -```bash -EXECUTORCH_EXTRA_LIBS=portable_ops_lib,portable_kernels bundle exec rake compile -``` -
- -## Resources - -- [ExecuTorch Documentation](https://pytorch.org/executorch/) -- [Changelog](CHANGELOG.md) -- [Report an Issue](https://github.com/benngarcia/executorch-ruby/issues) +- `Executorch::Model` is replaced by `Executorch::Module` (`Module.open`, `#call`, `#forward`, `#execute`, `#meta`, `#close`). +- Canonical dtype symbols are now explicit-width (`:float32`, `:int64`, etc.); short aliases remain accepted on input. +- Minimum Ruby version is now `>= 3.2`. +- `rice` is no longer a dependency. ## Development ```bash -git clone https://github.com/benngarcia/executorch-ruby.git -cd executorch-ruby bundle install -bundle config set --local build.executorch --with-executorch-dir=vendor/executorch -bundle exec rake compile -bundle exec rake test +bundle exec rake sdk:fetch # Fetches verified ExecuTorch 1.6.0 C++ SDK into ~/.cache/executorch-ruby/ +bundle exec rake compile # Compiles native C++17 extension +bundle exec rake fixtures:export # Exports deterministic .pte/.ptd test models via uv +bundle exec rake test # Runs full test suite (0 skips) +ruby bench/run_bench.rb # Runs local latency benchmarks ``` -## Contributing +To build and test under AddressSanitizer + UndefinedBehaviorSanitizer on Linux: -Bug reports and pull requests are welcome on [GitHub](https://github.com/benngarcia/executorch-ruby). +```bash +bundle exec rake clean +EXECUTORCH_SANITIZE=1 bundle exec rake compile +LD_PRELOAD="$(g++ -print-file-name=libasan.so):$(g++ -print-file-name=libubsan.so)" \ + ASAN_OPTIONS=detect_leaks=0:use_sigaltstack=0:halt_on_error=1 \ + UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 \ + bundle exec rake test +``` ## License Apache License 2.0. See [LICENSE.txt](LICENSE.txt). - -## Acknowledgments - -Built with [Rice](https://github.com/jasonroelofs/rice). Inspired by [onnxruntime-ruby](https://github.com/ankane/onnxruntime-ruby) and [torch.rb](https://github.com/ankane/torch.rb). diff --git a/Rakefile b/Rakefile index 7cd5c27..fde0418 100644 --- a/Rakefile +++ b/Rakefile @@ -1,52 +1,86 @@ -require 'bundler/gem_tasks' -require 'rake/testtask' -require 'rake/extensiontask' +# frozen_string_literal: true -Rake::TestTask.new(:test) do |t| - t.libs << 'test' - t.libs << 'lib' - t.test_files = FileList['test/**/*_test.rb'] +require "bundler/gem_tasks" +require "fileutils" +require "rake/extensiontask" +require "rake/testtask" +require "rbconfig" +require_relative "lib/executorch/sdk" + +gemspec = Gem::Specification.load(File.expand_path("executorch.gemspec", __dir__)) + +Rake::ExtensionTask.new("executorch", gemspec) do |ext| + ext.lib_dir = "lib/executorch" + ext.source_pattern = "*.{cpp,hpp,h}" end -Rake::ExtensionTask.new('executorch') do |ext| - ext.lib_dir = 'lib/executorch' +Rake::TestTask.new(:test) do |t| + t.libs << "test" + t.libs << "lib" + t.test_files = FileList["test/*_test.rb"] + t.warning = true end task default: %i[compile test] -namespace :executorch do - desc 'Build ExecuTorch from source and install to vendor/executorch' - task :build_deps do - source_dir = ENV.fetch('EXECUTORCH_SRC', File.expand_path('../executorch', __dir__)) - install_dir = File.expand_path('vendor/executorch', __dir__) +namespace :sdk do + desc "Download and verify the pinned ExecuTorch C++ SDK into local cache" + task :fetch do + dir = Executorch::SDK.ensure_sdk + puts "SDK ready at: #{dir}" + end +end - unless File.directory?(source_dir) - abort "ExecuTorch source not found at #{source_dir}. Clone it or set EXECUTORCH_SRC." +namespace :fixtures do + desc "Export deterministic .pte/.ptd test fixtures using uv" + task :export do + out_dir = ENV.fetch("EXECUTORCH_FIXTURES_DIR", File.expand_path("test/fixtures/models", __dir__)) + py = ENV["EXECUTORCH_PYTHON"] || File.expand_path("~/.cache/executorch-ruby/venv/bin/python") + if File.executable?(py) + sh py, "test/fixtures/export_fixtures.py", "--out", out_dir + else + sh "uv", "run", "--project", "test/fixtures", "python", "test/fixtures/export_fixtures.py", "--out", out_dir end + end +end - puts "Building ExecuTorch from #{source_dir}..." - puts "Installing to #{install_dir}..." +desc "Clean build outputs (preserves SDK cache and exported fixtures)" +task :clean do + dlext = RbConfig::CONFIG["DLEXT"] + FileUtils.rm_rf("tmp/x86_64-linux") + FileUtils.rm_rf("tmp/aarch64-linux") + FileUtils.rm_rf("tmp/arm64-darwin") + FileUtils.rm_rf("tmp/x86_64-darwin") + FileUtils.rm_rf("pkg") + FileUtils.rm_rf("lib/executorch/vendor") + Dir.glob("lib/executorch/**/*.{#{dlext},so,bundle}").each { |f| FileUtils.rm_f(f) } +end - Dir.chdir(source_dir) do - system('cmake', '-B', 'cmake-out', - "-DCMAKE_INSTALL_PREFIX=#{install_dir}", - '-DEXECUTORCH_BUILD_EXTENSION_MODULE=ON', - '-DEXECUTORCH_BUILD_EXTENSION_DATA_LOADER=ON', - '-DEXECUTORCH_BUILD_EXTENSION_TENSOR=ON', - '-DCMAKE_BUILD_TYPE=Release') || abort('CMake configure failed') +desc "Build a precompiled platform fat gem for the current host platform" +task :package_platform do + platform = Gem::Platform.local + ENV["EXECUTORCH_BUNDLE_VENDOR"] = "1" + Rake::Task[:clean].invoke + Rake::Task[:compile].invoke - system('cmake', '--build', 'cmake-out', "-j#{Etc.nprocessors}") || abort('CMake build failed') - system('cmake', '--install', 'cmake-out') || abort('CMake install failed') - end + ruby_abi = RUBY_VERSION[/\A\d+\.\d+/] + dlext = RbConfig::CONFIG["DLEXT"] + src_ext = "lib/executorch/executorch.#{dlext}" + abi_dir = "lib/executorch/#{ruby_abi}" + FileUtils.mkdir_p(abi_dir) + FileUtils.mv(src_ext, File.join(abi_dir, "executorch.#{dlext}")) - puts "ExecuTorch installed to #{install_dir}" - puts "Run: bundle config set --local build.executorch --with-executorch-dir=#{install_dir}" - end -end + plat_spec = gemspec.dup + plat_spec.platform = platform + plat_spec.extensions = [] + plat_spec.files = ( + gemspec.files.reject { |f| f.start_with?("ext/") } + + Dir["lib/executorch/#{ruby_abi}/*.#{dlext}"] + + Dir["lib/executorch/vendor/*"] + ).uniq.sort -desc 'Clean build artifacts' -task :clean do - FileUtils.rm_rf('lib/executorch/executorch.bundle') - FileUtils.rm_rf('lib/executorch/executorch.so') - FileUtils.rm_rf('tmp') + FileUtils.mkdir_p("pkg") + gem_file = Gem::Package.build(plat_spec) + FileUtils.mv(gem_file, File.join("pkg", File.basename(gem_file))) + puts "Built platform gem: pkg/#{File.basename(gem_file)}" end diff --git a/bench/run_bench.rb b/bench/run_bench.rb new file mode 100644 index 0000000..0421c95 --- /dev/null +++ b/bench/run_bench.rb @@ -0,0 +1,55 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +$LOAD_PATH.unshift File.expand_path("../lib", __dir__) +require "executorch" +require "json" + +FIXTURES_DIR = File.expand_path("../test/fixtures/models", __dir__) +MANIFEST = JSON.parse(File.read(File.join(FIXTURES_DIR, "manifest.json"))) + +def measure(label, warmup: 10, iters: 100) + warmup.times { yield } + GC.start(full_mark: true, immediate_sweep: true) + + samples = Array.new(iters) do + t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC) + yield + (Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0) * 1000.0 + end + samples.sort! + p50 = samples[(samples.size * 0.50).floor] + p95 = samples[[(samples.size * 0.95).floor, samples.size - 1].min] + printf "%-36s p50=%8.4f ms p95=%8.4f ms (n=%d)\n", label, p50, p95, iters +end + +puts "executorch-ruby #{Executorch::VERSION} | ExecuTorch SDK #{Executorch.executorch_version}" +puts "Backends: #{Executorch.backends.inspect} | Kernels: #{Executorch.kernel_count} | Threads: #{Executorch.num_threads}" +puts "-" * 78 + +%w[add_mul cnn_xnnpack heavy_mlp].each do |name| + spec = MANIFEST.fetch("models").fetch(name) + path = File.join(FIXTURES_DIR, spec["file"]) + in_desc = spec["inputs"].first + out_desc = spec["outputs"].first + + nested = in_desc["values"] + shape = in_desc["shape"] + raw = nested.pack("f*") + in_buf = IO::Buffer.for(raw) + out_buf = IO::Buffer.new(out_desc["values"].size * 4) + + Executorch::Module.open(path) do |mod| + mod.load_method(:forward) + t_in = Executorch::Tensor.from_buffer(in_buf, shape: shape, dtype: :float32) + t_out = Executorch::Tensor.from_buffer(out_buf, shape: out_desc["shape"], dtype: :float32) + + iters = name == "heavy_mlp" ? 30 : 200 + measure("#{name} / forward (owned)", iters: iters) { mod.call(t_in) } + measure("#{name} / forward (zero-copy out:)", iters: iters) { mod.call(t_in, out: t_out) } + measure("#{name} / e2e from_bytes + to_bytes", iters: iters) do + t = Executorch::Tensor.from_bytes(raw, shape: shape, dtype: :float32) + mod.call(t).to_bytes + end + end +end diff --git a/executorch.gemspec b/executorch.gemspec index 47e4504..46b4acf 100644 --- a/executorch.gemspec +++ b/executorch.gemspec @@ -1,33 +1,44 @@ -require_relative 'lib/executorch/version' +# frozen_string_literal: true -Gem::Specification.new do |spec| - spec.name = 'executorch' - spec.version = Executorch::VERSION - spec.authors = ['Benjamin Garcia'] - spec.email = ['hey@bengarcia.dev'] +require_relative "lib/executorch/version" - spec.summary = 'Ruby bindings for ExecuTorch' - spec.description = 'Run PyTorch models exported with ExecuTorch in Ruby' - spec.homepage = 'https://github.com/benngarcia/executorch-ruby' - spec.license = 'Apache-2.0' - spec.required_ruby_version = '>= 3.0.0' +Gem::Specification.new do |spec| + spec.name = "executorch" + spec.version = Executorch::VERSION + spec.authors = ["Benjamin Garcia"] + spec.email = ["hey@bengarcia.dev"] - spec.files = Dir[ - 'LICENSE.txt', - 'README.md', - 'CHANGELOG.md', - 'lib/**/*.rb', - 'ext/**/*.{rb,cpp,h,hpp}' - ] + spec.summary = "Native Ruby bindings for Meta's ExecuTorch runtime" + spec.description = "Run PyTorch models exported with ExecuTorch (.pte / .ptd) natively in Ruby with XNNPACK/CoreML acceleration, GVL-free execution, and zero-copy IO::Buffer tensors." + spec.homepage = "https://github.com/benngarcia/executorch-ruby" + spec.license = "Apache-2.0" + spec.required_ruby_version = ">= 3.2.0" - spec.require_paths = ['lib'] - spec.extensions = ['ext/executorch/extconf.rb'] + spec.files = Dir.chdir(__dir__) do + if File.directory?(".git") + `git ls-files -z`.split("\x0").select do |f| + f.start_with?("lib/", "ext/") || + %w[.executorch-version LICENSE.txt README.md CHANGELOG.md].include?(f) + end + else + Dir[ + ".executorch-version", + "LICENSE.txt", + "README.md", + "CHANGELOG.md", + "lib/**/*.rb", + "ext/**/*.{rb,cpp,hpp,h,map}", + ] + end + end - spec.add_dependency 'rice', '>= 4.3' + spec.require_paths = ["lib"] + spec.extensions = ["ext/executorch/extconf.rb"] spec.metadata = { - 'homepage_uri' => spec.homepage, - 'source_code_uri' => spec.homepage, - 'changelog_uri' => "#{spec.homepage}/blob/main/CHANGELOG.md" + "source_code_uri" => spec.homepage, + "changelog_uri" => "#{spec.homepage}/blob/master/CHANGELOG.md", + "bug_tracker_uri" => "#{spec.homepage}/issues", + "rubygems_mfa_required" => "true", } end diff --git a/ext/executorch/core/core.cpp b/ext/executorch/core/core.cpp new file mode 100644 index 0000000..0874b0c --- /dev/null +++ b/ext/executorch/core/core.cpp @@ -0,0 +1,1131 @@ +#include "module_core.hpp" +#include "tensor_core.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#ifdef ET_USE_THREADPOOL +namespace executorch::extension::threadpool { +class ThreadPool { + public: + void _unsafe_reset_threadpool(uint32_t num_threads); + size_t get_thread_count() const; +}; +ThreadPool* get_threadpool(); +} // namespace executorch::extension::threadpool +#endif + +namespace etrb { + +namespace { + +thread_local std::string* g_pal_log_target = nullptr; +std::once_flag g_runtime_init_flag; +std::mutex g_threadpool_mu; +pal_emit_log_message_method g_default_pal_emit = nullptr; + +void etrb_pal_emit_log( + et_timestamp_t timestamp, + et_pal_log_level_t level, + const char* filename, + const char* function, + size_t line, + const char* message, + size_t length) { + if (g_pal_log_target != nullptr && + (level == kError || level == kFatal)) { + try { + if (!g_pal_log_target->empty()) { + g_pal_log_target->push_back('\n'); + } + if (message != nullptr && length > 0) { + g_pal_log_target->append(message, length); + } + } catch (...) { + // Never throw across C PAL boundary. + } + return; + } + if (g_default_pal_emit != nullptr && (level == kError || level == kFatal)) { + // Only forward uncaptured errors if user opted in via EXECUTORCH_LOG_STDERR. + static const bool forward_stderr = + std::getenv("EXECUTORCH_LOG_STDERR") != nullptr; + if (forward_stderr) { + g_default_pal_emit( + timestamp, level, filename, function, line, message, length); + } + } +} + +bool mul_overflow_size(size_t a, size_t b, size_t* out) noexcept { +#if defined(__GNUC__) || defined(__clang__) + return __builtin_mul_overflow(a, b, out); +#else + if (a != 0 && b > std::numeric_limits::max() / a) { + return true; + } + *out = a * b; + return false; +#endif +} + +} // namespace + +void init_runtime_once() noexcept { + std::call_once(g_runtime_init_flag, []() { + executorch::runtime::runtime_init(); + const auto* existing = executorch::runtime::get_pal_impl(); + if (existing != nullptr) { + g_default_pal_emit = existing->emit_log_message; + } + auto impl = executorch::runtime::PalImpl::create( + &etrb_pal_emit_log, __FILE__); + executorch::runtime::register_pal(impl); + }); +} + +PalLogScope::PalLogScope() noexcept { + prev_buf_ = g_pal_log_target; + g_pal_log_target = &buf_; +} + +PalLogScope::~PalLogScope() noexcept { + g_pal_log_target = prev_buf_; +} + +std::string PalLogScope::take() noexcept { + return std::move(buf_); +} + +Status status_from_et_error( + executorch::runtime::Error err, + const char* context, + std::string pal_log, + ErrorKind default_kind) noexcept { + if (err == executorch::runtime::Error::Ok) { + return Status::Ok(); + } + ErrorKind kind = default_kind; + switch (err) { + case executorch::runtime::Error::OperatorMissing: + kind = ErrorKind::OperatorMissing; + break; + case executorch::runtime::Error::DelegateInvalidCompatibility: + case executorch::runtime::Error::DelegateMemoryAllocationFailed: + case executorch::runtime::Error::DelegateInvalidHandle: + kind = ErrorKind::Delegate; + break; + case executorch::runtime::Error::MemoryAllocationFailed: + case executorch::runtime::Error::OutOfResources: + kind = ErrorKind::Memory; + break; + case executorch::runtime::Error::AccessFailed: + case executorch::runtime::Error::InvalidProgram: + case executorch::runtime::Error::InvalidExternalData: + kind = ErrorKind::Load; + break; + case executorch::runtime::Error::NotFound: + kind = (default_kind == ErrorKind::MethodNotFound) + ? ErrorKind::MethodNotFound + : ErrorKind::Load; + break; + case executorch::runtime::Error::InvalidArgument: + if (default_kind == ErrorKind::Load) { + kind = ErrorKind::Load; + } else if (default_kind == ErrorKind::MethodNotFound || + pal_log.find("No method named") != std::string::npos) { + kind = ErrorKind::MethodNotFound; + } else { + kind = ErrorKind::Execution; + } + break; + case executorch::runtime::Error::InvalidType: + kind = ErrorKind::Type; + break; + default: + kind = default_kind; + break; + } + + try { + const char* ename = executorch::runtime::to_string(err); + std::string msg = std::string(context) + ": " + ename + " (0x" + + [&]() { + char hex[16]; + std::snprintf( + hex, sizeof(hex), "%x", static_cast(err)); + return std::string(hex); + }() + + ")"; + if (!pal_log.empty()) { + msg += " — " + pal_log; + } + return Status::Make( + kind, std::move(msg), static_cast(err), std::move(pal_log)); + } catch (...) { + return Status::Make( + ErrorKind::Memory, "out of memory formatting ExecuTorch error"); + } +} + +// --------------------------------------------------------------------------- +// TensorCore helpers +// --------------------------------------------------------------------------- + +AlignedBuffer::~AlignedBuffer() noexcept { + if (ptr != nullptr) { + std::free(ptr); + ptr = nullptr; + nbytes = 0; + } +} + +AlignedBuffer::AlignedBuffer(AlignedBuffer&& other) noexcept + : ptr(other.ptr), nbytes(other.nbytes) { + other.ptr = nullptr; + other.nbytes = 0; +} + +AlignedBuffer& AlignedBuffer::operator=(AlignedBuffer&& other) noexcept { + if (this != &other) { + if (ptr != nullptr) { + std::free(ptr); + } + ptr = other.ptr; + nbytes = other.nbytes; + other.ptr = nullptr; + other.nbytes = 0; + } + return *this; +} + +StatusOr AlignedBuffer::allocate(size_t nbytes) noexcept { + AlignedBuffer buf; + buf.nbytes = nbytes; + if (nbytes == 0) { + return StatusOr::Ok(std::move(buf)); + } + void* mem = nullptr; + if (::posix_memalign(&mem, 64, nbytes) != 0 || mem == nullptr) { + return StatusOr::Err( + Status::Make(ErrorKind::Memory, "failed to allocate tensor buffer")); + } + buf.ptr = mem; + return StatusOr::Ok(std::move(buf)); +} + +StatusOr AlignedBuffer::allocate_zeroed(size_t nbytes) noexcept { + auto res = allocate(nbytes); + if (!res.ok()) { + return res; + } + if (nbytes > 0 && res.value.ptr != nullptr) { + std::memset(res.value.ptr, 0, nbytes); + } + return res; +} + +StatusOr validate_shape( + const std::vector& raw_dims, + executorch::aten::ScalarType dtype) noexcept { + try { + if (!is_supported_dtype(dtype)) { + return StatusOr::Err(Status::Make( + ErrorKind::DType, + std::string("unsupported dtype: ") + scalar_type_name(dtype))); + } + const size_t item_size = scalar_type_size(dtype); + ShapeInfo info; + info.sizes.reserve(raw_dims.size()); + + constexpr int64_t kMaxDim = + static_cast(std::numeric_limits::max()); + size_t numel = 1; + bool has_zero = false; + + for (size_t i = 0; i < raw_dims.size(); ++i) { + const int64_t d = raw_dims[i]; + if (d < 0) { + return StatusOr::Err(Status::Make( + ErrorKind::Shape, + "shape dimension at axis " + std::to_string(i) + + " must be non-negative, got " + std::to_string(d))); + } + if (d > kMaxDim) { + return StatusOr::Err(Status::Make( + ErrorKind::Shape, + "shape dimension at axis " + std::to_string(i) + + " exceeds INT32_MAX: " + std::to_string(d))); + } + info.sizes.push_back(static_cast(d)); + if (d == 0) { + has_zero = true; + } else if (!has_zero) { + size_t next = 0; + if (mul_overflow_size(numel, static_cast(d), &next)) { + return StatusOr::Err(Status::Make( + ErrorKind::Shape, "tensor element count overflows size_t")); + } + numel = next; + } + } + + info.numel = has_zero ? 0 : numel; + if (mul_overflow_size(info.numel, item_size, &info.nbytes)) { + return StatusOr::Err(Status::Make( + ErrorKind::Shape, "tensor byte size overflows size_t")); + } + if (info.nbytes > static_cast(std::numeric_limits::max())) { + return StatusOr::Err(Status::Make( + ErrorKind::Shape, "tensor byte size exceeds SSIZE_MAX")); + } + return StatusOr::Ok(std::move(info)); + } catch (const std::bad_alloc&) { + return StatusOr::Err( + Status::Make(ErrorKind::Memory, "out of memory validating shape")); + } catch (...) { + return StatusOr::Err( + Status::Make(ErrorKind::Shape, "unexpected error validating shape")); + } +} + +bool is_standard_contiguous(const executorch::aten::Tensor& tensor) noexcept { + const ssize_t ndim = tensor.dim(); + if (ndim <= 0 || tensor.numel() <= 1) { + return true; + } + const auto sizes = tensor.sizes(); + const auto strides = tensor.strides(); + if (static_cast(strides.size()) != ndim) { + return false; + } + int64_t expected_stride = 1; + for (ssize_t i = ndim - 1; i >= 0; --i) { + const int64_t sz = static_cast(sizes[i]); + if (sz == 0) { + return true; + } + if (sz > 1 && static_cast(strides[i]) != expected_stride) { + return false; + } + expected_stride *= sz; + } + return true; +} + +Status copy_to_contiguous_bytes( + const executorch::aten::Tensor& tensor, + void* dst, + size_t dst_nbytes) noexcept { + const size_t elem_size = static_cast(tensor.element_size()); + const size_t numel = static_cast(tensor.numel()); + size_t needed = 0; + if (mul_overflow_size(numel, elem_size, &needed) || needed != dst_nbytes) { + return Status::Make( + ErrorKind::Shape, "destination buffer size does not match tensor nbytes"); + } + if (needed == 0) { + return Status::Ok(); + } + const auto* src = static_cast(tensor.const_data_ptr()); + if (src == nullptr || dst == nullptr) { + return Status::Make(ErrorKind::Memory, "null tensor data pointer"); + } + if (is_standard_contiguous(tensor)) { + std::memcpy(dst, src, needed); + return Status::Ok(); + } + + // General strided copy handling NHWC / channels-last / transposed layouts. + try { + const ssize_t ndim = tensor.dim(); + const auto sizes = tensor.sizes(); + const auto strides = tensor.strides(); + auto* out = static_cast(dst); + + std::vector coords(static_cast(ndim), 0); + for (size_t linear = 0; linear < numel; ++linear) { + int64_t elem_offset = 0; + for (ssize_t d = 0; d < ndim; ++d) { + elem_offset += coords[static_cast(d)] * + static_cast(strides[d]); + } + std::memcpy( + out + linear * elem_size, + src + static_cast(elem_offset) * elem_size, + elem_size); + + for (ssize_t d = ndim - 1; d >= 0; --d) { + coords[static_cast(d)]++; + if (coords[static_cast(d)] < static_cast(sizes[d])) { + break; + } + coords[static_cast(d)] = 0; + } + } + return Status::Ok(); + } catch (const std::bad_alloc&) { + return Status::Make( + ErrorKind::Memory, "out of memory copying strided tensor"); + } catch (...) { + return Status::Make( + ErrorKind::Execution, "unexpected error copying strided tensor"); + } +} + +StatusOr make_owned_tensor_ptr( + std::vector sizes, + executorch::aten::ScalarType dtype, + AlignedBuffer buf) noexcept { + try { + void* raw = buf.ptr; + auto holder = std::make_shared(std::move(buf)); + auto ptr = executorch::extension::make_tensor_ptr( + std::move(sizes), + raw, + dtype, + executorch::aten::Device(executorch::aten::DeviceType::CPU), + executorch::aten::TensorShapeDynamism::DYNAMIC_BOUND, + [holder = std::move(holder)](void*) {}); + return StatusOr::Ok(std::move(ptr)); + } catch (const std::bad_alloc&) { + return StatusOr::Err( + Status::Make(ErrorKind::Memory, "out of memory creating tensor")); + } catch (const std::exception& ex) { + return StatusOr::Err( + Status::Make(ErrorKind::Execution, ex.what())); + } catch (...) { + return StatusOr::Err( + Status::Make(ErrorKind::Execution, "failed creating tensor")); + } +} + +StatusOr make_borrowed_tensor_ptr( + std::vector sizes, + executorch::aten::ScalarType dtype, + void* data) noexcept { + try { + auto ptr = executorch::extension::make_tensor_ptr( + std::move(sizes), + data, + dtype, + executorch::aten::Device(executorch::aten::DeviceType::CPU), + executorch::aten::TensorShapeDynamism::DYNAMIC_BOUND, + nullptr); + return StatusOr::Ok(std::move(ptr)); + } catch (const std::bad_alloc&) { + return StatusOr::Err( + Status::Make(ErrorKind::Memory, "out of memory creating borrowed tensor")); + } catch (const std::exception& ex) { + return StatusOr::Err( + Status::Make(ErrorKind::Execution, ex.what())); + } catch (...) { + return StatusOr::Err( + Status::Make(ErrorKind::Execution, "failed creating borrowed tensor")); + } +} + +StatusOr clone_contiguous_tensor_ptr( + const executorch::aten::Tensor& tensor) noexcept { + try { + const auto dtype = tensor.scalar_type(); + const size_t nbytes = + static_cast(tensor.numel()) * static_cast(tensor.element_size()); + auto buf_res = AlignedBuffer::allocate(nbytes); + if (!buf_res.ok()) { + return StatusOr::Err( + std::move(buf_res.status)); + } + auto cp = copy_to_contiguous_bytes(tensor, buf_res.value.ptr, nbytes); + if (!cp.ok()) { + return StatusOr::Err(std::move(cp)); + } + std::vector sizes( + tensor.sizes().begin(), tensor.sizes().end()); + return make_owned_tensor_ptr( + std::move(sizes), dtype, std::move(buf_res.value)); + } catch (const std::bad_alloc&) { + return StatusOr::Err( + Status::Make(ErrorKind::Memory, "out of memory cloning tensor")); + } catch (...) { + return StatusOr::Err( + Status::Make(ErrorKind::Execution, "failed cloning tensor")); + } +} + +// --------------------------------------------------------------------------- +// ModuleCore +// --------------------------------------------------------------------------- + +StatusOr> ModuleCore::open_file( + const std::string& path, + const std::vector& data_files, + LoadMode load_mode) noexcept { + init_runtime_once(); + PalLogScope pal; + try { + struct stat st {}; + if (::stat(path.c_str(), &st) != 0) { + return StatusOr>::Err(Status::Make( + ErrorKind::Load, + "Cannot open ExecuTorch program '" + path + "': " + + std::strerror(errno))); + } + if (S_ISDIR(st.st_mode)) { + return StatusOr>::Err(Status::Make( + ErrorKind::Load, + "ExecuTorch program path is a directory: '" + path + "'")); + } + + size_t est = static_cast(st.st_size); + for (const auto& df : data_files) { + struct stat dst {}; + if (::stat(df.c_str(), &dst) != 0 || S_ISDIR(dst.st_mode)) { + return StatusOr>::Err(Status::Make( + ErrorKind::Load, + "Cannot open external data file '" + df + "'")); + } + est += static_cast(dst.st_size); + } + + std::unique_ptr core(new ModuleCore()); + core->source_label_ = path; + core->estimated_bytes_ = est; + + if (data_files.empty()) { + core->module_ = std::make_unique( + path, load_mode); + } else { + core->module_ = std::make_unique( + path, data_files, load_mode); + } + + auto err = core->module_->load( + executorch::runtime::Program::Verification::Minimal); + if (err != executorch::runtime::Error::Ok) { + return StatusOr>::Err(status_from_et_error( + err, + ("Failed to load ExecuTorch program '" + path + "'").c_str(), + pal.take(), + ErrorKind::Load)); + } + + return StatusOr>::Ok(std::move(core)); + } catch (const std::bad_alloc&) { + return StatusOr>::Err( + Status::Make(ErrorKind::Memory, "out of memory loading module")); + } catch (const std::exception& ex) { + return StatusOr>::Err( + Status::Make(ErrorKind::Load, ex.what(), 0, pal.take())); + } catch (...) { + return StatusOr>::Err( + Status::Make(ErrorKind::Load, "unknown error loading module", 0, pal.take())); + } +} + +StatusOr> ModuleCore::open_bytes( + std::vector bytes) noexcept { + init_runtime_once(); + PalLogScope pal; + try { + if (bytes.empty()) { + return StatusOr>::Err(Status::Make( + ErrorKind::Load, "Cannot load ExecuTorch program from empty bytes")); + } + std::unique_ptr core(new ModuleCore()); + core->source_label_ = ""; + core->estimated_bytes_ = bytes.size(); + core->owned_bytes_ = std::move(bytes); + + auto loader = std::make_unique( + core->owned_bytes_.data(), core->owned_bytes_.size()); + core->module_ = std::make_unique( + std::move(loader)); + + auto err = core->module_->load( + executorch::runtime::Program::Verification::Minimal); + if (err != executorch::runtime::Error::Ok) { + return StatusOr>::Err(status_from_et_error( + err, + "Failed to load ExecuTorch program from bytes", + pal.take(), + ErrorKind::Load)); + } + return StatusOr>::Ok(std::move(core)); + } catch (const std::bad_alloc&) { + return StatusOr>::Err( + Status::Make(ErrorKind::Memory, "out of memory loading module from bytes")); + } catch (const std::exception& ex) { + return StatusOr>::Err( + Status::Make(ErrorKind::Load, ex.what(), 0, pal.take())); + } catch (...) { + return StatusOr>::Err( + Status::Make(ErrorKind::Load, "unknown error loading bytes", 0, pal.take())); + } +} + +void ModuleCore::close() noexcept { + std::unique_lock lock(lifecycle_mu_); + if (closed_) { + return; + } + closed_ = true; + // Destroy module BEFORE clearing owned_bytes_ (BufferDataLoader borrows it). + module_.reset(); + owned_bytes_.clear(); + owned_bytes_.shrink_to_fit(); + estimated_bytes_ = 0; +} + +bool ModuleCore::is_closed() const noexcept { + std::shared_lock lock(lifecycle_mu_); + return closed_; +} + +std::string ModuleCore::source_label() const noexcept { + std::shared_lock lock(lifecycle_mu_); + return source_label_; +} + +size_t ModuleCore::estimated_memory_bytes() const noexcept { + std::shared_lock lock(lifecycle_mu_); + return estimated_bytes_; +} + +std::mutex& ModuleCore::mutex_for_method(const std::string& name) { + std::lock_guard g(method_mutexes_mu_); + auto& ptr = method_mutexes_[name]; + if (!ptr) { + ptr = std::make_unique(); + } + return *ptr; +} + +StatusOr> ModuleCore::method_names() noexcept { + std::shared_lock lock(lifecycle_mu_); + if (closed_ || !module_) { + return StatusOr>::Err( + Status::Make(ErrorKind::Closed, "ExecuTorch module is closed")); + } + PalLogScope pal; + try { + auto res = module_->method_names(); + if (!res.ok()) { + return StatusOr>::Err(status_from_et_error( + res.error(), "Failed to list method names", pal.take())); + } + std::vector names(res->begin(), res->end()); + std::sort(names.begin(), names.end()); + return StatusOr>::Ok(std::move(names)); + } catch (const std::bad_alloc&) { + return StatusOr>::Err( + Status::Make(ErrorKind::Memory, "out of memory listing methods")); + } catch (...) { + return StatusOr>::Err( + Status::Make(ErrorKind::Execution, "unexpected error listing methods")); + } +} + +StatusOr ModuleCore::method_meta( + const std::string& name) noexcept { + std::shared_lock lock(lifecycle_mu_); + if (closed_ || !module_) { + return StatusOr::Err( + Status::Make(ErrorKind::Closed, "ExecuTorch module is closed")); + } + PalLogScope pal; + try { + auto res = module_->method_meta(name); + if (!res.ok()) { + return StatusOr::Err(status_from_et_error( + res.error(), + ("Failed to read metadata for method '" + name + "'").c_str(), + pal.take(), + ErrorKind::MethodNotFound)); + } + const auto& meta = res.get(); + MethodMetaSnapshot snap; + snap.name = meta.name() ? meta.name() : name; + + const size_t n_in = meta.num_inputs(); + snap.inputs.reserve(n_in); + for (size_t i = 0; i < n_in; ++i) { + ValueMetaSnapshot vm; + auto tag_res = meta.input_tag(i); + if (tag_res.ok()) { + vm.tag = tag_res.get(); + if (vm.tag == executorch::runtime::Tag::Tensor) { + auto tm_res = meta.input_tensor_meta(i); + if (tm_res.ok()) { + const auto& tm = tm_res.get(); + vm.tensor.name = std::string(tm.name()); + vm.tensor.dtype = tm.scalar_type(); + vm.tensor.sizes.assign(tm.sizes().begin(), tm.sizes().end()); + vm.tensor.dim_order.assign( + tm.dim_order().begin(), tm.dim_order().end()); + vm.tensor.nbytes = tm.nbytes(); + vm.tensor.memory_planned = tm.is_memory_planned(); + } + } + } + snap.inputs.push_back(std::move(vm)); + } + + const size_t n_out = meta.num_outputs(); + snap.outputs.reserve(n_out); + for (size_t i = 0; i < n_out; ++i) { + ValueMetaSnapshot vm; + auto tag_res = meta.output_tag(i); + if (tag_res.ok()) { + vm.tag = tag_res.get(); + if (vm.tag == executorch::runtime::Tag::Tensor) { + auto tm_res = meta.output_tensor_meta(i); + if (tm_res.ok()) { + const auto& tm = tm_res.get(); + vm.tensor.name = std::string(tm.name()); + vm.tensor.dtype = tm.scalar_type(); + vm.tensor.sizes.assign(tm.sizes().begin(), tm.sizes().end()); + vm.tensor.dim_order.assign( + tm.dim_order().begin(), tm.dim_order().end()); + vm.tensor.nbytes = tm.nbytes(); + vm.tensor.memory_planned = tm.is_memory_planned(); + } + } + } + snap.outputs.push_back(std::move(vm)); + } + + const size_t n_backends = meta.num_backends(); + snap.backends.reserve(n_backends); + for (size_t i = 0; i < n_backends; ++i) { + auto b_res = meta.get_backend_name(i); + if (b_res.ok() && b_res.get() != nullptr) { + snap.backends.emplace_back(b_res.get()); + } + } + + const size_t n_bufs = meta.num_memory_planned_buffers(); + snap.planned_buffer_sizes.reserve(n_bufs); + int64_t total = 0; + for (size_t i = 0; i < n_bufs; ++i) { + auto sz_res = meta.memory_planned_buffer_size(i); + if (sz_res.ok()) { + snap.planned_buffer_sizes.push_back(sz_res.get()); + if (sz_res.get() > 0) { + total += sz_res.get(); + } + } + } + snap.planned_memory_bytes = total; + + return StatusOr::Ok(std::move(snap)); + } catch (const std::bad_alloc&) { + return StatusOr::Err( + Status::Make(ErrorKind::Memory, "out of memory reading method_meta")); + } catch (...) { + return StatusOr::Err( + Status::Make(ErrorKind::Execution, "unexpected error reading method_meta")); + } +} + +Status ModuleCore::load_method(const std::string& name) noexcept { + std::shared_lock lock(lifecycle_mu_); + if (closed_ || !module_) { + return Status::Make(ErrorKind::Closed, "ExecuTorch module is closed"); + } + PalLogScope pal; + try { + // Module::methods_ map is mutated on load_method, so serialize on method_mutexes_mu_ + // while checking/loading the method. + std::mutex& m_mu = mutex_for_method(name); + std::lock_guard mg(m_mu); + auto err = module_->load_method(name); + if (err != executorch::runtime::Error::Ok) { + return status_from_et_error( + err, + ("Failed to load method '" + name + "'").c_str(), + pal.take(), + ErrorKind::MethodNotFound); + } + return Status::Ok(); + } catch (const std::bad_alloc&) { + return Status::Make(ErrorKind::Memory, "out of memory loading method"); + } catch (const std::exception& ex) { + return Status::Make(ErrorKind::Execution, ex.what(), 0, pal.take()); + } catch (...) { + return Status::Make( + ErrorKind::Execution, "unknown error loading method", 0, pal.take()); + } +} + +StatusOr ModuleCore::unload_method(const std::string& name) noexcept { + // Unique lock ensures no concurrent execute() is running on any method + // while Module::methods_ hash map is modified. + std::unique_lock lock(lifecycle_mu_); + if (closed_ || !module_) { + return StatusOr::Err( + Status::Make(ErrorKind::Closed, "ExecuTorch module is closed")); + } + try { + return StatusOr::Ok(module_->unload_method(name)); + } catch (...) { + return StatusOr::Err( + Status::Make(ErrorKind::Execution, "failed unloading method")); + } +} + +bool ModuleCore::is_method_loaded(const std::string& name) noexcept { + std::shared_lock lock(lifecycle_mu_); + if (closed_ || !module_) { + return false; + } + try { + std::mutex& m_mu = mutex_for_method(name); + std::lock_guard mg(m_mu); + return module_->is_method_loaded(name); + } catch (...) { + return false; + } +} + +StatusOr> ModuleCore::execute( + const std::string& method_name, + const std::vector& inputs, + const std::vector& out_targets) noexcept { + std::shared_lock lock(lifecycle_mu_); + if (closed_ || !module_) { + return StatusOr>::Err( + Status::Make(ErrorKind::Closed, "ExecuTorch module is closed")); + } + PalLogScope pal; + try { + // Ensure method is loaded under an exclusive check if not already loaded, + // because Module::methods_ (std::unordered_map) is mutated on first load. + { + std::mutex& m_mu = mutex_for_method(method_name); + std::lock_guard mg(m_mu); + if (!module_->is_method_loaded(method_name)) { + lock.unlock(); + { + std::unique_lock ulock(lifecycle_mu_); + if (closed_ || !module_) { + return StatusOr>::Err( + Status::Make(ErrorKind::Closed, "ExecuTorch module is closed")); + } + if (!module_->is_method_loaded(method_name)) { + auto load_err = module_->load_method(method_name); + if (load_err != executorch::runtime::Error::Ok) { + return StatusOr>::Err(status_from_et_error( + load_err, + ("Failed to load method '" + method_name + "'").c_str(), + pal.take(), + ErrorKind::MethodNotFound)); + } + } + } + lock.lock(); + if (closed_ || !module_) { + return StatusOr>::Err( + Status::Make(ErrorKind::Closed, "ExecuTorch module is closed")); + } + } + } + + // Per-method lock: ExecuTorch Method owns a single mutable planned arena. + std::mutex& m_mu = mutex_for_method(method_name); + std::lock_guard mg(m_mu); + + // Backing containers (std::deque guarantees pointer stability on push_back). + std::deque> str_refs; + std::deque> dbl_list_refs; + std::deque> bool_vecs; + std::deque> bool_bufs; + std::deque> bool_list_refs; + + std::vector evalues; + evalues.reserve(inputs.size()); + + for (size_t i = 0; i < inputs.size(); ++i) { + const auto& in = inputs[i]; + switch (in.kind) { + case ValueKind::None: + evalues.emplace_back(); + break; + case ValueKind::Int: + evalues.emplace_back(in.int_val); + break; + case ValueKind::Double: + evalues.emplace_back(in.double_val); + break; + case ValueKind::Bool: + evalues.emplace_back(in.bool_val); + break; + case ValueKind::String: { + str_refs.emplace_back(in.string_val.data(), in.string_val.size()); + evalues.emplace_back(&str_refs.back()); + break; + } + case ValueKind::Tensor: { + if (!in.tensor_val) { + return StatusOr>::Err(Status::Make( + ErrorKind::Closed, + "Input tensor " + std::to_string(i) + " is closed")); + } + evalues.emplace_back(*in.tensor_val); + break; + } + case ValueKind::DoubleList: { + dbl_list_refs.emplace_back(in.double_list.data(), in.double_list.size()); + evalues.emplace_back(&dbl_list_refs.back()); + break; + } + case ValueKind::BoolList: { + auto arr = std::make_unique(in.bool_list.size()); + for (size_t j = 0; j < in.bool_list.size(); ++j) { + arr[j] = in.bool_list[j]; + } + bool_list_refs.emplace_back(arr.get(), in.bool_list.size()); + bool_bufs.push_back(std::move(arr)); + evalues.emplace_back(&bool_list_refs.back()); + break; + } + default: + return StatusOr>::Err(Status::Make( + ErrorKind::Type, + "Unsupported input EValue kind at index " + std::to_string(i))); + } + } + + auto res = module_->execute(method_name, evalues); + if (!res.ok()) { + return StatusOr>::Err(status_from_et_error( + res.error(), + ("Execution of method '" + method_name + "' failed").c_str(), + pal.take(), + ErrorKind::Execution)); + } + + const auto& raw_outputs = res.get(); + if (!out_targets.empty() && out_targets.size() != raw_outputs.size()) { + return StatusOr>::Err(Status::Make( + ErrorKind::Shape, + "out: expected " + std::to_string(raw_outputs.size()) + + " output tensor(s), got " + std::to_string(out_targets.size()))); + } + + std::vector outputs; + outputs.reserve(raw_outputs.size()); + + for (size_t i = 0; i < raw_outputs.size(); ++i) { + const auto& ev = raw_outputs[i]; + if (ev.isTensor()) { + const auto& src = ev.toTensor(); + if (!out_targets.empty()) { + const auto& dst = out_targets[i]; + if (!dst) { + return StatusOr>::Err(Status::Make( + ErrorKind::Closed, + "out: tensor " + std::to_string(i) + " is closed")); + } + if (dst->scalar_type() != src.scalar_type()) { + return StatusOr>::Err(Status::Make( + ErrorKind::DType, + std::string("out: dtype mismatch at output ") + + std::to_string(i) + ": expected " + + scalar_type_name(src.scalar_type()) + ", got " + + scalar_type_name(dst->scalar_type()))); + } + bool same_shape = (dst->dim() == src.dim()); + if (same_shape) { + for (ssize_t d = 0; d < src.dim(); ++d) { + if (dst->size(d) != src.size(d)) { + same_shape = false; + break; + } + } + } + if (!same_shape) { + return StatusOr>::Err(Status::Make( + ErrorKind::Shape, + "out: shape mismatch at output " + std::to_string(i))); + } + auto cp = copy_to_contiguous_bytes( + src, dst->mutable_data_ptr(), dst->nbytes()); + if (!cp.ok()) { + return StatusOr>::Err(std::move(cp)); + } + outputs.push_back(CoreValue::Tensor(dst)); + } else { + auto cloned = clone_contiguous_tensor_ptr(src); + if (!cloned.ok()) { + return StatusOr>::Err( + std::move(cloned.status)); + } + outputs.push_back(CoreValue::Tensor(std::move(cloned.value))); + } + } else if (!out_targets.empty()) { + return StatusOr>::Err(Status::Make( + ErrorKind::Type, + "out: target provided for non-tensor output " + std::to_string(i))); + } else if (ev.isInt()) { + outputs.push_back(CoreValue::Int(ev.toInt())); + } else if (ev.isDouble()) { + outputs.push_back(CoreValue::Double(ev.toDouble())); + } else if (ev.isBool()) { + outputs.push_back(CoreValue::Bool(ev.toBool())); + } else if (ev.isNone()) { + outputs.push_back(CoreValue::None()); + } else if (ev.isString()) { + auto sv = ev.tryToString(); + if (!sv.ok()) { + return StatusOr>::Err(status_from_et_error( + sv.error(), "Failed to extract String output", pal.take())); + } + outputs.push_back(CoreValue::String(std::string(sv.get()))); + } else if (ev.isIntList()) { + auto lr = ev.tryToIntList(); + if (!lr.ok()) { + return StatusOr>::Err(status_from_et_error( + lr.error(), "Failed to extract IntList output", pal.take())); + } + CoreValue cv; + cv.kind = ValueKind::IntList; + cv.int_list.assign(lr.get().begin(), lr.get().end()); + outputs.push_back(std::move(cv)); + } else if (ev.isDoubleList()) { + auto lr = ev.tryToDoubleList(); + if (!lr.ok()) { + return StatusOr>::Err(status_from_et_error( + lr.error(), "Failed to extract DoubleList output", pal.take())); + } + CoreValue cv; + cv.kind = ValueKind::DoubleList; + cv.double_list.assign(lr.get().begin(), lr.get().end()); + outputs.push_back(std::move(cv)); + } else if (ev.isBoolList()) { + auto lr = ev.tryToBoolList(); + if (!lr.ok()) { + return StatusOr>::Err(status_from_et_error( + lr.error(), "Failed to extract BoolList output", pal.take())); + } + CoreValue cv; + cv.kind = ValueKind::BoolList; + cv.bool_list.assign(lr.get().begin(), lr.get().end()); + outputs.push_back(std::move(cv)); + } else if (ev.isTensorList()) { + auto lr = ev.tryToTensorList(); + if (!lr.ok()) { + return StatusOr>::Err(status_from_et_error( + lr.error(), "Failed to extract TensorList output", pal.take())); + } + CoreValue cv; + cv.kind = ValueKind::TensorList; + for (const auto& t : lr.get()) { + auto cl = clone_contiguous_tensor_ptr(t); + if (!cl.ok()) { + return StatusOr>::Err(std::move(cl.status)); + } + cv.tensor_list.push_back(std::move(cl.value)); + } + outputs.push_back(std::move(cv)); + } else { + return StatusOr>::Err(Status::Make( + ErrorKind::Type, + "Unsupported output EValue tag at output " + std::to_string(i))); + } + } + + return StatusOr>::Ok(std::move(outputs)); + } catch (const std::bad_alloc&) { + return StatusOr>::Err( + Status::Make(ErrorKind::Memory, "out of memory executing method")); + } catch (const std::exception& ex) { + return StatusOr>::Err( + Status::Make(ErrorKind::Execution, ex.what(), 0, pal.take())); + } catch (...) { + return StatusOr>::Err( + Status::Make(ErrorKind::Execution, "unknown error executing method", 0, pal.take())); + } +} + +// --------------------------------------------------------------------------- +// Runtime introspection & threadpool controls +// --------------------------------------------------------------------------- + +std::vector registered_backends() noexcept { + init_runtime_once(); + std::vector out; + try { + const size_t n = executorch::runtime::get_num_registered_backends(); + out.reserve(n); + for (size_t i = 0; i < n; ++i) { + auto res = executorch::runtime::get_backend_name(i); + if (res.ok() && res.get() != nullptr) { + out.emplace_back(res.get()); + } + } + std::sort(out.begin(), out.end()); + } catch (...) { + } + return out; +} + +size_t registered_kernel_count() noexcept { + init_runtime_once(); + return executorch::runtime::get_registered_kernels().size(); +} + +int64_t get_num_threads() noexcept { + init_runtime_once(); +#ifdef ET_USE_THREADPOOL + std::lock_guard g(g_threadpool_mu); + auto* tp = executorch::extension::threadpool::get_threadpool(); + if (tp != nullptr) { + return static_cast(tp->get_thread_count()); + } +#endif + return executorch::extension::get_thread_count(); +} + +Status set_num_threads(int64_t n) noexcept { + init_runtime_once(); + if (n < 1 || n > 1024) { + return Status::Make( + ErrorKind::Argument, + "num_threads must be between 1 and 1024, got " + std::to_string(n)); + } +#ifdef ET_USE_THREADPOOL + try { + std::lock_guard g(g_threadpool_mu); + auto* tp = executorch::extension::threadpool::get_threadpool(); + if (tp == nullptr) { + return Status::Make( + ErrorKind::Execution, "ExecuTorch threadpool is unavailable"); + } + tp->_unsafe_reset_threadpool(static_cast(n)); + return Status::Ok(); + } catch (...) { + return Status::Make( + ErrorKind::Execution, "failed resetting ExecuTorch threadpool"); + } +#else + return Status::Make( + ErrorKind::Execution, + "ExecuTorch was built without threadpool support (ET_USE_THREADPOOL)"); +#endif +} + +} // namespace etrb diff --git a/ext/executorch/core/dtype.hpp b/ext/executorch/core/dtype.hpp new file mode 100644 index 0000000..8c0b8a3 --- /dev/null +++ b/ext/executorch/core/dtype.hpp @@ -0,0 +1,157 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +namespace etrb { + +// Single source of truth for all Ruby-constructible / readable ExecuTorch dtypes. +// Tuple: (ScalarType enumerator, canonical Ruby name, C++ storage type, byte size) +#define ETRB_FORALL_DTYPES(_) \ + _(Float, "float32", float, 4) \ + _(Double, "float64", double, 8) \ + _(Half, "float16", executorch::runtime::etensor::Half, 2) \ + _(BFloat16, "bfloat16", executorch::runtime::etensor::BFloat16, 2) \ + _(Byte, "uint8", uint8_t, 1) \ + _(Char, "int8", int8_t, 1) \ + _(Short, "int16", int16_t, 2) \ + _(Int, "int32", int32_t, 4) \ + _(Long, "int64", int64_t, 8) \ + _(UInt16, "uint16", uint16_t, 2) \ + _(UInt32, "uint32", uint32_t, 4) \ + _(UInt64, "uint64", uint64_t, 8) \ + _(Bool, "bool", bool, 1) + +inline constexpr const char* scalar_type_name( + executorch::aten::ScalarType st) noexcept { + switch (st) { +#define CASE_NAME(et_enum, name, ctype, sz) \ + case executorch::aten::ScalarType::et_enum: \ + return name; + ETRB_FORALL_DTYPES(CASE_NAME) +#undef CASE_NAME + case executorch::aten::ScalarType::QInt8: + return "qint8"; + case executorch::aten::ScalarType::QUInt8: + return "quint8"; + case executorch::aten::ScalarType::QInt32: + return "qint32"; + case executorch::aten::ScalarType::ComplexHalf: + return "complex32"; + case executorch::aten::ScalarType::ComplexFloat: + return "complex64"; + case executorch::aten::ScalarType::ComplexDouble: + return "complex128"; + case executorch::aten::ScalarType::Float8_e5m2: + return "float8_e5m2"; + case executorch::aten::ScalarType::Float8_e4m3fn: + return "float8_e4m3fn"; + default: + return "unknown"; + } +} + +inline constexpr size_t scalar_type_size( + executorch::aten::ScalarType st) noexcept { + switch (st) { +#define CASE_SIZE(et_enum, name, ctype, sz) \ + case executorch::aten::ScalarType::et_enum: \ + return sz; + ETRB_FORALL_DTYPES(CASE_SIZE) +#undef CASE_SIZE + case executorch::aten::ScalarType::QInt8: + case executorch::aten::ScalarType::QUInt8: + case executorch::aten::ScalarType::Float8_e5m2: + case executorch::aten::ScalarType::Float8_e4m3fn: + return 1; + case executorch::aten::ScalarType::QInt32: + case executorch::aten::ScalarType::ComplexHalf: + return 4; + case executorch::aten::ScalarType::ComplexFloat: + return 8; + case executorch::aten::ScalarType::ComplexDouble: + return 16; + default: + return 0; + } +} + +inline constexpr bool is_supported_dtype( + executorch::aten::ScalarType st) noexcept { + switch (st) { +#define CASE_SUP(et_enum, name, ctype, sz) \ + case executorch::aten::ScalarType::et_enum: \ + return true; + ETRB_FORALL_DTYPES(CASE_SUP) +#undef CASE_SUP + default: + return false; + } +} + +// Parse canonical dtype names AND backward-compatible short aliases. +inline bool parse_dtype_name( + std::string_view name, + executorch::aten::ScalarType* out) noexcept { + if (name == "float32" || name == "float") { + *out = executorch::aten::ScalarType::Float; + return true; + } + if (name == "float64" || name == "double") { + *out = executorch::aten::ScalarType::Double; + return true; + } + if (name == "float16" || name == "half") { + *out = executorch::aten::ScalarType::Half; + return true; + } + if (name == "bfloat16" || name == "bf16") { + *out = executorch::aten::ScalarType::BFloat16; + return true; + } + if (name == "uint8" || name == "byte") { + *out = executorch::aten::ScalarType::Byte; + return true; + } + if (name == "int8" || name == "char") { + *out = executorch::aten::ScalarType::Char; + return true; + } + if (name == "int16" || name == "short") { + *out = executorch::aten::ScalarType::Short; + return true; + } + if (name == "int32" || name == "int") { + *out = executorch::aten::ScalarType::Int; + return true; + } + if (name == "int64" || name == "long") { + *out = executorch::aten::ScalarType::Long; + return true; + } + if (name == "uint16") { + *out = executorch::aten::ScalarType::UInt16; + return true; + } + if (name == "uint32") { + *out = executorch::aten::ScalarType::UInt32; + return true; + } + if (name == "uint64") { + *out = executorch::aten::ScalarType::UInt64; + return true; + } + if (name == "bool") { + *out = executorch::aten::ScalarType::Bool; + return true; + } + return false; +} + +} // namespace etrb diff --git a/ext/executorch/core/module_core.hpp b/ext/executorch/core/module_core.hpp new file mode 100644 index 0000000..a919e06 --- /dev/null +++ b/ext/executorch/core/module_core.hpp @@ -0,0 +1,165 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "status.hpp" + +namespace etrb { + +enum class ValueKind : uint8_t { + None = 0, + Int, + Double, + Bool, + String, + Tensor, + IntList, + DoubleList, + BoolList, + TensorList, +}; + +// Owned, Ruby-independent representation of an ExecuTorch EValue. +// Safe to pass across GVL boundaries without touching any Ruby VALUEs. +struct CoreValue { + ValueKind kind = ValueKind::None; + int64_t int_val = 0; + double double_val = 0.0; + bool bool_val = false; + std::string string_val; + executorch::extension::TensorPtr tensor_val; + std::vector int_list; + std::vector double_list; + std::vector bool_list; + std::vector tensor_list; + + static CoreValue None() noexcept { return CoreValue{}; } + static CoreValue Int(int64_t v) noexcept { + CoreValue c; + c.kind = ValueKind::Int; + c.int_val = v; + return c; + } + static CoreValue Double(double v) noexcept { + CoreValue c; + c.kind = ValueKind::Double; + c.double_val = v; + return c; + } + static CoreValue Bool(bool v) noexcept { + CoreValue c; + c.kind = ValueKind::Bool; + c.bool_val = v; + return c; + } + static CoreValue String(std::string v) noexcept { + CoreValue c; + c.kind = ValueKind::String; + c.string_val = std::move(v); + return c; + } + static CoreValue Tensor(executorch::extension::TensorPtr ptr) noexcept { + CoreValue c; + c.kind = ValueKind::Tensor; + c.tensor_val = std::move(ptr); + return c; + } +}; + +struct TensorMetaSnapshot { + std::string name; + executorch::aten::ScalarType dtype = executorch::aten::ScalarType::Undefined; + std::vector sizes; + std::vector dim_order; + size_t nbytes = 0; + bool memory_planned = false; +}; + +struct ValueMetaSnapshot { + executorch::runtime::Tag tag = executorch::runtime::Tag::None; + TensorMetaSnapshot tensor; // Valid when tag == Tag::Tensor +}; + +struct MethodMetaSnapshot { + std::string name; + std::vector inputs; + std::vector outputs; + std::vector backends; + std::vector planned_buffer_sizes; + int64_t planned_memory_bytes = 0; +}; + +class ModuleCore { + public: + using LoadMode = executorch::extension::Module::LoadMode; + + ~ModuleCore() noexcept = default; + + ModuleCore(const ModuleCore&) = delete; + ModuleCore& operator=(const ModuleCore&) = delete; + + static StatusOr> open_file( + const std::string& path, + const std::vector& data_files, + LoadMode load_mode) noexcept; + + static StatusOr> open_bytes( + std::vector bytes) noexcept; + + // Deterministic resource release. Waits for in-flight calls via unique lock. + void close() noexcept; + bool is_closed() const noexcept; + + std::string source_label() const noexcept; + size_t estimated_memory_bytes() const noexcept; + + StatusOr> method_names() noexcept; + StatusOr method_meta(const std::string& name) noexcept; + Status load_method(const std::string& name) noexcept; + StatusOr unload_method(const std::string& name) noexcept; + bool is_method_loaded(const std::string& name) noexcept; + + // Thread-safe execution (per-method mutex under shared lifecycle lock). + // If `out_targets` is non-empty, writes tensor outputs directly into the + // caller-provided pre-allocated output tensors (validating count, shape, + // dtype, and contiguity) instead of allocating new output tensors. + StatusOr> execute( + const std::string& method_name, + const std::vector& inputs, + const std::vector& out_targets) noexcept; + + private: + ModuleCore() = default; + + std::mutex& mutex_for_method(const std::string& name); + + mutable std::shared_mutex lifecycle_mu_; + bool closed_ = false; + std::string source_label_; + size_t estimated_bytes_ = 0; + // Owned backing bytes when loaded via open_bytes (must outlive module_). + std::vector owned_bytes_; + std::unique_ptr module_; + + std::mutex method_mutexes_mu_; + std::unordered_map> method_mutexes_; +}; + +// Runtime introspection & threadpool controls +std::vector registered_backends() noexcept; +size_t registered_kernel_count() noexcept; +int64_t get_num_threads() noexcept; +Status set_num_threads(int64_t n) noexcept; + +} // namespace etrb diff --git a/ext/executorch/core/status.hpp b/ext/executorch/core/status.hpp new file mode 100644 index 0000000..4a70235 --- /dev/null +++ b/ext/executorch/core/status.hpp @@ -0,0 +1,100 @@ +#pragma once + +#include +#include +#include + +#include + +namespace etrb { + +enum class ErrorKind : uint8_t { + Ok = 0, + Load, + MethodNotFound, + OperatorMissing, + Delegate, + Shape, + DType, + Execution, + Memory, + Closed, + Argument, + Type, + Range, +}; + +struct Status { + ErrorKind kind = ErrorKind::Ok; + uint32_t et_code = 0; + std::string message; + std::string pal_log; + + bool ok() const noexcept { return kind == ErrorKind::Ok; } + + static Status Ok() noexcept { return Status{}; } + + static Status Make( + ErrorKind k, + std::string msg, + uint32_t code = 0, + std::string log = {}) noexcept { + Status s; + s.kind = k; + s.et_code = code; + s.message = std::move(msg); + s.pal_log = std::move(log); + return s; + } +}; + +template +struct StatusOr { + Status status; + T value{}; + + bool ok() const noexcept { return status.ok(); } + + static StatusOr Ok(T v) noexcept { + StatusOr out; + out.status = Status::Ok(); + out.value = std::move(v); + return out; + } + + static StatusOr Err(Status s) noexcept { + StatusOr out; + out.status = std::move(s); + return out; + } +}; + +// Initialize ExecuTorch runtime and register thread-local PAL log capture once. +void init_runtime_once() noexcept; + +// Scoped thread-local PAL log collector. Captures Error/Fatal PAL messages +// emitted on the current thread during an ExecuTorch call so they can be +// attached to Ruby exceptions. +class PalLogScope { + public: + PalLogScope() noexcept; + ~PalLogScope() noexcept; + + PalLogScope(const PalLogScope&) = delete; + PalLogScope& operator=(const PalLogScope&) = delete; + + std::string take() noexcept; + + private: + std::string* prev_buf_ = nullptr; + std::string buf_; +}; + +// Map an ExecuTorch runtime::Error + context + captured PAL log to Status. +Status status_from_et_error( + executorch::runtime::Error err, + const char* context, + std::string pal_log = {}, + ErrorKind default_kind = ErrorKind::Execution) noexcept; + +} // namespace etrb diff --git a/ext/executorch/core/tensor_core.hpp b/ext/executorch/core/tensor_core.hpp new file mode 100644 index 0000000..bb7c513 --- /dev/null +++ b/ext/executorch/core/tensor_core.hpp @@ -0,0 +1,73 @@ +#pragma once + +#include +#include +#include +#include + +#include + +#include "dtype.hpp" +#include "status.hpp" + +namespace etrb { + +struct ShapeInfo { + std::vector sizes; + size_t numel = 0; + size_t nbytes = 0; +}; + +// Overflow-safe validation of shape dims (0 <= d <= INT32_MAX), numel, and nbytes. +StatusOr validate_shape( + const std::vector& raw_dims, + executorch::aten::ScalarType dtype) noexcept; + +// Allocate raw uninitialized byte storage (no redundant zero-fill before memcpy) +// aligned to at least 64 bytes for SIMD/XNNPACK friendliness. +struct AlignedBuffer { + void* ptr = nullptr; + size_t nbytes = 0; + + AlignedBuffer() = default; + ~AlignedBuffer() noexcept; + + AlignedBuffer(const AlignedBuffer&) = delete; + AlignedBuffer& operator=(const AlignedBuffer&) = delete; + AlignedBuffer(AlignedBuffer&& other) noexcept; + AlignedBuffer& operator=(AlignedBuffer&& other) noexcept; + + static StatusOr allocate(size_t nbytes) noexcept; + static StatusOr allocate_zeroed(size_t nbytes) noexcept; +}; + +// Check whether an ExecuTorch tensor is laid out in standard C-contiguous +// row-major order (matching logical shape without transposition/gaps). +bool is_standard_contiguous(const executorch::aten::Tensor& tensor) noexcept; + +// Copy any ExecuTorch tensor (including non-contiguous / NHWC dim_order tensors) +// into a flat C-contiguous byte buffer of size `tensor.numel() * element_size`. +Status copy_to_contiguous_bytes( + const executorch::aten::Tensor& tensor, + void* dst, + size_t dst_nbytes) noexcept; + +// Clone an ExecuTorch tensor into an owned, C-contiguous TensorPtr. +StatusOr clone_contiguous_tensor_ptr( + const executorch::aten::Tensor& tensor) noexcept; + +// Build an owned C-contiguous TensorPtr taking ownership of `buf`. +StatusOr make_owned_tensor_ptr( + std::vector sizes, + executorch::aten::ScalarType dtype, + AlignedBuffer buf) noexcept; + +// Build an unowned view TensorPtr pointing into external memory (e.g. a pinned +// Ruby IO::Buffer). Caller guarantees `data` remains valid while the TensorPtr +// is used. +StatusOr make_borrowed_tensor_ptr( + std::vector sizes, + executorch::aten::ScalarType dtype, + void* data) noexcept; + +} // namespace etrb diff --git a/ext/executorch/executorch.cpp b/ext/executorch/executorch.cpp deleted file mode 100644 index f926110..0000000 --- a/ext/executorch/executorch.cpp +++ /dev/null @@ -1,582 +0,0 @@ -/** - * ExecuTorch Ruby Bindings - * - * This file provides Ruby bindings for Meta's ExecuTorch library using the Rice gem. - * It wraps the high-level Module API for loading and executing PyTorch models. - */ - -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include - -#include "utils.h" - -using namespace Rice; -using namespace executorch::runtime; -using namespace executorch::extension; -namespace et = executorch; - -// Forward declarations -class RubyTensor; -class RubyEValue; - -/** - * Ruby wrapper for executorch::aten::Tensor via TensorPtr - * - * This class manages tensor data and provides methods for creating tensors - * from Ruby arrays and extracting data back to Ruby. - */ -class RubyTensor { -public: - // Create a tensor from Ruby data array and shape - static RubyTensor create(Array data, Array shape, Symbol dtype) { - HANDLE_ET_ERRORS - - // Convert shape to vector using the proper SizesType - std::vector sizes; - for (size_t i = 0; i < shape.size(); i++) { - sizes.push_back(static_cast( - detail::From_Ruby().convert(shape[i].value()))); - } - - // Get scalar type from symbol - et::aten::ScalarType scalar_type = executorch_ruby::symbol_to_scalar_type(dtype.value()); - - // Convert data based on dtype and create tensor using templated make_tensor_ptr - // The templated version takes ownership of the data vector and handles memory management - if (scalar_type == et::aten::ScalarType::Float) { - std::vector float_data; - float_data.reserve(data.size()); - for (size_t i = 0; i < data.size(); i++) { - float_data.push_back(static_cast(detail::From_Ruby().convert(data[i].value()))); - } - // Use templated make_tensor_ptr which manages data ownership - TensorPtr tensor_ptr = make_tensor_ptr( - std::move(sizes), - std::move(float_data) - ); - return RubyTensor(std::move(tensor_ptr)); - } else if (scalar_type == et::aten::ScalarType::Double) { - std::vector double_data; - double_data.reserve(data.size()); - for (size_t i = 0; i < data.size(); i++) { - double_data.push_back(detail::From_Ruby().convert(data[i].value())); - } - TensorPtr tensor_ptr = make_tensor_ptr( - std::move(sizes), - std::move(double_data) - ); - return RubyTensor(std::move(tensor_ptr)); - } else if (scalar_type == et::aten::ScalarType::Long) { - std::vector int_data; - int_data.reserve(data.size()); - for (size_t i = 0; i < data.size(); i++) { - int_data.push_back(detail::From_Ruby().convert(data[i].value())); - } - TensorPtr tensor_ptr = make_tensor_ptr( - std::move(sizes), - std::move(int_data) - ); - return RubyTensor(std::move(tensor_ptr)); - } else if (scalar_type == et::aten::ScalarType::Int) { - std::vector int_data; - int_data.reserve(data.size()); - for (size_t i = 0; i < data.size(); i++) { - int_data.push_back(static_cast(detail::From_Ruby().convert(data[i].value()))); - } - TensorPtr tensor_ptr = make_tensor_ptr( - std::move(sizes), - std::move(int_data) - ); - return RubyTensor(std::move(tensor_ptr)); - } else { - rb_raise(rb_eArgError, "Unsupported dtype. Use :float, :double, :long, or :int"); - } - - // Should never reach here but compiler needs it - rb_raise(rb_eRuntimeError, "Unexpected code path in Tensor.create"); - END_HANDLE_ET_ERRORS - } - - // Create a float tensor (convenience method) - static RubyTensor from_array(Array data, Array shape) { - return create(data, shape, Symbol("float")); - } - - // Get shape as Ruby array - Array shape() const { - Array result; - for (int i = 0; i < tensor_ptr_->dim(); i++) { - result.push(tensor_ptr_->size(i)); - } - return result; - } - - // Get number of dimensions - int64_t dim() const { - return tensor_ptr_->dim(); - } - - // Get total number of elements - int64_t numel() const { - return tensor_ptr_->numel(); - } - - // Get dtype as symbol - Object dtype() const { - return Object(executorch_ruby::scalar_type_to_symbol(tensor_ptr_->scalar_type())); - } - - // Convert tensor data to Ruby array (flattened) - Array to_a() const { - Array result; - auto scalar_type = tensor_ptr_->scalar_type(); - - if (scalar_type == et::aten::ScalarType::Float) { - const float* data = tensor_ptr_->const_data_ptr(); - for (int64_t i = 0; i < tensor_ptr_->numel(); i++) { - result.push(data[i]); - } - } else if (scalar_type == et::aten::ScalarType::Double) { - const double* data = tensor_ptr_->const_data_ptr(); - for (int64_t i = 0; i < tensor_ptr_->numel(); i++) { - result.push(data[i]); - } - } else if (scalar_type == et::aten::ScalarType::Long) { - const int64_t* data = tensor_ptr_->const_data_ptr(); - for (int64_t i = 0; i < tensor_ptr_->numel(); i++) { - result.push(data[i]); - } - } else if (scalar_type == et::aten::ScalarType::Int) { - const int32_t* data = tensor_ptr_->const_data_ptr(); - for (int64_t i = 0; i < tensor_ptr_->numel(); i++) { - result.push(static_cast(data[i])); - } - } else { - rb_raise(rb_eRuntimeError, "Unsupported tensor dtype for to_a"); - } - - return result; - } - - // Get string representation - std::string to_s() const { - std::string result = "Tensor(shape=["; - for (int i = 0; i < tensor_ptr_->dim(); i++) { - if (i > 0) result += ", "; - result += std::to_string(tensor_ptr_->size(i)); - } - result += "], dtype="; - - auto scalar_type = tensor_ptr_->scalar_type(); - if (scalar_type == et::aten::ScalarType::Float) result += "float"; - else if (scalar_type == et::aten::ScalarType::Double) result += "double"; - else if (scalar_type == et::aten::ScalarType::Long) result += "long"; - else if (scalar_type == et::aten::ScalarType::Int) result += "int"; - else result += "unknown"; - - result += ")"; - return result; - } - - // Access the underlying tensor - et::aten::Tensor& get() { return *tensor_ptr_; } - const et::aten::Tensor& get() const { return *tensor_ptr_; } - - // Get the TensorPtr for ownership transfer - TensorPtr& get_ptr() { return tensor_ptr_; } - - // Create from existing TensorPtr (used internally) - explicit RubyTensor(TensorPtr ptr) : tensor_ptr_(std::move(ptr)) {} - - // Create from Tensor reference (clones the tensor) - static RubyTensor from_tensor(const et::aten::Tensor& tensor) { - return RubyTensor(clone_tensor_ptr(tensor)); - } - -private: - TensorPtr tensor_ptr_; -}; - -/** - * Ruby wrapper for executorch::runtime::EValue - * - * EValue is a tagged union that can hold different value types: - * - None - * - Int (int64_t) - * - Double - * - Bool - * - String - * - Tensor - * - Lists (IntList, DoubleList, BoolList, TensorList) - */ -class RubyEValue { -public: - // Create from different types - static RubyEValue from_none() { - return RubyEValue(EValue()); - } - - static RubyEValue from_int(int64_t value) { - return RubyEValue(EValue(value)); - } - - static RubyEValue from_double(double value) { - return RubyEValue(EValue(value)); - } - - static RubyEValue from_bool(bool value) { - return RubyEValue(EValue(value)); - } - - static RubyEValue from_tensor(RubyTensor& tensor) { - return RubyEValue(EValue(tensor.get()), tensor.get_ptr()); - } - - // Type checking - bool is_none() const { return evalue_.isNone(); } - bool is_int() const { return evalue_.isInt(); } - bool is_double() const { return evalue_.isDouble(); } - bool is_bool() const { return evalue_.isBool(); } - bool is_string() const { return evalue_.isString(); } - bool is_tensor() const { return evalue_.isTensor(); } - - // Value extraction - int64_t to_int() const { - if (!is_int()) { - rb_raise(rb_eTypeError, "EValue is not an Int"); - } - return evalue_.toInt(); - } - - double to_double() const { - if (!is_double()) { - rb_raise(rb_eTypeError, "EValue is not a Double"); - } - return evalue_.toDouble(); - } - - bool to_bool() const { - if (!is_bool()) { - rb_raise(rb_eTypeError, "EValue is not a Bool"); - } - return evalue_.toBool(); - } - - RubyTensor to_tensor() const { - if (!is_tensor()) { - rb_raise(rb_eTypeError, "EValue is not a Tensor"); - } - return RubyTensor::from_tensor(evalue_.toTensor()); - } - - // Convert to Ruby object based on type - Object to_ruby() const { - if (is_none()) { - return Object(Qnil); - } else if (is_int()) { - return Object(LONG2NUM(evalue_.toInt())); - } else if (is_double()) { - return Object(DBL2NUM(evalue_.toDouble())); - } else if (is_bool()) { - return Object(evalue_.toBool() ? Qtrue : Qfalse); - } else if (is_tensor()) { - // Return tensor info as hash - auto tensor = evalue_.toTensor(); - VALUE hash = rb_hash_new(); - rb_hash_aset(hash, ID2SYM(rb_intern("type")), rb_str_new_cstr("tensor")); - rb_hash_aset(hash, ID2SYM(rb_intern("dtype")), - executorch_ruby::scalar_type_to_symbol(tensor.scalar_type())); - - // Build shape array - VALUE shape = rb_ary_new(); - for (int i = 0; i < tensor.dim(); i++) { - rb_ary_push(shape, LONG2NUM(tensor.size(i))); - } - rb_hash_aset(hash, ID2SYM(rb_intern("shape")), shape); - - return Object(hash); - } else { - return Object(Qnil); - } - } - - // Get type name - std::string type_name() const { - if (is_none()) return "None"; - if (is_int()) return "Int"; - if (is_double()) return "Double"; - if (is_bool()) return "Bool"; - if (is_string()) return "String"; - if (is_tensor()) return "Tensor"; - return "Unknown"; - } - - // Access underlying EValue - const EValue& get() const { return evalue_; } - EValue& get() { return evalue_; } - - // For internal use - create from EValue with tensor ownership - explicit RubyEValue(EValue evalue, TensorPtr tensor_ptr = nullptr) - : evalue_(std::move(evalue)), tensor_ptr_(std::move(tensor_ptr)) {} - -private: - EValue evalue_; - TensorPtr tensor_ptr_; // Keep tensor alive if EValue references it -}; - -/** - * Ruby wrapper for executorch::extension::Module - * - * This class manages the lifecycle of an ExecuTorch model and provides - * methods for loading and executing inference. - */ -class RubyModel { -public: - RubyModel(const std::string& path) - : path_(path), module_(nullptr) { - HANDLE_ET_ERRORS - module_ = std::make_unique(path); - // Auto-load on construction - auto err = module_->load(); - executorch_ruby::check_error(err); - END_HANDLE_ET_ERRORS - } - - bool is_loaded() const { - return module_ && module_->is_loaded(); - } - - Array method_names() { - HANDLE_ET_ERRORS - if (!is_loaded()) { - rb_raise(rb_eRuntimeError, "Module not loaded"); - } - auto result = module_->method_names(); - auto names_set = executorch_ruby::unwrap_result(std::move(result)); - Array arr; - for (const auto& name : names_set) { - arr.push(String(name)); - } - return arr; - END_HANDLE_ET_ERRORS - } - - // Execute the forward method with tensor inputs - Array forward(Array inputs) { - HANDLE_ET_ERRORS - if (!is_loaded()) { - rb_raise(rb_eRuntimeError, "Module not loaded"); - } - - // Load forward method if not already loaded - if (!module_->is_method_loaded("forward")) { - auto load_err = module_->load_method("forward"); - if (load_err != executorch::runtime::Error::Ok) { - const char* load_error_name = "Unknown"; - switch (load_err) { - case executorch::runtime::Error::Ok: load_error_name = "Ok"; break; - case executorch::runtime::Error::Internal: load_error_name = "Internal"; break; - case executorch::runtime::Error::InvalidState: load_error_name = "InvalidState"; break; - case executorch::runtime::Error::InvalidArgument: load_error_name = "InvalidArgument"; break; - case executorch::runtime::Error::InvalidType: load_error_name = "InvalidType"; break; - case executorch::runtime::Error::NotFound: load_error_name = "NotFound"; break; - case executorch::runtime::Error::MemoryAllocationFailed: load_error_name = "MemoryAllocationFailed"; break; - case executorch::runtime::Error::AccessFailed: load_error_name = "AccessFailed"; break; - case executorch::runtime::Error::NotSupported: load_error_name = "NotSupported"; break; - default: load_error_name = "Unknown"; break; - } - rb_raise(rb_eRuntimeError, "Failed to load forward method: %s (%d)", load_error_name, static_cast(load_err)); - } - } - - // Convert Ruby inputs to EValues - // Keep tensors alive during forward execution - std::vector input_tensors; - std::vector input_evalues; - - for (size_t i = 0; i < inputs.size(); i++) { - Object input = inputs[i]; - - // Check if it's a RubyTensor - if (input.is_a(rb_cObject)) { - try { - RubyTensor& tensor = detail::From_Ruby().convert(input.value()); - // Clone the tensor to ensure we own the data during forward - TensorPtr cloned = clone_tensor_ptr(tensor.get()); - input_tensors.push_back(cloned); - input_evalues.push_back(EValue(*cloned)); - } catch (...) { - // Try as RubyEValue - try { - RubyEValue& evalue = detail::From_Ruby().convert(input.value()); - input_evalues.push_back(evalue.get()); - } catch (...) { - rb_raise(rb_eTypeError, "Input %zu must be a Tensor or EValue", i); - } - } - } - } - - // Execute forward - auto result = module_->forward(input_evalues); - if (!result.ok()) { - auto error = result.error(); - const char* error_name = "Unknown"; - switch (error) { - case executorch::runtime::Error::Ok: error_name = "Ok"; break; - case executorch::runtime::Error::Internal: error_name = "Internal"; break; - case executorch::runtime::Error::InvalidState: error_name = "InvalidState"; break; - case executorch::runtime::Error::InvalidArgument: error_name = "InvalidArgument"; break; - case executorch::runtime::Error::InvalidType: error_name = "InvalidType"; break; - case executorch::runtime::Error::NotFound: error_name = "NotFound"; break; - case executorch::runtime::Error::MemoryAllocationFailed: error_name = "MemoryAllocationFailed"; break; - case executorch::runtime::Error::AccessFailed: error_name = "AccessFailed"; break; - case executorch::runtime::Error::NotSupported: error_name = "NotSupported"; break; - default: error_name = "Unknown"; break; - } - rb_raise(rb_eRuntimeError, "Forward execution failed: %s (%d)", error_name, static_cast(error)); - } - auto outputs = std::move(result.get()); - - // Convert outputs to Ruby array of RubyTensors - Array ruby_outputs; - for (auto& output : outputs) { - if (output.isTensor()) { - // Clone the tensor to own the data - ruby_outputs.push(RubyTensor::from_tensor(output.toTensor())); - } else if (output.isInt()) { - ruby_outputs.push(output.toInt()); - } else if (output.isDouble()) { - ruby_outputs.push(output.toDouble()); - } else if (output.isBool()) { - ruby_outputs.push(output.toBool() ? Qtrue : Qfalse); - } else { - ruby_outputs.push(Qnil); - } - } - - return ruby_outputs; - END_HANDLE_ET_ERRORS - } - - // Execute a named method - Array execute(const std::string& method_name, Array inputs) { - HANDLE_ET_ERRORS - if (!is_loaded()) { - rb_raise(rb_eRuntimeError, "Module not loaded"); - } - - // Convert Ruby inputs to EValues - // Keep tensors alive during execution - std::vector input_tensors; - std::vector input_evalues; - for (size_t i = 0; i < inputs.size(); i++) { - Object input = inputs[i]; - - try { - RubyTensor& tensor = detail::From_Ruby().convert(input.value()); - // Clone the tensor to ensure we own the data during execution - TensorPtr cloned = clone_tensor_ptr(tensor.get()); - input_tensors.push_back(cloned); - input_evalues.push_back(EValue(*cloned)); - } catch (...) { - try { - RubyEValue& evalue = detail::From_Ruby().convert(input.value()); - input_evalues.push_back(evalue.get()); - } catch (...) { - rb_raise(rb_eTypeError, "Input %zu must be a Tensor or EValue", i); - } - } - } - - // Execute method - auto result = module_->execute(method_name, input_evalues); - auto outputs = executorch_ruby::unwrap_result(std::move(result)); - - // Convert outputs to Ruby - Array ruby_outputs; - for (auto& output : outputs) { - if (output.isTensor()) { - ruby_outputs.push(RubyTensor::from_tensor(output.toTensor())); - } else if (output.isInt()) { - ruby_outputs.push(output.toInt()); - } else if (output.isDouble()) { - ruby_outputs.push(output.toDouble()); - } else if (output.isBool()) { - ruby_outputs.push(output.toBool() ? Qtrue : Qfalse); - } else { - ruby_outputs.push(Qnil); - } - } - - return ruby_outputs; - END_HANDLE_ET_ERRORS - } - - // Get the file path - std::string path() const { - return path_; - } - - // Access the underlying module for advanced use - et::extension::Module* get_module() { - return module_.get(); - } - -private: - std::string path_; - std::unique_ptr module_; -}; - -/** - * Initialize the Executorch Ruby module - */ -extern "C" -void Init_executorch() { - Rice::Module m = define_module("Executorch"); - - // Define version constant - m.const_set("NATIVE_VERSION", String("0.1.0")); - - // Define error class - define_class_under(m, "NativeError") - .define_constructor(Constructor()); - - // Define Tensor class - define_class_under(m, "Tensor") - .define_singleton_function("create", &RubyTensor::create, - Arg("data"), Arg("shape"), Arg("dtype")) - .define_singleton_function("from_array", &RubyTensor::from_array, - Arg("data"), Arg("shape")) - .define_method("shape", &RubyTensor::shape) - .define_method("dim", &RubyTensor::dim) - .define_method("numel", &RubyTensor::numel) - .define_method("dtype", &RubyTensor::dtype) - .define_method("_original_to_a", &RubyTensor::to_a) - .define_method("to_s", &RubyTensor::to_s) - .define_method("inspect", &RubyTensor::to_s); - - // Define Model class - define_class_under(m, "Model") - .define_constructor(Constructor(), - Arg("path")) - .define_method("loaded?", &RubyModel::is_loaded) - .define_method("method_names", &RubyModel::method_names) - .define_method("path", &RubyModel::path) - .define_method("forward", &RubyModel::forward, - Arg("inputs")) - .define_method("execute", &RubyModel::execute, - Arg("method_name"), Arg("inputs")); - - // Note: EValue is kept internal - users interact with Tensor and native Ruby types -} diff --git a/ext/executorch/executorch.map b/ext/executorch/executorch.map new file mode 100644 index 0000000..d619372 --- /dev/null +++ b/ext/executorch/executorch.map @@ -0,0 +1,6 @@ +{ + global: + Init_executorch; + local: + *; +}; diff --git a/ext/executorch/extconf.rb b/ext/executorch/extconf.rb index 1369b01..4288ed3 100644 --- a/ext/executorch/extconf.rb +++ b/ext/executorch/extconf.rb @@ -1,208 +1,289 @@ -require 'mkmf-rice' - -$CXXFLAGS += ' -std=c++17' -$CXXFLAGS += ' -DC10_USING_CUSTOM_GENERATED_MACROS' -$CXXFLAGS += ' -Wno-deprecated-declarations' - -# ============================================================================== -# ExecuTorch Path Detection -# ============================================================================== -# -# 1. --with-executorch-dir flag (bundle config or gem install) -# 2. EXECUTORCH_DIR environment variable -# - -include_dirs = [] -lib_dirs = [] - -# Helper to add prefix paths -def add_prefix_paths(prefix, include_dirs, lib_dirs) - return false unless prefix && File.directory?(prefix) - - inc = File.join(prefix, 'include') - lib = File.join(prefix, 'lib') - - if File.directory?(inc) && File.directory?(lib) - include_dirs << inc - lib_dirs << lib - true - else - false +# frozen_string_literal: true + +require "fileutils" +require "mkmf" +require "rbconfig" +require "shellwords" +require_relative "../../lib/executorch/sdk" + +target_os = RbConfig::CONFIG["target_os"].to_s +is_darwin = target_os.match?(/darwin/i) +is_linux = target_os.match?(/linux/i) + +if target_os.match?(/mswin|mingw|cygwin/i) + abort "executorch-ruby does not support Windows native builds yet." +end + +# ---------------------------------------------------------------------------- +# 1. Locate ExecuTorch C++ SDK +# ---------------------------------------------------------------------------- + +def resolve_dir(raw) + return nil if raw.nil? || raw.empty? + + expanded = File.expand_path(raw) + return expanded if Executorch::SDK.valid_sdk?(expanded) + + # Bundler runs extconf.rb inside ext/executorch/; also resolve relative paths + # against the original invocation PWD if set. + if !Pathname.new(raw).absolute? && ENV["PWD"] + from_pwd = File.expand_path(raw, ENV["PWD"]) + return from_pwd if Executorch::SDK.valid_sdk?(from_pwd) end + + nil end -# Priority 1: --with-executorch-dir flag (standard Ruby gem pattern) -# Usage: bundle config set --local build.executorch --with-executorch-dir=/path/to/executorch -# or: gem install executorch -- --with-executorch-dir=/path/to/executorch -executorch_dir = arg_config('--with-executorch-dir') -if executorch_dir - if add_prefix_paths(executorch_dir, include_dirs, lib_dirs) - puts "Using --with-executorch-dir: #{executorch_dir}" - else - abort "Error: --with-executorch-dir path is invalid: #{executorch_dir}" +require "pathname" + +sdk_dir = nil + +if (arg = arg_config("--with-executorch-dir")) + sdk_dir = resolve_dir(arg) + unless sdk_dir + abort <<~ERR + Invalid --with-executorch-dir: #{arg} + Expected include/executorch/extension/module/module.h and lib/ inside that directory. + Tip: use an absolute path (Bundler runs extconf.rb inside ext/executorch/). + ERR end + puts "Using --with-executorch-dir: #{sdk_dir}" end -# Priority 2: Environment variable (for CI/scripting) -if include_dirs.empty? - executorch_prefix = ENV['EXECUTORCH_DIR'] - if add_prefix_paths(executorch_prefix, include_dirs, lib_dirs) - puts "Using EXECUTORCH_DIR: #{executorch_prefix}" +if sdk_dir.nil? && ENV["EXECUTORCH_DIR"] && !ENV["EXECUTORCH_DIR"].empty? + sdk_dir = resolve_dir(ENV["EXECUTORCH_DIR"]) + unless sdk_dir + abort "Invalid EXECUTORCH_DIR: #{ENV['EXECUTORCH_DIR']}" end + puts "Using EXECUTORCH_DIR: #{sdk_dir}" end -include_dirs.compact! -include_dirs.uniq! -lib_dirs.compact! -lib_dirs.uniq! +if sdk_dir.nil? + # Check cached official SDK first, then standard system prefixes. + candidates = [ + Executorch::SDK.default_cache_dir, + "/opt/homebrew", + "/usr/local", + ] + sdk_dir = candidates.find { |c| Executorch::SDK.valid_sdk?(c) } +end -if include_dirs.empty? || lib_dirs.empty? - abort <<~ERROR - ExecuTorch installation not found! +if sdk_dir.nil? && ENV["EXECUTORCH_NO_DOWNLOAD"] != "1" + sdk_dir = Executorch::SDK.ensure_sdk +end - Configure the path using one of these methods: +unless Executorch::SDK.valid_sdk?(sdk_dir) + abort <<~ERR + ExecuTorch C++ SDK not found! + Provide --with-executorch-dir=/abs/path/to/executorch or EXECUTORCH_DIR=/abs/path, + or unset EXECUTORCH_NO_DOWNLOAD to fetch the verified ExecuTorch #{Executorch::SDK::VERSION} SDK. + ERR +end + +include_dir = File.join(sdk_dir, "include") +lib_dir = File.join(sdk_dir, "lib") +c10_inc = File.join(include_dir, "executorch", "runtime", "core", "portable_type", "c10") + +# Read SDK version from executorch.pc if present, else fall back to .executorch-version. +sdk_version = Executorch::SDK::VERSION +pc_file = File.join(lib_dir, "pkgconfig", "executorch.pc") +pc_cflags = [] +if File.exist?(pc_file) + File.readlines(pc_file).each do |line| + if line =~ /^Version:\s*(\S+)/ + sdk_version = Regexp.last_match(1) + elsif line =~ /^Cflags:\s*(.+)/ + Regexp.last_match(1).split.each do |tok| + pc_cflags << tok if tok.start_with?("-D") + end + end + end +end + +puts "ExecuTorch SDK: #{sdk_dir} (version #{sdk_version})" - 1. Bundle config (recommended - set once per project): - bundle config set --local build.executorch --with-executorch-dir=/path/to/executorch +# ---------------------------------------------------------------------------- +# 2. Compiler & Symbol Visibility Flags +# ---------------------------------------------------------------------------- - 2. Environment variable (useful for CI): - EXECUTORCH_DIR=/path/to/executorch bundle install +$CXXFLAGS = "#{CONFIG['CXXFLAGS']} -std=c++17 -fvisibility=hidden -fvisibility-inlines-hidden" +$CXXFLAGS += " -Wall -Wextra -Wno-unused-parameter -Wno-deprecated-declarations" +$CXXFLAGS += " -DEXECUTORCH_RUBY_SDK_VERSION=\\\"#{sdk_version}\\\"" - Need to build ExecuTorch first? See: https://pytorch.org/executorch/ - ERROR +if pc_cflags.any? + pc_cflags.each { |flag| $CXXFLAGS += " #{flag}" } +else + $CXXFLAGS += " -DC10_USING_CUSTOM_GENERATED_MACROS" end -# Validate headers exist -include_dir = include_dirs.first -lib_dir = lib_dirs.first +if ENV["EXECUTORCH_SANITIZE"] == "1" + puts "Enabling AddressSanitizer + UndefinedBehaviorSanitizer" + $CXXFLAGS += " -fsanitize=address,undefined -fno-omit-frame-pointer -O1 -g" + $LDFLAGS += " -fsanitize=address,undefined" +end -unless File.exist?(File.join(include_dir, 'executorch', 'extension', 'module', 'module.h')) - abort <<~ERROR - ExecuTorch module.h header not found at: #{include_dir} - Make sure EXECUTORCH_BUILD_EXTENSION_MODULE=ON was set during build. - ERROR +$INCFLAGS = "-I#{Shellwords.escape(include_dir)} #{$INCFLAGS}" +if File.directory?(c10_inc) + $INCFLAGS = "-I#{Shellwords.escape(c10_inc)} #{$INCFLAGS}" end +$INCFLAGS = "-I#{Shellwords.escape(File.join(__dir__, 'core'))} #{$INCFLAGS}" -puts "Include directory: #{include_dir}" -puts "Library directory: #{lib_dir}" - -# Configure include paths -# Also add the portable c10 headers path for standalone builds -portable_c10_dir = File.join(include_dir, 'executorch', 'runtime', 'core', 'portable_type', 'c10') -$INCFLAGS = "-I#{include_dir} -I#{portable_c10_dir} #{$INCFLAGS}" - -# Configure library paths -$LDFLAGS += " -L#{lib_dir}" - -# Add rpath for runtime library loading -$LDFLAGS += if RUBY_PLATFORM =~ /darwin/ - " -Wl,-rpath,#{lib_dir}" - else - " -Wl,-rpath,#{lib_dir}" - end - -# ============================================================================== -# Library Linking Configuration -# ============================================================================== - -# Default libraries required for basic operation -DEFAULT_LIBS = %w[ - extension_module_static - extension_data_loader - extension_tensor - extension_named_data_map - extension_flat_tensor - extension_threadpool - executorch - executorch_core -].freeze - -# Determine which libraries to link -libs = if ENV['EXECUTORCH_LIBS'] - # User-specified library list (overrides defaults) - user_libs = ENV['EXECUTORCH_LIBS'].split(',').map(&:strip).reject(&:empty?) - puts "Using custom library list: #{user_libs.join(', ')}" - user_libs - else - DEFAULT_LIBS.dup - end - -# Link extension libraries first (order matters for static linking) -libs.each do |lib| - lib_file = File.join(lib_dir, "lib#{lib}.a") - if File.exist?(lib_file) - $LDFLAGS += " -l#{lib}" - puts " Linking: #{lib}" - else - # Try without _static suffix - alt_lib = lib.sub(/_static$/, '') - alt_file = File.join(lib_dir, "lib#{alt_lib}.a") - if File.exist?(alt_file) - $LDFLAGS += " -l#{alt_lib}" - puts " Linking: #{alt_lib} (alternative)" - elsif lib.include?('extension_') - # Extension libraries are optional - puts " Skipping optional: #{lib} (not found)" - else - # Core libraries should exist - abort "Required library not found: #{lib} (looked for #{lib_file})" +# ---------------------------------------------------------------------------- +# 3. Linking: Shared SDK (preferred) vs Static Source Build +# ---------------------------------------------------------------------------- + +dlext = is_darwin ? "dylib" : "so" +shared_runtime = File.join(lib_dir, "libexecutorch.#{dlext}") + +bundle_vendor = ENV["EXECUTORCH_BUNDLE_VENDOR"] == "1" +vendor_dir = File.expand_path("../../lib/executorch/vendor", __dir__) + +$LDFLAGS += " -L#{Shellwords.escape(lib_dir)}" + +if File.exist?(shared_runtime) + puts "Linking mode: shared ExecuTorch SDK (.#{dlext})" + + if bundle_vendor + FileUtils.mkdir_p(vendor_dir) + key = Executorch::SDK.platform_key + files = Executorch::SDK::VENDOR_LIBS[key] || Dir.glob(File.join(lib_dir, "libexecutorch*.#{dlext}")) + .map { |p| File.basename(p) } + files.each do |fname| + src = File.join(lib_dir, fname) + next unless File.exist?(src) + + FileUtils.cp(src, File.join(vendor_dir, fname)) + puts " Vendored: #{fname}" end end -end -# Check for portable kernels (if available) -# Use -force_load on macOS to include global constructors that register kernels -portable_ops_lib = File.join(lib_dir, 'libportable_ops_lib.a') -if File.exist?(portable_ops_lib) - $LDFLAGS += if RUBY_PLATFORM =~ /darwin/ - # macOS: -force_load pulls in all symbols including global constructors - " -Wl,-force_load,#{portable_ops_lib}" - else - # Linux: --whole-archive achieves the same effect - ' -Wl,--whole-archive -lportable_ops_lib -Wl,--no-whole-archive' - end - puts ' Linking: portable_ops_lib (force_load)' - - # Portable kernels - if File.exist?(File.join(lib_dir, 'libportable_kernels.a')) - $LDFLAGS += ' -lportable_kernels' - puts ' Linking: portable_kernels' + if is_darwin + if bundle_vendor + $LDFLAGS += " -Wl,-rpath,@loader_path/vendor -Wl,-rpath,@loader_path/../vendor" + else + $LDFLAGS += " -Wl,-rpath,#{Shellwords.escape(lib_dir)}" + end + elsif is_linux + if bundle_vendor + $LDFLAGS += " -Wl,--enable-new-dtags -Wl,-rpath,'$$ORIGIN/vendor' -Wl,-rpath,'$$ORIGIN/../vendor'" + else + $LDFLAGS += " -Wl,--enable-new-dtags -Wl,-rpath,#{Shellwords.escape(lib_dir)}" + end end -end -# CPU info and pthreadpool (often required) -%w[cpuinfo pthreadpool].each do |lib| - if File.exist?(File.join(lib_dir, "lib#{lib}.a")) - $LDFLAGS += " -l#{lib}" - puts " Linking: #{lib}" + # Core runtime + threadpool + $LOCAL_LIBS += " -lexecutorch" + if File.exist?(File.join(lib_dir, "libexecutorch_threadpool.#{dlext}")) + $LOCAL_LIBS += " -lexecutorch_threadpool" + $CXXFLAGS += " -DET_USE_THREADPOOL" unless $CXXFLAGS.include?("-DET_USE_THREADPOOL") end -end -# Extra libraries from environment (consolidated from version B) -if ENV['EXECUTORCH_EXTRA_LIBS'] - extra_libs = ENV['EXECUTORCH_EXTRA_LIBS'].split(',').map(&:strip).reject(&:empty?) - extra_libs.each do |lib| - if File.exist?(File.join(lib_dir, "lib#{lib}.a")) - $LDFLAGS += " -l#{lib}" - puts " Linking extra: #{lib}" + # Self-registering shared kernel & backend plugins: + # Must NOT be dropped by linker --as-needed / -dead_strip_dylibs! + plugin_libs = %w[ + executorch_kernels_optimized + executorch_kernels_quantized + executorch_kernels_torchao + executorch_backend_xnnpack + executorch_backend_coreml + executorch_backend_mlx + ].select { |name| File.exist?(File.join(lib_dir, "lib#{name}.#{dlext}")) } + + unless plugin_libs.empty? + puts " Plugins: #{plugin_libs.join(', ')}" + if is_linux + $LOCAL_LIBS += " -Wl,--no-as-needed" + plugin_libs.each { |lib| $LOCAL_LIBS += " -l#{lib}" } + $LOCAL_LIBS += " -Wl,--as-needed" + elsif is_darwin + plugin_libs.each { |lib| $LOCAL_LIBS += " -Wl,-needed-l#{lib}" } + end + end +else + # Fallback: static ExecuTorch source build (.a archives) + puts "Linking mode: static ExecuTorch archives (.a)" + + def force_load_flag(path, is_darwin) + escaped = Shellwords.escape(path) + if is_darwin + " -Wl,-force_load,#{escaped}" else - puts " Warning: extra library not found: #{lib}" + " -Wl,--whole-archive #{escaped} -Wl,--no-whole-archive" end end -end -# ============================================================================== -# Platform-Specific Configuration -# ============================================================================== + mandatory = %w[extension_module_static extension_data_loader extension_tensor executorch executorch_core] + mandatory.each do |lib| + path = File.join(lib_dir, "lib#{lib}.a") + alt = File.join(lib_dir, "lib#{lib.sub(/_static$/, '')}.a") + unless File.exist?(path) || File.exist?(alt) + abort "Required static library missing: #{lib} (checked #{path})" + end + end + + whole_libs = [] + # Prefer optimized_native_cpu_ops_lib over portable_ops_lib (mutually exclusive) + %w[optimized_native_cpu_ops_lib portable_ops_lib].each do |ops| + p = File.join(lib_dir, "lib#{ops}.a") + if File.exist?(p) + whole_libs << p + break + end + end + # Additional non-conflicting self-registering archives + %w[quantized_ops_lib xnnpack_backend coreml_backend mps_backend].each do |extra| + p = File.join(lib_dir, "lib#{extra}.a") + whole_libs << p if File.exist?(p) + end + + whole_libs.each do |p| + puts " Whole-archive: #{File.basename(p)}" + $LOCAL_LIBS += force_load_flag(p, is_darwin) + end + + # Static dependency archives (ordered & grouped on Linux so GNU ld resolves cycles cleanly) + static_deps = %w[ + extension_module_static extension_module + extension_data_loader extension_tensor extension_named_data_map + extension_flat_tensor extension_threadpool + optimized_kernels portable_kernels quantized_kernels cpublas eigen_blas + XNNPACK xnnpack-microkernels-prod microkernels-prod kleidiai + pthreadpool cpuinfo clog + executorch executorch_core + ].uniq.map { |l| File.join(lib_dir, "lib#{l}.a") }.select { |p| File.exist?(p) } + + $LOCAL_LIBS += " -Wl,--start-group" if is_linux + static_deps.each { |p| $LOCAL_LIBS += " #{Shellwords.escape(p)}" } + $LOCAL_LIBS += " -Wl,--end-group" if is_linux + + if is_darwin + $LOCAL_LIBS += " -framework Accelerate" + if File.exist?(File.join(lib_dir, "libcoreml_backend.a")) + $LOCAL_LIBS += " -framework CoreML -framework Foundation -lsqlite3" + end + end +end -if (RUBY_PLATFORM =~ /darwin/) && (RUBY_PLATFORM =~ /arm64/) - # Apple Silicon specific - puts 'Building for Apple Silicon (arm64)' +# Export ONLY Init_executorch so zero C++ / ExecuTorch symbols leak globally! +if is_linux + map_file = File.expand_path("executorch.map", __dir__) + $DLDFLAGS += " -Wl,--version-script=#{Shellwords.escape(map_file)} -Wl,--exclude-libs,ALL" + $LOCAL_LIBS += " -lpthread -lm -ldl" +elsif is_darwin + $DLDFLAGS += " -Wl,-exported_symbol,_Init_executorch" end -$LDFLAGS += ' -lpthread' if RUBY_PLATFORM =~ /linux/ +# ---------------------------------------------------------------------------- +# 4. Sources & Makefile +# ---------------------------------------------------------------------------- -# Create Makefile -create_makefile('executorch/executorch') +$VPATH << "$(srcdir)/core" +$srcs = %w[ + core.cpp + rb_errors.cpp + rb_tensor.cpp + rb_module.cpp + rb_executorch.cpp +] -puts "\nConfiguration complete. Run 'make' to build." +create_makefile("executorch/executorch") diff --git a/ext/executorch/rb_errors.cpp b/ext/executorch/rb_errors.cpp new file mode 100644 index 0000000..de951cd --- /dev/null +++ b/ext/executorch/rb_errors.cpp @@ -0,0 +1,117 @@ +#include "rb_internal.hpp" + +namespace etrb { + +static VALUE rb_error_code(VALUE self) { + return rb_ivar_get(self, g_refs.id_code); +} + +static VALUE rb_error_pal_log(VALUE self) { + return rb_ivar_get(self, g_refs.id_pal_log); +} + +void init_errors(VALUE mExecutorch) { + g_refs.id_code = rb_intern("@code"); + g_refs.id_pal_log = rb_intern("@pal_log"); + + g_refs.eError = + rb_define_class_under(mExecutorch, "Error", rb_eStandardError); + rb_define_method(g_refs.eError, "code", rb_error_code, 0); + rb_define_method(g_refs.eError, "pal_log", rb_error_pal_log, 0); + + g_refs.eLoadError = + rb_define_class_under(mExecutorch, "LoadError", g_refs.eError); + g_refs.eMethodNotFoundError = + rb_define_class_under(mExecutorch, "MethodNotFoundError", g_refs.eError); + g_refs.eOperatorMissingError = + rb_define_class_under(mExecutorch, "OperatorMissingError", g_refs.eError); + g_refs.eDelegateError = + rb_define_class_under(mExecutorch, "DelegateError", g_refs.eError); + g_refs.eShapeError = + rb_define_class_under(mExecutorch, "ShapeError", g_refs.eError); + g_refs.eDTypeError = + rb_define_class_under(mExecutorch, "DTypeError", g_refs.eError); + g_refs.eExecutionError = + rb_define_class_under(mExecutorch, "ExecutionError", g_refs.eError); + g_refs.eMemoryError = + rb_define_class_under(mExecutorch, "MemoryError", g_refs.eError); + g_refs.eClosedError = + rb_define_class_under(mExecutorch, "ClosedError", g_refs.eError); + + rb_global_variable(&g_refs.eError); + rb_global_variable(&g_refs.eLoadError); + rb_global_variable(&g_refs.eMethodNotFoundError); + rb_global_variable(&g_refs.eOperatorMissingError); + rb_global_variable(&g_refs.eDelegateError); + rb_global_variable(&g_refs.eShapeError); + rb_global_variable(&g_refs.eDTypeError); + rb_global_variable(&g_refs.eExecutionError); + rb_global_variable(&g_refs.eMemoryError); + rb_global_variable(&g_refs.eClosedError); +} + +VALUE status_to_ruby_exception(const Status& st) { + VALUE klass = g_refs.eExecutionError; + switch (st.kind) { + case ErrorKind::Load: + klass = g_refs.eLoadError; + break; + case ErrorKind::MethodNotFound: + klass = g_refs.eMethodNotFoundError; + break; + case ErrorKind::OperatorMissing: + klass = g_refs.eOperatorMissingError; + break; + case ErrorKind::Delegate: + klass = g_refs.eDelegateError; + break; + case ErrorKind::Shape: + klass = g_refs.eShapeError; + break; + case ErrorKind::DType: + klass = g_refs.eDTypeError; + break; + case ErrorKind::Memory: + klass = g_refs.eMemoryError; + break; + case ErrorKind::Closed: + klass = g_refs.eClosedError; + break; + case ErrorKind::Argument: + klass = rb_eArgError; + break; + case ErrorKind::Type: + klass = rb_eTypeError; + break; + case ErrorKind::Range: + klass = rb_eRangeError; + break; + case ErrorKind::Execution: + default: + klass = g_refs.eExecutionError; + break; + } + + VALUE msg = rb_utf8_str_new(st.message.data(), static_cast(st.message.size())); + VALUE exc = rb_exc_new_str(klass, msg); + if (rb_obj_is_kind_of(exc, g_refs.eError)) { + rb_ivar_set( + exc, + g_refs.id_code, + st.et_code == 0 ? Qnil : ULONG2NUM(static_cast(st.et_code))); + rb_ivar_set( + exc, + g_refs.id_pal_log, + st.pal_log.empty() + ? Qnil + : rb_utf8_str_new( + st.pal_log.data(), static_cast(st.pal_log.size()))); + } + return exc; +} + +[[noreturn]] void raise_status_no_live_cpp(VALUE exc) { + rb_exc_raise(exc); +} + +} // namespace etrb diff --git a/ext/executorch/rb_executorch.cpp b/ext/executorch/rb_executorch.cpp new file mode 100644 index 0000000..f382c59 --- /dev/null +++ b/ext/executorch/rb_executorch.cpp @@ -0,0 +1,69 @@ +#include "rb_internal.hpp" + +namespace etrb { + +RubyRefs g_refs; + +namespace { + +VALUE rb_et_backends(VALUE) { + auto list = registered_backends(); + VALUE ary = rb_ary_new_capa(static_cast(list.size())); + for (const auto& name : list) { + rb_ary_push(ary, rb_utf8_str_new(name.data(), static_cast(name.size()))); + } + return ary; +} + +VALUE rb_et_kernel_count(VALUE) { + return ULL2NUM(registered_kernel_count()); +} + +VALUE rb_et_num_threads(VALUE) { + return LL2NUM(get_num_threads()); +} + +VALUE rb_et_set_num_threads(VALUE, VALUE val) { + if (!RB_INTEGER_TYPE_P(val)) { + rb_raise(rb_eTypeError, "num_threads must be an Integer"); + } + int64_t n = NUM2LL(val); + VALUE err_exc = Qnil; + { + auto st = set_num_threads(n); + if (!st.ok()) { + err_exc = status_to_ruby_exception(st); + } + } + if (err_exc != Qnil) raise_status_no_live_cpp(err_exc); + return val; +} + +VALUE rb_et_executorch_version(VALUE) { +#ifdef EXECUTORCH_RUBY_SDK_VERSION + return rb_utf8_str_new_cstr(EXECUTORCH_RUBY_SDK_VERSION); +#else + return rb_utf8_str_new_cstr("unknown"); +#endif +} + +} // namespace +} // namespace etrb + +extern "C" __attribute__((visibility("default"))) void Init_executorch(void) { + etrb::init_runtime_once(); + + VALUE mExecutorch = rb_define_module("Executorch"); + etrb::g_refs.mExecutorch = mExecutorch; + rb_global_variable(&etrb::g_refs.mExecutorch); + + etrb::init_errors(mExecutorch); + etrb::init_tensor(mExecutorch); + etrb::init_module(mExecutorch); + + rb_define_singleton_method(mExecutorch, "backends", etrb::rb_et_backends, 0); + rb_define_singleton_method(mExecutorch, "kernel_count", etrb::rb_et_kernel_count, 0); + rb_define_singleton_method(mExecutorch, "num_threads", etrb::rb_et_num_threads, 0); + rb_define_singleton_method(mExecutorch, "num_threads=", etrb::rb_et_set_num_threads, 1); + rb_define_singleton_method(mExecutorch, "executorch_version", etrb::rb_et_executorch_version, 0); +} diff --git a/ext/executorch/rb_internal.hpp b/ext/executorch/rb_internal.hpp new file mode 100644 index 0000000..4ce21cb --- /dev/null +++ b/ext/executorch/rb_internal.hpp @@ -0,0 +1,121 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "core/dtype.hpp" +#include "core/module_core.hpp" +#include "core/status.hpp" +#include "core/tensor_core.hpp" + +namespace etrb { + +// Cached Ruby modules, classes, and symbols initialized once in Init_executorch. +struct RubyRefs { + VALUE mExecutorch = Qnil; + VALUE cModule = Qnil; + VALUE cMethodMeta = Qnil; + VALUE cTensorInfo = Qnil; + VALUE cTensor = Qnil; + + // Error hierarchy (all < Executorch::Error < StandardError) + VALUE eError = Qnil; + VALUE eLoadError = Qnil; + VALUE eMethodNotFoundError = Qnil; + VALUE eOperatorMissingError = Qnil; + VALUE eDelegateError = Qnil; + VALUE eShapeError = Qnil; + VALUE eDTypeError = Qnil; + VALUE eExecutionError = Qnil; + VALUE eMemoryError = Qnil; + VALUE eClosedError = Qnil; + + // Cached IDs + ID id_code = 0; + ID id_pal_log = 0; + ID id_float32 = 0; + ID id_float64 = 0; + ID id_float16 = 0; + ID id_bfloat16 = 0; + ID id_uint8 = 0; + ID id_int8 = 0; + ID id_int16 = 0; + ID id_uint16 = 0; + ID id_int32 = 0; + ID id_uint32 = 0; + ID id_int64 = 0; + ID id_uint64 = 0; + ID id_bool = 0; + ID id_unknown = 0; + + // LoadMode symbols + ID id_mmap = 0; + ID id_file = 0; + ID id_mmap_mlock = 0; + ID id_mmap_mlock_ignore_errors = 0; + ID id_mmap_madvise = 0; + + // Keyword IDs + ID id_kw_shape = 0; + ID id_kw_dtype = 0; + ID id_kw_load_mode = 0; + ID id_kw_data_files = 0; + ID id_kw_out = 0; +}; + +extern RubyRefs g_refs; + +// TypedData structs +struct RbTensorWrap { + // Owned TensorPtr (null if borrowed_buf != Qnil or closed). + executorch::extension::TensorPtr tensor; + // When created via Tensor.from_buffer, holds the Ruby IO::Buffer VALUE + // (marked in dmark so GC keeps it alive; locked around off-GVL execute). + VALUE borrowed_buf = Qnil; + std::vector borrowed_sizes; + executorch::aten::ScalarType borrowed_dtype = + executorch::aten::ScalarType::Undefined; + size_t borrowed_nbytes = 0; + size_t tracked_bytes = 0; + bool closed = false; +}; + +struct RbModuleWrap { + std::unique_ptr core; + size_t tracked_bytes = 0; +}; + +extern const rb_data_type_t kTensorDataType; +extern const rb_data_type_t kModuleDataType; + +// Subsystem initializers +void init_errors(VALUE mExecutorch); +void init_tensor(VALUE mExecutorch); +void init_module(VALUE mExecutorch); + +// Convert Status into a Ruby exception VALUE WITHOUT raising (so callers can +// finish destroying all C++ objects on the stack before rb_exc_raise). +VALUE status_to_ruby_exception(const Status& st); + +// Helper: build Ruby exception from Status and raise it. +// SAFETY: Caller MUST ensure NO C++ objects with non-trivial destructors are +// live on the stack in the caller's frame (or any intervening C++ frames)! +[[noreturn]] void raise_status_no_live_cpp(VALUE exc); + +// Tensor interop helpers used by rb_module.cpp +VALUE wrap_owned_tensor(executorch::extension::TensorPtr ptr); +bool is_rb_tensor(VALUE obj); +RbTensorWrap* get_rb_tensor(VALUE obj); + +// Dtype Symbol <-> ScalarType helpers (using cached IDs, zero rb_intern on hot path) +VALUE scalar_type_to_sym(executorch::aten::ScalarType st); +bool sym_to_scalar_type(VALUE sym, executorch::aten::ScalarType* out); + +} // namespace etrb diff --git a/ext/executorch/rb_module.cpp b/ext/executorch/rb_module.cpp new file mode 100644 index 0000000..008d2b7 --- /dev/null +++ b/ext/executorch/rb_module.cpp @@ -0,0 +1,760 @@ +#include "rb_internal.hpp" + +#include +#include + +namespace etrb { + +namespace { + +void module_free(void* p) { + auto* wrap = static_cast(p); + if (wrap->tracked_bytes > 0) { + rb_gc_adjust_memory_usage(-static_cast(wrap->tracked_bytes)); + wrap->tracked_bytes = 0; + } + delete wrap; +} + +size_t module_memsize(const void* p) { + const auto* wrap = static_cast(p); + return sizeof(RbModuleWrap) + wrap->tracked_bytes; +} + +VALUE module_alloc(VALUE klass) { + auto* wrap = new (std::nothrow) RbModuleWrap(); + if (wrap == nullptr) { + rb_memerror(); + } + return TypedData_Wrap_Struct(klass, &kModuleDataType, wrap); +} + +RbModuleWrap* get_module_wrap(VALUE self) { + RbModuleWrap* wrap = nullptr; + TypedData_Get_Struct(self, RbModuleWrap, &kModuleDataType, wrap); + if (wrap == nullptr || !wrap->core || wrap->core->is_closed()) { + rb_raise(g_refs.eClosedError, "Executorch::Module is closed"); + } + return wrap; +} + +ModuleCore::LoadMode parse_load_mode(VALUE val) { + if (val == Qundef || val == Qnil) { + return ModuleCore::LoadMode::Mmap; + } + if (!RB_SYMBOL_P(val)) { + rb_raise(rb_eTypeError, "load_mode must be a Symbol"); + } + ID id = SYM2ID(val); + if (id == g_refs.id_mmap) return ModuleCore::LoadMode::Mmap; + if (id == g_refs.id_file) return ModuleCore::LoadMode::File; + if (id == g_refs.id_mmap_mlock) return ModuleCore::LoadMode::MmapUseMlock; + if (id == g_refs.id_mmap_mlock_ignore_errors) { + return ModuleCore::LoadMode::MmapUseMlockIgnoreErrors; + } + if (id == g_refs.id_mmap_madvise) return ModuleCore::LoadMode::MmapUseMadvise; + rb_raise( + rb_eArgError, + "unknown load_mode :%s (expected :mmap, :file, :mmap_mlock, " + ":mmap_mlock_ignore_errors, or :mmap_madvise)", + rb_id2name(id)); +} + +std::string value_to_method_name(VALUE v) { + if (RB_SYMBOL_P(v)) { + const char* s = rb_id2name(SYM2ID(v)); + return s ? std::string(s) : std::string(); + } + VALUE str = StringValue(v); + return std::string(RSTRING_PTR(str), static_cast(RSTRING_LEN(str))); +} + +const char* tag_to_name(executorch::runtime::Tag tag) noexcept { + switch (tag) { + case executorch::runtime::Tag::None: return "none"; + case executorch::runtime::Tag::Tensor: return "tensor"; + case executorch::runtime::Tag::String: return "string"; + case executorch::runtime::Tag::Double: return "double"; + case executorch::runtime::Tag::Int: return "int"; + case executorch::runtime::Tag::Bool: return "bool"; + case executorch::runtime::Tag::ListBool: return "list_bool"; + case executorch::runtime::Tag::ListDouble: return "list_double"; + case executorch::runtime::Tag::ListTensor: return "list_tensor"; + case executorch::runtime::Tag::ListScalar: return "list_scalar"; + case executorch::runtime::Tag::ListOptionalTensor: return "list_optional_tensor"; + case executorch::runtime::Tag::ListInt: return "list_int"; + default: return "unknown"; + } +} + +VALUE build_value_meta(const ValueMetaSnapshot& vm) { + VALUE tag_sym = ID2SYM(rb_intern(tag_to_name(vm.tag))); + if (vm.tag != executorch::runtime::Tag::Tensor) { + return rb_funcall( + g_refs.cTensorInfo, + rb_intern("new"), + 6, + tag_sym, + Qnil, + Qnil, + Qnil, + Qnil, + Qfalse); + } + VALUE shape = rb_ary_new_capa(static_cast(vm.tensor.sizes.size())); + for (auto s : vm.tensor.sizes) rb_ary_push(shape, LONG2NUM(s)); + VALUE order = rb_ary_new_capa(static_cast(vm.tensor.dim_order.size())); + for (auto o : vm.tensor.dim_order) rb_ary_push(order, INT2FIX(o)); + VALUE dtype = scalar_type_to_sym(vm.tensor.dtype); + VALUE nbytes = ULL2NUM(vm.tensor.nbytes); + VALUE planned = vm.tensor.memory_planned ? Qtrue : Qfalse; + return rb_funcall( + g_refs.cTensorInfo, + rb_intern("new"), + 6, + tag_sym, + dtype, + shape, + order, + nbytes, + planned); +} + +VALUE build_method_meta(const MethodMetaSnapshot& snap) { + VALUE name = rb_utf8_str_new(snap.name.data(), static_cast(snap.name.size())); + VALUE inputs = rb_ary_new_capa(static_cast(snap.inputs.size())); + for (const auto& vm : snap.inputs) rb_ary_push(inputs, build_value_meta(vm)); + VALUE outputs = rb_ary_new_capa(static_cast(snap.outputs.size())); + for (const auto& vm : snap.outputs) rb_ary_push(outputs, build_value_meta(vm)); + VALUE backends = rb_ary_new_capa(static_cast(snap.backends.size())); + for (const auto& b : snap.backends) { + rb_ary_push(backends, rb_utf8_str_new(b.data(), static_cast(b.size()))); + } + VALUE planned = LL2NUM(snap.planned_memory_bytes); + return rb_funcall( + g_refs.cMethodMeta, + rb_intern("new"), + 5, + name, + inputs, + outputs, + backends, + planned); +} + +// Convert Ruby VALUE to CoreValue under the GVL. For borrowed IO::Buffer +// tensors, records the IO::Buffer VALUE in `locked_bufs` so we lock it around +// the off-GVL execute call and guarantee unlock via rb_ensure. +Status ruby_to_core_value( + VALUE v, + CoreValue* out, + std::vector* locked_bufs, + bool for_output_target) { + if (is_rb_tensor(v)) { + RbTensorWrap* wrap = nullptr; + TypedData_Get_Struct(v, RbTensorWrap, &kTensorDataType, wrap); + if (wrap == nullptr || wrap->closed || + (!wrap->tensor && wrap->borrowed_buf == Qnil)) { + return Status::Make(ErrorKind::Closed, "Executorch::Tensor is closed"); + } + if (wrap->borrowed_buf != Qnil) { + void* ptr = nullptr; + size_t len = 0; + if (for_output_target) { + rb_io_buffer_get_bytes_for_writing(wrap->borrowed_buf, &ptr, &len); + } else { + const void* cptr = nullptr; + rb_io_buffer_get_bytes_for_reading(wrap->borrowed_buf, &cptr, &len); + ptr = const_cast(cptr); + } + if (len != wrap->borrowed_nbytes) { + return Status::Make( + ErrorKind::Shape, + "IO::Buffer size changed: expected " + + std::to_string(wrap->borrowed_nbytes) + ", got " + + std::to_string(len)); + } + auto tp_res = make_borrowed_tensor_ptr( + wrap->borrowed_sizes, wrap->borrowed_dtype, ptr); + if (!tp_res.ok()) { + return tp_res.status; + } + locked_bufs->push_back(wrap->borrowed_buf); + *out = CoreValue::Tensor(std::move(tp_res.value)); + return Status::Ok(); + } + *out = CoreValue::Tensor(wrap->tensor); + return Status::Ok(); + } + + if (for_output_target) { + return Status::Make(ErrorKind::Type, "out: target must be an Executorch::Tensor"); + } + + if (v == Qnil) { + *out = CoreValue::None(); + return Status::Ok(); + } + if (v == Qtrue) { + *out = CoreValue::Bool(true); + return Status::Ok(); + } + if (v == Qfalse) { + *out = CoreValue::Bool(false); + return Status::Ok(); + } + if (RB_INTEGER_TYPE_P(v)) { + *out = CoreValue::Int(NUM2LL(v)); + return Status::Ok(); + } + if (RB_FLOAT_TYPE_P(v)) { + *out = CoreValue::Double(RFLOAT_VALUE(v)); + return Status::Ok(); + } + if (RB_TYPE_P(v, T_STRING)) { + *out = CoreValue::String( + std::string(RSTRING_PTR(v), static_cast(RSTRING_LEN(v)))); + return Status::Ok(); + } + return Status::Make( + ErrorKind::Type, + std::string("unsupported ExecuTorch input type: ") + rb_obj_classname(v)); +} + +VALUE core_value_to_ruby(CoreValue& cv) { + switch (cv.kind) { + case ValueKind::None: + return Qnil; + case ValueKind::Int: + return LL2NUM(cv.int_val); + case ValueKind::Double: + return DBL2NUM(cv.double_val); + case ValueKind::Bool: + return cv.bool_val ? Qtrue : Qfalse; + case ValueKind::String: + return rb_utf8_str_new( + cv.string_val.data(), static_cast(cv.string_val.size())); + case ValueKind::Tensor: + return wrap_owned_tensor(std::move(cv.tensor_val)); + case ValueKind::IntList: { + VALUE ary = rb_ary_new_capa(static_cast(cv.int_list.size())); + for (auto x : cv.int_list) rb_ary_push(ary, LL2NUM(x)); + return ary; + } + case ValueKind::DoubleList: { + VALUE ary = rb_ary_new_capa(static_cast(cv.double_list.size())); + for (auto x : cv.double_list) rb_ary_push(ary, DBL2NUM(x)); + return ary; + } + case ValueKind::BoolList: { + VALUE ary = rb_ary_new_capa(static_cast(cv.bool_list.size())); + for (bool x : cv.bool_list) rb_ary_push(ary, x ? Qtrue : Qfalse); + return ary; + } + case ValueKind::TensorList: { + VALUE ary = rb_ary_new_capa(static_cast(cv.tensor_list.size())); + for (auto& tp : cv.tensor_list) { + rb_ary_push(ary, wrap_owned_tensor(std::move(tp))); + } + return ary; + } + } + return Qnil; +} + +// --------------------------------------------------------------------------- +// Ruby methods for Executorch::Module +// --------------------------------------------------------------------------- + +// Module._open_file(path, load_mode:, data_files:) +VALUE rb_module_s_open_file(int argc, VALUE* argv, VALUE klass) { + VALUE path_val = Qnil; + VALUE opts = Qnil; + rb_scan_args(argc, argv, "1:", &path_val, &opts); + + // Supports String and Pathname via rb_get_path! + VALUE path_str = rb_get_path(path_val); + VALUE kw_vals[2] = {Qundef, Qundef}; + ID kw_ids[2] = {g_refs.id_kw_load_mode, g_refs.id_kw_data_files}; + if (!NIL_P(opts)) { + rb_get_kwargs(opts, kw_ids, 0, 2, kw_vals); + } + const auto mode = parse_load_mode(kw_vals[0]); + + VALUE err_exc = Qnil; + VALUE obj = Qnil; + int protect_state = 0; + + { + std::string path(RSTRING_PTR(path_str), static_cast(RSTRING_LEN(path_str))); + std::vector data_files; + + if (kw_vals[1] != Qundef && kw_vals[1] != Qnil) { + VALUE df_ary = kw_vals[1]; + if (!RB_TYPE_P(df_ary, T_ARRAY)) { + err_exc = rb_exc_new_cstr(rb_eTypeError, "data_files must be an Array of paths"); + } else { + struct DfArg { + VALUE ary; + std::vector* out; + } dfa{df_ary, &data_files}; + rb_protect( + [](VALUE a) -> VALUE { + auto* d = reinterpret_cast(a); + long n = RARRAY_LEN(d->ary); + d->out->reserve(static_cast(n)); + for (long i = 0; i < n; ++i) { + VALUE ps = rb_get_path(rb_ary_entry(d->ary, i)); + d->out->emplace_back( + RSTRING_PTR(ps), static_cast(RSTRING_LEN(ps))); + } + return Qnil; + }, + reinterpret_cast(&dfa), + &protect_state); + } + } + + if (protect_state == 0 && err_exc == Qnil) { + struct OpenCtx { + const std::string* path; + const std::vector* data_files; + ModuleCore::LoadMode mode; + StatusOr> result; + } ctx{&path, &data_files, mode, {}}; + + rb_thread_call_without_gvl( + [](void* p) -> void* { + auto* c = static_cast(p); + c->result = ModuleCore::open_file(*c->path, *c->data_files, c->mode); + return nullptr; + }, + &ctx, + RUBY_UBF_IO, + nullptr); + + if (!ctx.result.ok()) { + err_exc = status_to_ruby_exception(ctx.result.status); + } else { + obj = module_alloc(klass); + RbModuleWrap* wrap = nullptr; + TypedData_Get_Struct(obj, RbModuleWrap, &kModuleDataType, wrap); + wrap->core = std::move(ctx.result.value); + wrap->tracked_bytes = wrap->core->estimated_memory_bytes(); + if (wrap->tracked_bytes > 0) { + rb_gc_adjust_memory_usage(static_cast(wrap->tracked_bytes)); + } + } + } + } + + RB_GC_GUARD(path_str); + if (protect_state != 0) rb_jump_tag(protect_state); + if (err_exc != Qnil) raise_status_no_live_cpp(err_exc); + return obj; +} + +// Module.from_bytes(str) +VALUE rb_module_s_from_bytes(VALUE klass, VALUE bytes_val) { + Check_Type(bytes_val, T_STRING); + VALUE err_exc = Qnil; + VALUE obj = Qnil; + + { + const auto* raw = reinterpret_cast(RSTRING_PTR(bytes_val)); + const size_t len = static_cast(RSTRING_LEN(bytes_val)); + std::vector copy; + try { + copy.assign(raw, raw + len); + } catch (const std::bad_alloc&) { + err_exc = rb_exc_new_cstr(g_refs.eMemoryError, "out of memory copying .pte bytes"); + } + + if (err_exc == Qnil) { + struct BytesCtx { + std::vector* bytes; + StatusOr> result; + } ctx{©, {}}; + + rb_thread_call_without_gvl( + [](void* p) -> void* { + auto* c = static_cast(p); + c->result = ModuleCore::open_bytes(std::move(*c->bytes)); + return nullptr; + }, + &ctx, + RUBY_UBF_IO, + nullptr); + + if (!ctx.result.ok()) { + err_exc = status_to_ruby_exception(ctx.result.status); + } else { + obj = module_alloc(klass); + RbModuleWrap* wrap = nullptr; + TypedData_Get_Struct(obj, RbModuleWrap, &kModuleDataType, wrap); + wrap->core = std::move(ctx.result.value); + wrap->tracked_bytes = wrap->core->estimated_memory_bytes(); + if (wrap->tracked_bytes > 0) { + rb_gc_adjust_memory_usage(static_cast(wrap->tracked_bytes)); + } + } + } + } + + RB_GC_GUARD(bytes_val); + if (err_exc != Qnil) raise_status_no_live_cpp(err_exc); + return obj; +} + +VALUE rb_module_source(VALUE self) { + auto* wrap = get_module_wrap(self); + std::string s = wrap->core->source_label(); + return rb_utf8_str_new(s.data(), static_cast(s.size())); +} + +VALUE rb_module_close(VALUE self) { + RbModuleWrap* wrap = nullptr; + TypedData_Get_Struct(self, RbModuleWrap, &kModuleDataType, wrap); + if (wrap != nullptr && wrap->core && !wrap->core->is_closed()) { + rb_thread_call_without_gvl( + [](void* p) -> void* { + static_cast(p)->close(); + return nullptr; + }, + wrap->core.get(), + RUBY_UBF_IO, + nullptr); + if (wrap->tracked_bytes > 0) { + rb_gc_adjust_memory_usage(-static_cast(wrap->tracked_bytes)); + wrap->tracked_bytes = 0; + } + } + return Qnil; +} + +VALUE rb_module_closed_p(VALUE self) { + RbModuleWrap* wrap = nullptr; + TypedData_Get_Struct(self, RbModuleWrap, &kModuleDataType, wrap); + return (wrap == nullptr || !wrap->core || wrap->core->is_closed()) ? Qtrue : Qfalse; +} + +VALUE rb_module_method_names(VALUE self) { + auto* wrap = get_module_wrap(self); + VALUE err_exc = Qnil; + VALUE out = Qnil; + { + auto res = wrap->core->method_names(); + if (!res.ok()) { + err_exc = status_to_ruby_exception(res.status); + } else { + out = rb_ary_new_capa(static_cast(res.value.size())); + for (const auto& name : res.value) { + rb_ary_push(out, rb_utf8_str_new(name.data(), static_cast(name.size()))); + } + } + } + if (err_exc != Qnil) raise_status_no_live_cpp(err_exc); + return out; +} + +VALUE rb_module_meta(int argc, VALUE* argv, VALUE self) { + auto* wrap = get_module_wrap(self); + VALUE name_val = Qnil; + rb_scan_args(argc, argv, "01", &name_val); + VALUE err_exc = Qnil; + VALUE out = Qnil; + { + std::string mname = NIL_P(name_val) ? std::string("forward") + : value_to_method_name(name_val); + auto res = wrap->core->method_meta(mname); + if (!res.ok()) { + err_exc = status_to_ruby_exception(res.status); + } else { + out = build_method_meta(res.value); + } + } + if (err_exc != Qnil) raise_status_no_live_cpp(err_exc); + return out; +} + +VALUE rb_module_load_method(int argc, VALUE* argv, VALUE self) { + auto* wrap = get_module_wrap(self); + VALUE name_val = Qnil; + rb_scan_args(argc, argv, "01", &name_val); + VALUE err_exc = Qnil; + { + std::string mname = NIL_P(name_val) ? std::string("forward") + : value_to_method_name(name_val); + struct LoadCtx { + ModuleCore* core; + const std::string* name; + Status status; + } ctx{wrap->core.get(), &mname, Status::Ok()}; + + rb_thread_call_without_gvl( + [](void* p) -> void* { + auto* c = static_cast(p); + c->status = c->core->load_method(*c->name); + return nullptr; + }, + &ctx, + RUBY_UBF_IO, + nullptr); + + if (!ctx.status.ok()) { + err_exc = status_to_ruby_exception(ctx.status); + } + } + RB_GC_GUARD(self); + if (err_exc != Qnil) raise_status_no_live_cpp(err_exc); + return self; +} + +VALUE rb_module_unload_method(int argc, VALUE* argv, VALUE self) { + auto* wrap = get_module_wrap(self); + VALUE name_val = Qnil; + rb_scan_args(argc, argv, "01", &name_val); + VALUE err_exc = Qnil; + bool unloaded = false; + { + std::string mname = NIL_P(name_val) ? std::string("forward") + : value_to_method_name(name_val); + auto res = wrap->core->unload_method(mname); + if (!res.ok()) { + err_exc = status_to_ruby_exception(res.status); + } else { + unloaded = res.value; + } + } + if (err_exc != Qnil) raise_status_no_live_cpp(err_exc); + return unloaded ? Qtrue : Qfalse; +} + +VALUE rb_module_method_loaded_p(int argc, VALUE* argv, VALUE self) { + auto* wrap = get_module_wrap(self); + VALUE name_val = Qnil; + rb_scan_args(argc, argv, "01", &name_val); + std::string mname = NIL_P(name_val) ? std::string("forward") + : value_to_method_name(name_val); + return wrap->core->is_method_loaded(mname) ? Qtrue : Qfalse; +} + +// _execute(method_name, inputs_array, out_array_or_nil) -> Array of outputs +VALUE rb_module_execute_raw(VALUE self, VALUE name_val, VALUE inputs_ary, VALUE out_val) { + auto* wrap = get_module_wrap(self); + Check_Type(inputs_ary, T_ARRAY); + + VALUE err_exc = Qnil; + VALUE result_ary = Qnil; + int protect_state = 0; + + { + std::string mname = value_to_method_name(name_val); + std::vector core_inputs; + std::vector out_targets; + std::vector out_ruby_objs; + std::vector locked_bufs; + + // 1. Convert inputs & out targets under the GVL. + struct PrepArg { + VALUE inputs_ary; + VALUE out_val; + std::vector* core_inputs; + std::vector* out_targets; + std::vector* out_ruby_objs; + std::vector* locked_bufs; + Status status; + } prep{inputs_ary, out_val, &core_inputs, &out_targets, &out_ruby_objs, &locked_bufs, Status::Ok()}; + + rb_protect( + [](VALUE a) -> VALUE { + auto* p = reinterpret_cast(a); + long n_in = RARRAY_LEN(p->inputs_ary); + p->core_inputs->reserve(static_cast(n_in)); + for (long i = 0; i < n_in; ++i) { + CoreValue cv; + auto st = ruby_to_core_value( + rb_ary_entry(p->inputs_ary, i), &cv, p->locked_bufs, false); + if (!st.ok()) { + p->status = std::move(st); + return Qnil; + } + p->core_inputs->push_back(std::move(cv)); + } + if (!NIL_P(p->out_val)) { + if (RB_TYPE_P(p->out_val, T_ARRAY)) { + long n_out = RARRAY_LEN(p->out_val); + p->out_targets->reserve(static_cast(n_out)); + p->out_ruby_objs->reserve(static_cast(n_out)); + for (long i = 0; i < n_out; ++i) { + VALUE item = rb_ary_entry(p->out_val, i); + CoreValue cv; + auto st = ruby_to_core_value(item, &cv, p->locked_bufs, true); + if (!st.ok()) { + p->status = std::move(st); + return Qnil; + } + p->out_targets->push_back(std::move(cv.tensor_val)); + p->out_ruby_objs->push_back(item); + } + } else { + CoreValue cv; + auto st = ruby_to_core_value(p->out_val, &cv, p->locked_bufs, true); + if (!st.ok()) { + p->status = std::move(st); + return Qnil; + } + p->out_targets->push_back(std::move(cv.tensor_val)); + p->out_ruby_objs->push_back(p->out_val); + } + } + return Qnil; + }, + reinterpret_cast(&prep), + &protect_state); + + if (protect_state == 0 && !prep.status.ok()) { + err_exc = status_to_ruby_exception(prep.status); + } + + // 2. Lock any borrowed IO::Buffers before releasing GVL, and unlock all of + // them unconditionally immediately after (even if an exception occurs). + if (protect_state == 0 && err_exc == Qnil) { + std::vector actually_locked; + actually_locked.reserve(locked_bufs.size()); + + struct ExecCtx { + ModuleCore* core; + const std::string* method_name; + const std::vector* inputs; + const std::vector* out_targets; + StatusOr> result; + } ectx{wrap->core.get(), &mname, &core_inputs, &out_targets, {}}; + + struct LockRunArg { + std::vector* to_lock; + std::vector* locked; + ExecCtx* ectx; + } lra{&locked_bufs, &actually_locked, &ectx}; + + rb_protect( + [](VALUE a) -> VALUE { + auto* l = reinterpret_cast(a); + for (VALUE b : *l->to_lock) { + // Avoid double-locking the exact same IO::Buffer object twice. + bool seen = false; + for (VALUE already : *l->locked) { + if (already == b) { seen = true; break; } + } + if (!seen) { + rb_io_buffer_lock(b); + l->locked->push_back(b); + } + } + rb_thread_call_without_gvl( + [](void* p) -> void* { + auto* c = static_cast(p); + c->result = c->core->execute( + *c->method_name, *c->inputs, *c->out_targets); + return nullptr; + }, + l->ectx, + RUBY_UBF_IO, + nullptr); + return Qnil; + }, + reinterpret_cast(&lra), + &protect_state); + + // Always unlock every locked IO::Buffer under the GVL. + for (auto it = actually_locked.rbegin(); it != actually_locked.rend(); ++it) { + rb_io_buffer_try_unlock(*it); + } + + if (protect_state == 0) { + if (!ectx.result.ok()) { + err_exc = status_to_ruby_exception(ectx.result.status); + } else if (!out_ruby_objs.empty()) { + // Return the exact caller-provided out: Ruby Tensor objects! + result_ary = rb_ary_new_capa(static_cast(out_ruby_objs.size())); + for (VALUE ro : out_ruby_objs) { + rb_ary_push(result_ary, ro); + } + } else { + struct WrapOutArg { + std::vector* vals; + } woa{&ectx.result.value}; + result_ary = rb_protect( + [](VALUE a) -> VALUE { + auto* w = reinterpret_cast(a); + VALUE ary = rb_ary_new_capa(static_cast(w->vals->size())); + for (auto& cv : *w->vals) { + rb_ary_push(ary, core_value_to_ruby(cv)); + } + return ary; + }, + reinterpret_cast(&woa), + &protect_state); + } + } + } + } // All C++ locals destroyed here before any rb_jump_tag / rb_exc_raise! + + RB_GC_GUARD(self); + RB_GC_GUARD(inputs_ary); + RB_GC_GUARD(out_val); + if (protect_state != 0) rb_jump_tag(protect_state); + if (err_exc != Qnil) raise_status_no_live_cpp(err_exc); + return result_ary; +} + +} // namespace + +const rb_data_type_t kModuleDataType = { + "Executorch::Module", + { + nullptr, + module_free, + module_memsize, + nullptr, + {nullptr}, + }, + nullptr, + nullptr, + RUBY_TYPED_FREE_IMMEDIATELY, +}; + +void init_module(VALUE mExecutorch) { + g_refs.id_mmap = rb_intern("mmap"); + g_refs.id_file = rb_intern("file"); + g_refs.id_mmap_mlock = rb_intern("mmap_mlock"); + g_refs.id_mmap_mlock_ignore_errors = rb_intern("mmap_mlock_ignore_errors"); + g_refs.id_mmap_madvise = rb_intern("mmap_madvise"); + g_refs.id_kw_load_mode = rb_intern("load_mode"); + g_refs.id_kw_data_files = rb_intern("data_files"); + g_refs.id_kw_out = rb_intern("out"); + + g_refs.cMethodMeta = rb_const_get(mExecutorch, rb_intern("MethodMeta")); + g_refs.cTensorInfo = rb_const_get(mExecutorch, rb_intern("TensorInfo")); + rb_global_variable(&g_refs.cMethodMeta); + rb_global_variable(&g_refs.cTensorInfo); + + g_refs.cModule = rb_define_class_under(mExecutorch, "Module", rb_cObject); + rb_global_variable(&g_refs.cModule); + rb_undef_alloc_func(g_refs.cModule); + + rb_define_singleton_method(g_refs.cModule, "_open_file", rb_module_s_open_file, -1); + rb_define_singleton_method(g_refs.cModule, "from_bytes", rb_module_s_from_bytes, 1); + + rb_define_method(g_refs.cModule, "source", rb_module_source, 0); + rb_define_method(g_refs.cModule, "close", rb_module_close, 0); + rb_define_method(g_refs.cModule, "closed?", rb_module_closed_p, 0); + rb_define_method(g_refs.cModule, "method_names", rb_module_method_names, 0); + rb_define_method(g_refs.cModule, "meta", rb_module_meta, -1); + rb_define_method(g_refs.cModule, "load_method", rb_module_load_method, -1); + rb_define_method(g_refs.cModule, "unload_method", rb_module_unload_method, -1); + rb_define_method(g_refs.cModule, "method_loaded?", rb_module_method_loaded_p, -1); + rb_define_private_method(g_refs.cModule, "_execute", rb_module_execute_raw, 3); +} + +} // namespace etrb diff --git a/ext/executorch/rb_tensor.cpp b/ext/executorch/rb_tensor.cpp new file mode 100644 index 0000000..24efdc2 --- /dev/null +++ b/ext/executorch/rb_tensor.cpp @@ -0,0 +1,1281 @@ +#include "rb_internal.hpp" + +#include +#include +#include +#include + +namespace etrb { + +namespace { + +void tensor_mark(void* p) { + auto* wrap = static_cast(p); + if (wrap->borrowed_buf != Qnil) { + rb_gc_mark(wrap->borrowed_buf); + } +} + +void tensor_free(void* p) { + auto* wrap = static_cast(p); + if (wrap->tracked_bytes > 0) { + rb_gc_adjust_memory_usage(-static_cast(wrap->tracked_bytes)); + wrap->tracked_bytes = 0; + } + delete wrap; +} + +size_t tensor_memsize(const void* p) { + const auto* wrap = static_cast(p); + return sizeof(RbTensorWrap) + wrap->tracked_bytes; +} + +VALUE tensor_alloc(VALUE klass) { + auto* wrap = new (std::nothrow) RbTensorWrap(); + if (wrap == nullptr) { + rb_memerror(); + } + return TypedData_Wrap_Struct(klass, &kTensorDataType, wrap); +} + +RbTensorWrap* check_open_tensor(VALUE self) { + RbTensorWrap* wrap = nullptr; + TypedData_Get_Struct(self, RbTensorWrap, &kTensorDataType, wrap); + if (wrap == nullptr || wrap->closed || + (!wrap->tensor && wrap->borrowed_buf == Qnil)) { + rb_raise(g_refs.eClosedError, "Executorch::Tensor is closed"); + } + return wrap; +} + +// Validate & extract a borrowed IO::Buffer's bytes right now under the GVL. +void check_borrowed_read( + const RbTensorWrap* wrap, + const void** out_ptr, + size_t* out_len) { + const void* ptr = nullptr; + size_t len = 0; + rb_io_buffer_get_bytes_for_reading(wrap->borrowed_buf, &ptr, &len); + if (len != wrap->borrowed_nbytes) { + rb_raise( + g_refs.eShapeError, + "IO::Buffer size changed: expected %zu bytes, got %zu", + wrap->borrowed_nbytes, + len); + } + *out_ptr = ptr; + *out_len = len; +} + +// Parse Ruby Array of dims into int64_t vector with reentrancy-safe length reads. +void parse_ruby_shape(VALUE shape_ary, std::vector* out) { + Check_Type(shape_ary, T_ARRAY); + long len = RARRAY_LEN(shape_ary); + out->reserve(static_cast(len)); + for (long i = 0; i < len; ++i) { + if (i >= RARRAY_LEN(shape_ary)) { + rb_raise(rb_eArgError, "shape array was mutated during conversion"); + } + VALUE v = rb_ary_entry(shape_ary, i); + if (!RB_INTEGER_TYPE_P(v)) { + rb_raise(rb_eTypeError, "shape dimensions must be Integer"); + } + out->push_back(NUM2LL(v)); + } +} + +// Safe scalar extraction from Ruby VALUE to target C++ dtype. +template +T ruby_to_elem(VALUE v); + +template <> +float ruby_to_elem(VALUE v) { + if (RB_FLOAT_TYPE_P(v)) return static_cast(RFLOAT_VALUE(v)); + if (FIXNUM_P(v)) return static_cast(FIX2LONG(v)); + return static_cast(NUM2DBL(v)); +} + +template <> +double ruby_to_elem(VALUE v) { + if (RB_FLOAT_TYPE_P(v)) return RFLOAT_VALUE(v); + if (FIXNUM_P(v)) return static_cast(FIX2LONG(v)); + return NUM2DBL(v); +} + +template <> +executorch::runtime::etensor::Half ruby_to_elem(VALUE v) { + return executorch::runtime::etensor::Half(ruby_to_elem(v)); +} + +template <> +executorch::runtime::etensor::BFloat16 ruby_to_elem(VALUE v) { + return executorch::runtime::etensor::BFloat16(ruby_to_elem(v)); +} + +template <> +bool ruby_to_elem(VALUE v) { + if (v == Qtrue) return true; + if (v == Qfalse) return false; + if (FIXNUM_P(v)) return FIX2LONG(v) != 0; + rb_raise(rb_eTypeError, "expected true, false, or Integer for :bool tensor"); +} + +template +IntT ruby_to_signed_int(VALUE v) { + long long val = 0; + if (FIXNUM_P(v)) { + val = static_cast(FIX2LONG(v)); + } else { + if (RB_FLOAT_TYPE_P(v)) { + double d = RFLOAT_VALUE(v); + if (std::isnan(d) || std::isinf(d)) { + rb_raise(rb_eFloatDomainError, "non-finite float cannot convert to integer"); + } + } + val = NUM2LL(v); + } + constexpr long long lo = static_cast(std::numeric_limits::min()); + constexpr long long hi = static_cast(std::numeric_limits::max()); + if (val < lo || val > hi) { + rb_raise( + rb_eRangeError, + "integer %lld out of range for %zu-bit signed dtype", + val, + sizeof(IntT) * 8); + } + return static_cast(val); +} + +template +UIntT ruby_to_unsigned_int(VALUE v) { + unsigned long long val = 0; + if (FIXNUM_P(v)) { + long lv = FIX2LONG(v); + if (lv < 0) { + rb_raise(rb_eRangeError, "negative value %ld out of range for unsigned dtype", lv); + } + val = static_cast(lv); + } else { + if (RB_FLOAT_TYPE_P(v)) { + double d = RFLOAT_VALUE(v); + if (std::isnan(d) || std::isinf(d)) { + rb_raise(rb_eFloatDomainError, "non-finite float cannot convert to unsigned integer"); + } + if (d < 0.0) { + rb_raise(rb_eRangeError, "negative float out of range for unsigned dtype"); + } + } + val = NUM2ULL(v); + } + constexpr unsigned long long hi = + static_cast(std::numeric_limits::max()); + if (val > hi) { + rb_raise( + rb_eRangeError, + "integer %llu out of range for %zu-bit unsigned dtype", + val, + sizeof(UIntT) * 8); + } + return static_cast(val); +} + +template <> int8_t ruby_to_elem(VALUE v) { return ruby_to_signed_int(v); } +template <> int16_t ruby_to_elem(VALUE v) { return ruby_to_signed_int(v); } +template <> int32_t ruby_to_elem(VALUE v) { return ruby_to_signed_int(v); } +template <> int64_t ruby_to_elem(VALUE v) { return ruby_to_signed_int(v); } +template <> uint8_t ruby_to_elem(VALUE v) { return ruby_to_unsigned_int(v); } +template <> uint16_t ruby_to_elem(VALUE v) { return ruby_to_unsigned_int(v); } +template <> uint32_t ruby_to_elem(VALUE v) { return ruby_to_unsigned_int(v); } +template <> uint64_t ruby_to_elem(VALUE v) { return ruby_to_unsigned_int(v); } + +// Convert C++ element to Ruby VALUE. +template +VALUE elem_to_ruby(T v); + +template <> VALUE elem_to_ruby(float v) { return DBL2NUM(static_cast(v)); } +template <> VALUE elem_to_ruby(double v) { return DBL2NUM(v); } +template <> VALUE elem_to_ruby(executorch::runtime::etensor::Half v) { + return DBL2NUM(static_cast(static_cast(v))); +} +template <> VALUE elem_to_ruby(executorch::runtime::etensor::BFloat16 v) { + return DBL2NUM(static_cast(static_cast(v))); +} +template <> VALUE elem_to_ruby(bool v) { return v ? Qtrue : Qfalse; } +template <> VALUE elem_to_ruby(int8_t v) { return INT2FIX(v); } +template <> VALUE elem_to_ruby(int16_t v) { return INT2FIX(v); } +template <> VALUE elem_to_ruby(int32_t v) { return LONG2NUM(v); } +template <> VALUE elem_to_ruby(int64_t v) { return LL2NUM(v); } +template <> VALUE elem_to_ruby(uint8_t v) { return INT2FIX(v); } +template <> VALUE elem_to_ruby(uint16_t v) { return INT2FIX(v); } +template <> VALUE elem_to_ruby(uint32_t v) { return ULONG2NUM(v); } +template <> VALUE elem_to_ruby(uint64_t v) { return ULL2NUM(v); } + +// Exact nested-array shape inference AND full structural validation (no silent +// data loss on [[], [1, 2]] or [[], "x"], no bypass on [[1], [[2]]]). +// Does NOT allocate any C++ objects that could leak if rb_raise runs because +// we only call rb_raise AFTER returning an error code from pure C++ traversal! +int infer_and_validate_nested_c( + VALUE node, + size_t depth, + std::vector& shape, + bool& shape_locked, + std::string& err_msg) { + if (!RB_TYPE_P(node, T_ARRAY)) { + if (!shape_locked) { + shape_locked = true; + } else if (depth != shape.size()) { + err_msg = "inconsistent nesting depth at level " + std::to_string(depth) + + ": expected Array"; + return -1; + } + return 0; + } + + const long n = RARRAY_LEN(node); + if (!shape_locked && depth == shape.size()) { + shape.push_back(static_cast(n)); + } else if (depth >= shape.size()) { + err_msg = "unexpected nested Array at leaf depth " + std::to_string(depth); + return -1; + } else if (shape[depth] != static_cast(n)) { + err_msg = "jagged array at depth " + std::to_string(depth) + + ": expected size " + std::to_string(shape[depth]) + ", got " + + std::to_string(n); + return -1; + } + + if (n == 0) { + // An empty sub-array at depth d means every sibling at depth d MUST also be + // an empty Array (size 0), and no deeper dimension exists below it. + if (!shape_locked) { + shape_locked = true; + } else if (depth + 1 != shape.size()) { + err_msg = "jagged empty array at depth " + std::to_string(depth); + return -1; + } + return 0; + } + + for (long i = 0; i < n; ++i) { + VALUE child = rb_ary_entry(node, i); + if (infer_and_validate_nested_c(child, depth + 1, shape, shape_locked, err_msg) != 0) { + return -1; + } + } + return 0; +} + +// Reentrancy-safe single-pass write from nested or flat Ruby Array into raw +// typed buffer. Re-checks RARRAY_LEN on EVERY iteration in case a custom #to_f +// or #to_int mutates the Ruby Array! +// Protected wrapper ensures C++ locals are never leaked across rb_raise. +template +struct FillCtx { + VALUE root; + T* dst; + size_t cap; + size_t pos; + size_t target_depth; +}; + +template +VALUE fill_nested_body(VALUE arg) { + auto* ctx = reinterpret_cast*>(arg); + + auto walk = [&](auto& self, VALUE node, size_t depth) -> void { + if (depth == ctx->target_depth) { + if (RB_TYPE_P(node, T_ARRAY)) { + rb_raise(rb_eArgError, "unexpected Array at leaf level during fill"); + } + if (ctx->pos >= ctx->cap) { + rb_raise(rb_eArgError, "array grew during conversion"); + } + T val = ruby_to_elem(node); + ctx->dst[ctx->pos++] = val; + return; + } + if (!RB_TYPE_P(node, T_ARRAY)) { + rb_raise(rb_eArgError, "array mutated to non-Array during conversion"); + } + long len = RARRAY_LEN(node); + for (long i = 0; i < len; ++i) { + // Re-check length on every step: prevents OOB read if a custom coercion + // shrank `node` via `node.clear` or `node.pop`. + if (i >= RARRAY_LEN(node)) { + rb_raise(rb_eArgError, "array was mutated during conversion"); + } + VALUE elem = rb_ary_entry(node, i); + self(self, elem, depth + 1); + } + }; + + walk(walk, ctx->root, 0); + if (ctx->pos != ctx->cap) { + rb_raise( + rb_eArgError, + "data length (%zu) does not match shape element count (%zu)", + ctx->pos, + ctx->cap); + } + return Qnil; +} + +template +VALUE fill_flat_body(VALUE arg) { + auto* ctx = reinterpret_cast*>(arg); + if (!RB_TYPE_P(ctx->root, T_ARRAY)) { + if (ctx->cap != 1) { + rb_raise(rb_eArgError, "scalar data requires shape [] or [1]"); + } + ctx->dst[0] = ruby_to_elem(ctx->root); + ctx->pos = 1; + return Qnil; + } + long initial_len = RARRAY_LEN(ctx->root); + if (static_cast(initial_len) != ctx->cap) { + rb_raise( + g_refs.eShapeError, + "data length (%ld) does not match shape element count (%zu)", + initial_len, + ctx->cap); + } + for (long i = 0; i < initial_len; ++i) { + if (i >= RARRAY_LEN(ctx->root)) { + rb_raise(rb_eArgError, "array was mutated during conversion"); + } + VALUE elem = rb_ary_entry(ctx->root, i); + ctx->dst[i] = ruby_to_elem(elem); + } + ctx->pos = static_cast(initial_len); + return Qnil; +} + +// Dispatch typed fill inside rb_protect so AlignedBuffer is ALWAYS freed if +// Ruby raises TypeError/RangeError/FloatDomainError during element conversion! +int fill_buffer_protected( + VALUE data, + executorch::aten::ScalarType dtype, + void* dst, + size_t numel, + bool nested, + size_t target_depth) { + int state = 0; + switch (dtype) { +#define CASE_FILL(et_enum, name, ctype, sz) \ + case executorch::aten::ScalarType::et_enum: { \ + FillCtx ctx{data, static_cast(dst), numel, 0, target_depth}; \ + rb_protect( \ + nested ? fill_nested_body : fill_flat_body, \ + reinterpret_cast(&ctx), \ + &state); \ + break; \ + } + ETRB_FORALL_DTYPES(CASE_FILL) +#undef CASE_FILL + default: + state = -1; + break; + } + return state; +} + +// Recursively build nested Ruby Array directly from contiguous raw memory +// (zero intermediate flat array allocation, zero [result, offset] pairs!). +template +VALUE build_nested_ruby( + const T* base, + const executorch::aten::SizesType* sizes, + size_t ndim, + size_t dim, + size_t& offset) { + const long count = static_cast(sizes[dim]); + VALUE ary = rb_ary_new_capa(count); + if (dim + 1 == ndim) { + for (long i = 0; i < count; ++i) { + rb_ary_push(ary, elem_to_ruby(base[offset++])); + } + } else { + for (long i = 0; i < count; ++i) { + rb_ary_push(ary, build_nested_ruby(base, sizes, ndim, dim + 1, offset)); + } + } + return ary; +} + +VALUE build_ruby_from_contiguous( + const void* raw, + executorch::aten::ScalarType dtype, + const executorch::aten::SizesType* sizes, + size_t ndim, + size_t numel, + bool flat) { + if (ndim == 0) { + if (numel != 1) { + return Qnil; + } + switch (dtype) { +#define CASE_SCALAR(et_enum, name, ctype, sz) \ + case executorch::aten::ScalarType::et_enum: \ + return elem_to_ruby(*static_cast(raw)); + ETRB_FORALL_DTYPES(CASE_SCALAR) +#undef CASE_SCALAR + default: + rb_raise(g_refs.eDTypeError, "unsupported dtype for scalar extraction"); + } + } + + if (flat || ndim == 1) { + VALUE ary = rb_ary_new_capa(static_cast(numel)); + switch (dtype) { +#define CASE_FLAT(et_enum, name, ctype, sz) \ + case executorch::aten::ScalarType::et_enum: { \ + const auto* p = static_cast(raw); \ + for (size_t i = 0; i < numel; ++i) { \ + rb_ary_push(ary, elem_to_ruby(p[i])); \ + } \ + return ary; \ + } + ETRB_FORALL_DTYPES(CASE_FLAT) +#undef CASE_FLAT + default: + rb_raise(g_refs.eDTypeError, "unsupported dtype for to_a"); + } + } + + size_t offset = 0; + switch (dtype) { +#define CASE_NESTED(et_enum, name, ctype, sz) \ + case executorch::aten::ScalarType::et_enum: \ + return build_nested_ruby( \ + static_cast(raw), sizes, ndim, 0, offset); + ETRB_FORALL_DTYPES(CASE_NESTED) +#undef CASE_NESTED + default: + rb_raise(g_refs.eDTypeError, "unsupported dtype for to_a"); + } +} + +// Helper: parse dtype option (default :float32). +executorch::aten::ScalarType parse_dtype_opt(VALUE v) { + if (v == Qundef || v == Qnil) { + return executorch::aten::ScalarType::Float; + } + executorch::aten::ScalarType st = executorch::aten::ScalarType::Undefined; + if (!sym_to_scalar_type(v, &st)) { + if (!RB_SYMBOL_P(v)) { + rb_raise(rb_eTypeError, "dtype must be a Symbol"); + } + rb_raise(g_refs.eDTypeError, "unknown or unsupported dtype: :%s", rb_id2name(SYM2ID(v))); + } + return st; +} + +// --------------------------------------------------------------------------- +// Ruby methods for Executorch::Tensor +// --------------------------------------------------------------------------- + +// Tensor.new(data, shape: nil, dtype: :float32) +VALUE rb_tensor_s_new(int argc, VALUE* argv, VALUE klass) { + VALUE data = Qnil; + VALUE opts = Qnil; + rb_scan_args(argc, argv, "1:", &data, &opts); + + VALUE kw_vals[2] = {Qundef, Qundef}; + ID kw_ids[2] = {g_refs.id_kw_shape, g_refs.id_kw_dtype}; + if (!NIL_P(opts)) { + rb_get_kwargs(opts, kw_ids, 0, 2, kw_vals); + } + VALUE shape_val = kw_vals[0]; + VALUE dtype_val = kw_vals[1]; + + const auto dtype = parse_dtype_opt(dtype_val); + const bool explicit_shape = (shape_val != Qundef && shape_val != Qnil); + + VALUE err_exc = Qnil; + VALUE result = Qnil; + int protect_state = 0; + + { + std::vector raw_dims; + bool nested = false; + size_t target_depth = 0; + + if (explicit_shape) { + if (!RB_TYPE_P(shape_val, T_ARRAY)) { + err_exc = rb_exc_new_cstr(rb_eTypeError, "shape must be an Array of Integers"); + } else { + // Reentrancy-safe shape extraction inside rb_protect. + struct ShapeArg { + VALUE ary; + std::vector* dims; + } sa{shape_val, &raw_dims}; + rb_protect( + [](VALUE a) -> VALUE { + auto* s = reinterpret_cast(a); + parse_ruby_shape(s->ary, s->dims); + return Qnil; + }, + reinterpret_cast(&sa), + &protect_state); + } + } else { + if (RB_TYPE_P(data, T_ARRAY)) { + bool locked = false; + std::string err_msg; + if (infer_and_validate_nested_c(data, 0, raw_dims, locked, err_msg) != 0) { + err_exc = rb_exc_new_str( + rb_eArgError, + rb_utf8_str_new(err_msg.data(), static_cast(err_msg.size()))); + } else { + nested = true; + target_depth = raw_dims.size(); + } + } else if (RB_INTEGER_TYPE_P(data) || RB_FLOAT_TYPE_P(data) || + data == Qtrue || data == Qfalse || + rb_respond_to(data, rb_intern("to_f"))) { + // 0-D scalar tensor! + raw_dims.clear(); + nested = false; + } else { + err_exc = rb_exc_new_cstr( + rb_eTypeError, "Tensor data must be an Array or scalar Numeric/Boolean"); + } + } + + if (protect_state == 0 && err_exc == Qnil) { + auto shape_res = validate_shape(raw_dims, dtype); + if (!shape_res.ok()) { + err_exc = status_to_ruby_exception(shape_res.status); + } else { + auto buf_res = AlignedBuffer::allocate(shape_res.value.nbytes); + if (!buf_res.ok()) { + err_exc = status_to_ruby_exception(buf_res.status); + } else { + // If explicit shape was passed with a nested array, validate & flatten cleanly! + if (explicit_shape && RB_TYPE_P(data, T_ARRAY) && + RARRAY_LEN(data) > 0 && RB_TYPE_P(rb_ary_entry(data, 0), T_ARRAY)) { + std::vector inferred; + bool locked = false; + std::string err_msg; + if (infer_and_validate_nested_c(data, 0, inferred, locked, err_msg) != 0) { + err_exc = rb_exc_new_str( + rb_eArgError, + rb_utf8_str_new(err_msg.data(), static_cast(err_msg.size()))); + } else { + nested = true; + target_depth = inferred.size(); + } + } + + if (err_exc == Qnil) { + protect_state = fill_buffer_protected( + data, + dtype, + buf_res.value.ptr, + shape_res.value.numel, + nested, + target_depth); + } + + if (protect_state == 0 && err_exc == Qnil) { + auto tp_res = make_owned_tensor_ptr( + std::move(shape_res.value.sizes), dtype, std::move(buf_res.value)); + if (!tp_res.ok()) { + err_exc = status_to_ruby_exception(tp_res.status); + } else { + result = wrap_owned_tensor(std::move(tp_res.value)); + (void)klass; + } + } + } + } + } + } // All C++ locals destroyed here! + + if (protect_state != 0) { + rb_jump_tag(protect_state); + } + if (err_exc != Qnil) { + raise_status_no_live_cpp(err_exc); + } + return result; +} + +// Tensor.from_bytes(str, shape:, dtype: :float32) +VALUE rb_tensor_s_from_bytes(int argc, VALUE* argv, VALUE klass) { + (void)klass; + VALUE bytes_val = Qnil; + VALUE opts = Qnil; + rb_scan_args(argc, argv, "1:", &bytes_val, &opts); + Check_Type(bytes_val, T_STRING); + + VALUE kw_vals[2] = {Qundef, Qundef}; + ID kw_ids[2] = {g_refs.id_kw_shape, g_refs.id_kw_dtype}; + if (NIL_P(opts)) { + rb_raise(rb_eArgError, "missing keyword: :shape"); + } + rb_get_kwargs(opts, kw_ids, 1, 1, kw_vals); + + VALUE shape_val = kw_vals[0]; + const auto dtype = parse_dtype_opt(kw_vals[1]); + Check_Type(shape_val, T_ARRAY); + + VALUE err_exc = Qnil; + VALUE result = Qnil; + int protect_state = 0; + + { + std::vector raw_dims; + struct ShapeArg { + VALUE ary; + std::vector* dims; + } sa{shape_val, &raw_dims}; + rb_protect( + [](VALUE a) -> VALUE { + auto* s = reinterpret_cast(a); + parse_ruby_shape(s->ary, s->dims); + return Qnil; + }, + reinterpret_cast(&sa), + &protect_state); + + if (protect_state == 0) { + auto shape_res = validate_shape(raw_dims, dtype); + if (!shape_res.ok()) { + err_exc = status_to_ruby_exception(shape_res.status); + } else { + const size_t actual = static_cast(RSTRING_LEN(bytes_val)); + const size_t expected = shape_res.value.nbytes; + if (actual != expected) { + std::string msg = "byte length mismatch: expected " + + std::to_string(expected) + " bytes, got " + + std::to_string(actual); + err_exc = rb_exc_new_str( + g_refs.eShapeError, + rb_utf8_str_new(msg.data(), static_cast(msg.size()))); + } else { + auto buf_res = AlignedBuffer::allocate(expected); + if (!buf_res.ok()) { + err_exc = status_to_ruby_exception(buf_res.status); + } else { + if (expected > 0) { + std::memcpy(buf_res.value.ptr, RSTRING_PTR(bytes_val), expected); + } + auto tp_res = make_owned_tensor_ptr( + std::move(shape_res.value.sizes), dtype, std::move(buf_res.value)); + if (!tp_res.ok()) { + err_exc = status_to_ruby_exception(tp_res.status); + } else { + result = wrap_owned_tensor(std::move(tp_res.value)); + } + } + } + } + } + } // All C++ locals destroyed here! + + RB_GC_GUARD(bytes_val); + if (protect_state != 0) { + rb_jump_tag(protect_state); + } + if (err_exc != Qnil) { + raise_status_no_live_cpp(err_exc); + } + return result; +} + +// Tensor.from_buffer(io_buffer, shape:, dtype: :float32) — zero-copy view! +VALUE rb_tensor_s_from_buffer(int argc, VALUE* argv, VALUE klass) { + VALUE buf_val = Qnil; + VALUE opts = Qnil; + rb_scan_args(argc, argv, "1:", &buf_val, &opts); + + if (!rb_obj_is_kind_of(buf_val, rb_cIOBuffer)) { + rb_raise(rb_eTypeError, "expected an IO::Buffer"); + } + if (NIL_P(opts)) { + rb_raise(rb_eArgError, "missing keyword: :shape"); + } + VALUE kw_vals[2] = {Qundef, Qundef}; + ID kw_ids[2] = {g_refs.id_kw_shape, g_refs.id_kw_dtype}; + rb_get_kwargs(opts, kw_ids, 1, 1, kw_vals); + + VALUE shape_val = kw_vals[0]; + const auto dtype = parse_dtype_opt(kw_vals[1]); + Check_Type(shape_val, T_ARRAY); + + const void* ptr = nullptr; + size_t actual = 0; + rb_io_buffer_get_bytes_for_reading(buf_val, &ptr, &actual); + + VALUE err_exc = Qnil; + VALUE result = Qnil; + int protect_state = 0; + + { + std::vector raw_dims; + struct ShapeArg { + VALUE ary; + std::vector* dims; + } sa{shape_val, &raw_dims}; + rb_protect( + [](VALUE a) -> VALUE { + auto* s = reinterpret_cast(a); + parse_ruby_shape(s->ary, s->dims); + return Qnil; + }, + reinterpret_cast(&sa), + &protect_state); + + if (protect_state == 0) { + auto shape_res = validate_shape(raw_dims, dtype); + if (!shape_res.ok()) { + err_exc = status_to_ruby_exception(shape_res.status); + } else if (actual != shape_res.value.nbytes) { + std::string msg = "IO::Buffer byte length mismatch: expected " + + std::to_string(shape_res.value.nbytes) + + " bytes, got " + std::to_string(actual); + err_exc = rb_exc_new_str( + g_refs.eShapeError, + rb_utf8_str_new(msg.data(), static_cast(msg.size()))); + } else { + result = tensor_alloc(klass); + RbTensorWrap* wrap = nullptr; + TypedData_Get_Struct(result, RbTensorWrap, &kTensorDataType, wrap); + wrap->borrowed_buf = buf_val; + wrap->borrowed_sizes = std::move(shape_res.value.sizes); + wrap->borrowed_dtype = dtype; + wrap->borrowed_nbytes = shape_res.value.nbytes; + } + } + } + + if (protect_state != 0) { + rb_jump_tag(protect_state); + } + if (err_exc != Qnil) { + raise_status_no_live_cpp(err_exc); + } + return result; +} + +// Tensor.zeros(shape, dtype: :float32) +VALUE rb_tensor_s_zeros(int argc, VALUE* argv, VALUE klass) { + (void)klass; + VALUE shape_val = Qnil; + VALUE opts = Qnil; + rb_scan_args(argc, argv, "1:", &shape_val, &opts); + Check_Type(shape_val, T_ARRAY); + + VALUE kw_vals[1] = {Qundef}; + ID kw_ids[1] = {g_refs.id_kw_dtype}; + if (!NIL_P(opts)) { + rb_get_kwargs(opts, kw_ids, 0, 1, kw_vals); + } + const auto dtype = parse_dtype_opt(kw_vals[0]); + + VALUE err_exc = Qnil; + VALUE result = Qnil; + int protect_state = 0; + + { + std::vector raw_dims; + struct ShapeArg { + VALUE ary; + std::vector* dims; + } sa{shape_val, &raw_dims}; + rb_protect( + [](VALUE a) -> VALUE { + auto* s = reinterpret_cast(a); + parse_ruby_shape(s->ary, s->dims); + return Qnil; + }, + reinterpret_cast(&sa), + &protect_state); + + if (protect_state == 0) { + auto shape_res = validate_shape(raw_dims, dtype); + if (!shape_res.ok()) { + err_exc = status_to_ruby_exception(shape_res.status); + } else { + auto buf_res = AlignedBuffer::allocate_zeroed(shape_res.value.nbytes); + if (!buf_res.ok()) { + err_exc = status_to_ruby_exception(buf_res.status); + } else { + auto tp_res = make_owned_tensor_ptr( + std::move(shape_res.value.sizes), dtype, std::move(buf_res.value)); + if (!tp_res.ok()) { + err_exc = status_to_ruby_exception(tp_res.status); + } else { + result = wrap_owned_tensor(std::move(tp_res.value)); + } + } + } + } + } + + if (protect_state != 0) { + rb_jump_tag(protect_state); + } + if (err_exc != Qnil) { + raise_status_no_live_cpp(err_exc); + } + return result; +} + +VALUE rb_tensor_shape(VALUE self) { + auto* wrap = check_open_tensor(self); + if (wrap->borrowed_buf != Qnil) { + VALUE ary = rb_ary_new_capa(static_cast(wrap->borrowed_sizes.size())); + for (auto d : wrap->borrowed_sizes) { + rb_ary_push(ary, LONG2NUM(d)); + } + return ary; + } + const auto sizes = wrap->tensor->sizes(); + VALUE ary = rb_ary_new_capa(static_cast(sizes.size())); + for (auto d : sizes) { + rb_ary_push(ary, LONG2NUM(d)); + } + return ary; +} + +VALUE rb_tensor_strides(VALUE self) { + auto* wrap = check_open_tensor(self); + if (wrap->borrowed_buf != Qnil) { + const size_t ndim = wrap->borrowed_sizes.size(); + VALUE ary = rb_ary_new_capa(static_cast(ndim)); + if (ndim == 0) return ary; + std::vector st(ndim, 1); + for (size_t i = ndim - 1; i > 0; --i) { + st[i - 1] = st[i] * static_cast(wrap->borrowed_sizes[i]); + } + for (auto s : st) { + rb_ary_push(ary, LL2NUM(s)); + } + return ary; + } + const auto strides = wrap->tensor->strides(); + VALUE ary = rb_ary_new_capa(static_cast(strides.size())); + for (auto s : strides) { + rb_ary_push(ary, LONG2NUM(s)); + } + return ary; +} + +VALUE rb_tensor_dim_order(VALUE self) { + auto* wrap = check_open_tensor(self); + if (wrap->borrowed_buf != Qnil) { + const size_t ndim = wrap->borrowed_sizes.size(); + VALUE ary = rb_ary_new_capa(static_cast(ndim)); + for (size_t i = 0; i < ndim; ++i) { + rb_ary_push(ary, ULONG2NUM(i)); + } + return ary; + } + const auto order = wrap->tensor->dim_order(); + VALUE ary = rb_ary_new_capa(static_cast(order.size())); + for (auto o : order) { + rb_ary_push(ary, INT2FIX(o)); + } + return ary; +} + +VALUE rb_tensor_contiguous_p(VALUE self) { + auto* wrap = check_open_tensor(self); + if (wrap->borrowed_buf != Qnil) { + return Qtrue; + } + return is_standard_contiguous(*wrap->tensor) ? Qtrue : Qfalse; +} + +VALUE rb_tensor_dim(VALUE self) { + auto* wrap = check_open_tensor(self); + if (wrap->borrowed_buf != Qnil) { + return LONG2NUM(static_cast(wrap->borrowed_sizes.size())); + } + return LONG2NUM(wrap->tensor->dim()); +} + +VALUE rb_tensor_numel(VALUE self) { + auto* wrap = check_open_tensor(self); + if (wrap->borrowed_buf != Qnil) { + size_t item_sz = scalar_type_size(wrap->borrowed_dtype); + return ULL2NUM(item_sz == 0 ? 0 : wrap->borrowed_nbytes / item_sz); + } + return LL2NUM(wrap->tensor->numel()); +} + +VALUE rb_tensor_nbytes(VALUE self) { + auto* wrap = check_open_tensor(self); + if (wrap->borrowed_buf != Qnil) { + return ULL2NUM(wrap->borrowed_nbytes); + } + return ULL2NUM(wrap->tensor->nbytes()); +} + +VALUE rb_tensor_dtype(VALUE self) { + auto* wrap = check_open_tensor(self); + auto st = (wrap->borrowed_buf != Qnil) ? wrap->borrowed_dtype + : wrap->tensor->scalar_type(); + return scalar_type_to_sym(st); +} + +VALUE rb_tensor_to_bytes(VALUE self) { + auto* wrap = check_open_tensor(self); + if (wrap->borrowed_buf != Qnil) { + const void* ptr = nullptr; + size_t len = 0; + check_borrowed_read(wrap, &ptr, &len); + VALUE str = rb_str_buf_new(static_cast(len)); + if (len > 0) { + rb_str_cat(str, static_cast(ptr), static_cast(len)); + } + RB_GC_GUARD(self); + return str; + } + + const auto& t = *wrap->tensor; + const size_t nbytes = t.nbytes(); + if (nbytes > static_cast(std::numeric_limits::max())) { + rb_raise(g_refs.eMemoryError, "tensor too large for Ruby String"); + } + VALUE str = rb_str_new(nullptr, static_cast(nbytes)); + VALUE err_exc = Qnil; + { + auto st = copy_to_contiguous_bytes(t, RSTRING_PTR(str), nbytes); + if (!st.ok()) { + err_exc = status_to_ruby_exception(st); + } + } + RB_GC_GUARD(self); + if (err_exc != Qnil) { + raise_status_no_live_cpp(err_exc); + } + return str; +} + +VALUE rb_tensor_to_buffer(VALUE self) { + auto* wrap = check_open_tensor(self); + size_t nbytes = 0; + if (wrap->borrowed_buf != Qnil) { + const void* src = nullptr; + check_borrowed_read(wrap, &src, &nbytes); + VALUE io_buf = rb_io_buffer_new(nullptr, nbytes, RB_IO_BUFFER_INTERNAL); + if (nbytes > 0) { + void* dst = nullptr; + size_t dst_len = 0; + rb_io_buffer_get_bytes_for_writing(io_buf, &dst, &dst_len); + std::memcpy(dst, src, nbytes); + } + RB_GC_GUARD(self); + return io_buf; + } + + const auto& t = *wrap->tensor; + nbytes = t.nbytes(); + VALUE io_buf = rb_io_buffer_new(nullptr, nbytes, RB_IO_BUFFER_INTERNAL); + VALUE err_exc = Qnil; + if (nbytes > 0) { + void* dst = nullptr; + size_t dst_len = 0; + rb_io_buffer_get_bytes_for_writing(io_buf, &dst, &dst_len); + auto st = copy_to_contiguous_bytes(t, dst, nbytes); + if (!st.ok()) { + err_exc = status_to_ruby_exception(st); + } + } + RB_GC_GUARD(self); + if (err_exc != Qnil) { + raise_status_no_live_cpp(err_exc); + } + return io_buf; +} + +static VALUE tensor_to_a_impl(VALUE self, bool flat) { + auto* wrap = check_open_tensor(self); + if (wrap->borrowed_buf != Qnil) { + const void* ptr = nullptr; + size_t len = 0; + check_borrowed_read(wrap, &ptr, &len); + const size_t item_sz = scalar_type_size(wrap->borrowed_dtype); + const size_t numel = item_sz == 0 ? 0 : len / item_sz; + VALUE out = build_ruby_from_contiguous( + ptr, + wrap->borrowed_dtype, + wrap->borrowed_sizes.data(), + wrap->borrowed_sizes.size(), + numel, + flat); + RB_GC_GUARD(self); + return out; + } + + const auto& t = *wrap->tensor; + const size_t numel = static_cast(t.numel()); + const size_t ndim = static_cast(t.dim()); + + if (is_standard_contiguous(t)) { + VALUE out = build_ruby_from_contiguous( + t.const_data_ptr(), + t.scalar_type(), + t.sizes().data(), + ndim, + numel, + flat); + RB_GC_GUARD(self); + return out; + } + + // Non-contiguous: copy into temporary contiguous buffer first, then convert + // inside rb_protect so buffer is always released if Ruby raises OOM. + VALUE err_exc = Qnil; + VALUE out = Qnil; + int protect_state = 0; + { + auto buf_res = AlignedBuffer::allocate(t.nbytes()); + if (!buf_res.ok()) { + err_exc = status_to_ruby_exception(buf_res.status); + } else { + auto cp = copy_to_contiguous_bytes(t, buf_res.value.ptr, t.nbytes()); + if (!cp.ok()) { + err_exc = status_to_ruby_exception(cp); + } else { + struct BuildArg { + const void* raw; + executorch::aten::ScalarType dtype; + const executorch::aten::SizesType* sizes; + size_t ndim; + size_t numel; + bool flat; + } ba{buf_res.value.ptr, t.scalar_type(), t.sizes().data(), ndim, numel, flat}; + out = rb_protect( + [](VALUE a) -> VALUE { + auto* b = reinterpret_cast(a); + return build_ruby_from_contiguous( + b->raw, b->dtype, b->sizes, b->ndim, b->numel, b->flat); + }, + reinterpret_cast(&ba), + &protect_state); + } + } + } + RB_GC_GUARD(self); + if (protect_state != 0) rb_jump_tag(protect_state); + if (err_exc != Qnil) raise_status_no_live_cpp(err_exc); + return out; +} + +VALUE rb_tensor_to_a(VALUE self) { return tensor_to_a_impl(self, false); } +VALUE rb_tensor_flat_to_a(VALUE self) { return tensor_to_a_impl(self, true); } + +VALUE rb_tensor_item(VALUE self) { + auto* wrap = check_open_tensor(self); + const size_t numel = (wrap->borrowed_buf != Qnil) + ? (wrap->borrowed_nbytes / + std::max(1, scalar_type_size(wrap->borrowed_dtype))) + : static_cast(wrap->tensor->numel()); + if (numel != 1) { + rb_raise( + g_refs.eShapeError, + "item requires a tensor with exactly 1 element, got %zu", + numel); + } + const void* ptr = nullptr; + executorch::aten::ScalarType dtype = executorch::aten::ScalarType::Undefined; + if (wrap->borrowed_buf != Qnil) { + size_t len = 0; + check_borrowed_read(wrap, &ptr, &len); + dtype = wrap->borrowed_dtype; + } else { + ptr = wrap->tensor->const_data_ptr(); + dtype = wrap->tensor->scalar_type(); + } + VALUE out = build_ruby_from_contiguous(ptr, dtype, nullptr, 0, 1, true); + RB_GC_GUARD(self); + return out; +} + +VALUE rb_tensor_close(VALUE self) { + RbTensorWrap* wrap = nullptr; + TypedData_Get_Struct(self, RbTensorWrap, &kTensorDataType, wrap); + if (wrap != nullptr && !wrap->closed) { + wrap->closed = true; + wrap->tensor.reset(); + wrap->borrowed_buf = Qnil; + wrap->borrowed_sizes.clear(); + if (wrap->tracked_bytes > 0) { + rb_gc_adjust_memory_usage(-static_cast(wrap->tracked_bytes)); + wrap->tracked_bytes = 0; + } + } + return Qnil; +} + +VALUE rb_tensor_closed_p(VALUE self) { + RbTensorWrap* wrap = nullptr; + TypedData_Get_Struct(self, RbTensorWrap, &kTensorDataType, wrap); + return (wrap == nullptr || wrap->closed) ? Qtrue : Qfalse; +} + +VALUE rb_tensor_eq(VALUE self, VALUE other) { + if (!is_rb_tensor(other)) { + return Qfalse; + } + auto* a = check_open_tensor(self); + auto* b = check_open_tensor(other); + if (a == b) return Qtrue; + + const auto dtype_a = (a->borrowed_buf != Qnil) ? a->borrowed_dtype : a->tensor->scalar_type(); + const auto dtype_b = (b->borrowed_buf != Qnil) ? b->borrowed_dtype : b->tensor->scalar_type(); + if (dtype_a != dtype_b) return Qfalse; + + const executorch::aten::SizesType* sa = + (a->borrowed_buf != Qnil) ? a->borrowed_sizes.data() : a->tensor->sizes().data(); + const size_t da = + (a->borrowed_buf != Qnil) ? a->borrowed_sizes.size() : static_cast(a->tensor->dim()); + const executorch::aten::SizesType* sb = + (b->borrowed_buf != Qnil) ? b->borrowed_sizes.data() : b->tensor->sizes().data(); + const size_t db = + (b->borrowed_buf != Qnil) ? b->borrowed_sizes.size() : static_cast(b->tensor->dim()); + if (da != db) return Qfalse; + for (size_t i = 0; i < da; ++i) { + if (sa[i] != sb[i]) return Qfalse; + } + + VALUE ba = rb_tensor_to_bytes(self); + VALUE bb = rb_tensor_to_bytes(other); + if (RSTRING_LEN(ba) != RSTRING_LEN(bb)) return Qfalse; + const size_t n = static_cast(RSTRING_LEN(ba)); + if (n == 0) return Qtrue; + bool eq = (std::memcmp(RSTRING_PTR(ba), RSTRING_PTR(bb), n) == 0); + RB_GC_GUARD(ba); + RB_GC_GUARD(bb); + return eq ? Qtrue : Qfalse; +} + +} // namespace + +const rb_data_type_t kTensorDataType = { + "Executorch::Tensor", + { + tensor_mark, + tensor_free, + tensor_memsize, + nullptr, + {nullptr}, + }, + nullptr, + nullptr, + RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_FROZEN_SHAREABLE, +}; + +VALUE wrap_owned_tensor(executorch::extension::TensorPtr ptr) { + VALUE obj = tensor_alloc(g_refs.cTensor); + RbTensorWrap* wrap = nullptr; + TypedData_Get_Struct(obj, RbTensorWrap, &kTensorDataType, wrap); + const size_t nb = ptr ? ptr->nbytes() : 0; + wrap->tensor = std::move(ptr); + wrap->tracked_bytes = nb; + if (nb > 0) { + rb_gc_adjust_memory_usage(static_cast(nb)); + } + return obj; +} + +bool is_rb_tensor(VALUE obj) { + return rb_typeddata_is_kind_of(obj, &kTensorDataType) != 0; +} + +RbTensorWrap* get_rb_tensor(VALUE obj) { + return check_open_tensor(obj); +} + +VALUE scalar_type_to_sym(executorch::aten::ScalarType st) { + switch (st) { + case executorch::aten::ScalarType::Float: return ID2SYM(g_refs.id_float32); + case executorch::aten::ScalarType::Double: return ID2SYM(g_refs.id_float64); + case executorch::aten::ScalarType::Half: return ID2SYM(g_refs.id_float16); + case executorch::aten::ScalarType::BFloat16: return ID2SYM(g_refs.id_bfloat16); + case executorch::aten::ScalarType::Byte: return ID2SYM(g_refs.id_uint8); + case executorch::aten::ScalarType::Char: return ID2SYM(g_refs.id_int8); + case executorch::aten::ScalarType::Short: return ID2SYM(g_refs.id_int16); + case executorch::aten::ScalarType::UInt16: return ID2SYM(g_refs.id_uint16); + case executorch::aten::ScalarType::Int: return ID2SYM(g_refs.id_int32); + case executorch::aten::ScalarType::UInt32: return ID2SYM(g_refs.id_uint32); + case executorch::aten::ScalarType::Long: return ID2SYM(g_refs.id_int64); + case executorch::aten::ScalarType::UInt64: return ID2SYM(g_refs.id_uint64); + case executorch::aten::ScalarType::Bool: return ID2SYM(g_refs.id_bool); + default: return ID2SYM(rb_intern(scalar_type_name(st))); + } +} + +bool sym_to_scalar_type(VALUE sym, executorch::aten::ScalarType* out) { + if (!RB_SYMBOL_P(sym)) { + return false; + } + ID id = SYM2ID(sym); + if (id == g_refs.id_float32) { *out = executorch::aten::ScalarType::Float; return true; } + if (id == g_refs.id_float64) { *out = executorch::aten::ScalarType::Double; return true; } + if (id == g_refs.id_int64) { *out = executorch::aten::ScalarType::Long; return true; } + if (id == g_refs.id_int32) { *out = executorch::aten::ScalarType::Int; return true; } + if (id == g_refs.id_uint8) { *out = executorch::aten::ScalarType::Byte; return true; } + if (id == g_refs.id_bool) { *out = executorch::aten::ScalarType::Bool; return true; } + if (id == g_refs.id_float16) { *out = executorch::aten::ScalarType::Half; return true; } + if (id == g_refs.id_bfloat16) { *out = executorch::aten::ScalarType::BFloat16; return true; } + if (id == g_refs.id_int8) { *out = executorch::aten::ScalarType::Char; return true; } + if (id == g_refs.id_int16) { *out = executorch::aten::ScalarType::Short; return true; } + if (id == g_refs.id_uint16) { *out = executorch::aten::ScalarType::UInt16; return true; } + if (id == g_refs.id_uint32) { *out = executorch::aten::ScalarType::UInt32; return true; } + if (id == g_refs.id_uint64) { *out = executorch::aten::ScalarType::UInt64; return true; } + const char* name = rb_id2name(id); + return name != nullptr && parse_dtype_name(name, out); +} + +void init_tensor(VALUE mExecutorch) { + g_refs.id_float32 = rb_intern("float32"); + g_refs.id_float64 = rb_intern("float64"); + g_refs.id_float16 = rb_intern("float16"); + g_refs.id_bfloat16 = rb_intern("bfloat16"); + g_refs.id_uint8 = rb_intern("uint8"); + g_refs.id_int8 = rb_intern("int8"); + g_refs.id_int16 = rb_intern("int16"); + g_refs.id_uint16 = rb_intern("uint16"); + g_refs.id_int32 = rb_intern("int32"); + g_refs.id_uint32 = rb_intern("uint32"); + g_refs.id_int64 = rb_intern("int64"); + g_refs.id_uint64 = rb_intern("uint64"); + g_refs.id_bool = rb_intern("bool"); + g_refs.id_unknown = rb_intern("unknown"); + g_refs.id_kw_shape = rb_intern("shape"); + g_refs.id_kw_dtype = rb_intern("dtype"); + + g_refs.cTensor = rb_define_class_under(mExecutorch, "Tensor", rb_cObject); + rb_global_variable(&g_refs.cTensor); + rb_undef_alloc_func(g_refs.cTensor); + + rb_define_singleton_method(g_refs.cTensor, "new", rb_tensor_s_new, -1); + rb_define_singleton_method(g_refs.cTensor, "from_bytes", rb_tensor_s_from_bytes, -1); + rb_define_singleton_method(g_refs.cTensor, "from_buffer", rb_tensor_s_from_buffer, -1); + rb_define_singleton_method(g_refs.cTensor, "zeros", rb_tensor_s_zeros, -1); + + rb_define_method(g_refs.cTensor, "shape", rb_tensor_shape, 0); + rb_define_method(g_refs.cTensor, "strides", rb_tensor_strides, 0); + rb_define_method(g_refs.cTensor, "dim_order", rb_tensor_dim_order, 0); + rb_define_method(g_refs.cTensor, "contiguous?", rb_tensor_contiguous_p, 0); + rb_define_method(g_refs.cTensor, "dim", rb_tensor_dim, 0); + rb_define_method(g_refs.cTensor, "ndim", rb_tensor_dim, 0); + rb_define_method(g_refs.cTensor, "numel", rb_tensor_numel, 0); + rb_define_method(g_refs.cTensor, "nbytes", rb_tensor_nbytes, 0); + rb_define_method(g_refs.cTensor, "dtype", rb_tensor_dtype, 0); + rb_define_method(g_refs.cTensor, "to_a", rb_tensor_to_a, 0); + rb_define_method(g_refs.cTensor, "flat_to_a", rb_tensor_flat_to_a, 0); + rb_define_method(g_refs.cTensor, "to_bytes", rb_tensor_to_bytes, 0); + rb_define_method(g_refs.cTensor, "to_buffer", rb_tensor_to_buffer, 0); + rb_define_method(g_refs.cTensor, "item", rb_tensor_item, 0); + rb_define_method(g_refs.cTensor, "close", rb_tensor_close, 0); + rb_define_method(g_refs.cTensor, "closed?", rb_tensor_closed_p, 0); + rb_define_method(g_refs.cTensor, "==", rb_tensor_eq, 1); +} + +} // namespace etrb diff --git a/ext/executorch/utils.h b/ext/executorch/utils.h deleted file mode 100644 index a19a27e..0000000 --- a/ext/executorch/utils.h +++ /dev/null @@ -1,140 +0,0 @@ -#ifndef EXECUTORCH_RUBY_UTILS_H -#define EXECUTORCH_RUBY_UTILS_H - -#include -#include -#include -#include - -// Error handling macros - translate C++ exceptions to Ruby exceptions -#define HANDLE_ET_ERRORS try { - -#define END_HANDLE_ET_ERRORS \ - } \ - catch (const Rice::Exception &ex) { \ - throw; \ - } \ - catch (const std::exception &ex) { \ - rb_raise(rb_eRuntimeError, "ExecuTorch error: %s", ex.what()); \ - } - -namespace executorch_ruby { - -inline void check_error(executorch::runtime::Error error) { - if (error != executorch::runtime::Error::Ok) { - const char* error_name = "Unknown error"; - switch (error) { - case executorch::runtime::Error::Ok: - return; - case executorch::runtime::Error::Internal: - error_name = "Internal error"; - break; - case executorch::runtime::Error::InvalidState: - error_name = "Invalid state"; - break; - case executorch::runtime::Error::InvalidArgument: - error_name = "Invalid argument"; - break; - case executorch::runtime::Error::InvalidType: - error_name = "Invalid type"; - break; - case executorch::runtime::Error::NotFound: - error_name = "Not found"; - break; - case executorch::runtime::Error::MemoryAllocationFailed: - error_name = "Memory allocation failed"; - break; - case executorch::runtime::Error::AccessFailed: - error_name = "Access failed"; - break; - case executorch::runtime::Error::NotSupported: - error_name = "Not supported"; - break; - case executorch::runtime::Error::DelegateInvalidCompatibility: - error_name = "Delegate invalid compatibility"; - break; - case executorch::runtime::Error::DelegateMemoryAllocationFailed: - error_name = "Delegate memory allocation failed"; - break; - case executorch::runtime::Error::DelegateInvalidHandle: - error_name = "Delegate invalid handle"; - break; - default: - error_name = "Unknown error"; - break; - } - rb_raise(rb_eRuntimeError, "ExecuTorch error: %s", error_name); - } -} - -// Helper to unwrap Result and raise Ruby exception on error -template -T unwrap_result(executorch::runtime::Result&& result) { - if (!result.ok()) { - check_error(result.error()); - // Should never reach here, but just in case - rb_raise(rb_eRuntimeError, "ExecuTorch: unexpected error"); - } - return std::move(result.get()); -} - -// Convert ExecuTorch ScalarType to Ruby symbol -// Uses short names (:int, :long, :float) to match input symbols -inline VALUE scalar_type_to_symbol(executorch::aten::ScalarType dtype) { - switch (dtype) { - case executorch::aten::ScalarType::Byte: - return ID2SYM(rb_intern("byte")); - case executorch::aten::ScalarType::Char: - return ID2SYM(rb_intern("char")); - case executorch::aten::ScalarType::Short: - return ID2SYM(rb_intern("short")); - case executorch::aten::ScalarType::Int: - return ID2SYM(rb_intern("int")); - case executorch::aten::ScalarType::Long: - return ID2SYM(rb_intern("long")); - case executorch::aten::ScalarType::Half: - return ID2SYM(rb_intern("half")); - case executorch::aten::ScalarType::Float: - return ID2SYM(rb_intern("float")); - case executorch::aten::ScalarType::Double: - return ID2SYM(rb_intern("double")); - case executorch::aten::ScalarType::Bool: - return ID2SYM(rb_intern("bool")); - default: - return ID2SYM(rb_intern("unknown")); - } -} - -inline executorch::aten::ScalarType symbol_to_scalar_type(VALUE sym) { - if (!RB_TYPE_P(sym, T_SYMBOL)) { - rb_raise(rb_eTypeError, "Expected Symbol for dtype"); - } - - ID id = SYM2ID(sym); - - if (id == rb_intern("uint8") || id == rb_intern("byte")) { - return executorch::aten::ScalarType::Byte; - } else if (id == rb_intern("int8") || id == rb_intern("char")) { - return executorch::aten::ScalarType::Char; - } else if (id == rb_intern("int16") || id == rb_intern("short")) { - return executorch::aten::ScalarType::Short; - } else if (id == rb_intern("int32") || id == rb_intern("int")) { - return executorch::aten::ScalarType::Int; - } else if (id == rb_intern("int64") || id == rb_intern("long")) { - return executorch::aten::ScalarType::Long; - } else if (id == rb_intern("float16") || id == rb_intern("half")) { - return executorch::aten::ScalarType::Half; - } else if (id == rb_intern("float32") || id == rb_intern("float")) { - return executorch::aten::ScalarType::Float; - } else if (id == rb_intern("float64") || id == rb_intern("double")) { - return executorch::aten::ScalarType::Double; - } else if (id == rb_intern("bool")) { - return executorch::aten::ScalarType::Bool; - } else { - rb_raise(rb_eArgError, "Unknown dtype: %s", rb_id2name(id)); - } -} - -} // namespace executorch_ruby - -#endif // EXECUTORCH_RUBY_UTILS_H diff --git a/lib/executorch.rb b/lib/executorch.rb index c5d5af5..9d7f26a 100644 --- a/lib/executorch.rb +++ b/lib/executorch.rb @@ -1,212 +1,16 @@ # frozen_string_literal: true require_relative "executorch/version" +require_relative "executorch/method_meta" -# Load the native extension +# Load precompiled Ruby-version-specific native extension first (fat gems), +# falling back to standard single-version native extension path. begin + ruby_abi = RUBY_VERSION[/\A\d+\.\d+/] + require_relative "executorch/#{ruby_abi}/executorch" +rescue LoadError require_relative "executorch/executorch" -rescue LoadError => e - warn "Failed to load ExecuTorch native extension: #{e.message}" - warn "Make sure to run: bundle exec rake compile" - raise end -module Executorch - # Extend Tensor with Ruby-friendly methods - class Tensor - class << self - # Create a new tensor from data - # - # @param data [Array] Array of numeric values (can be nested or flat) - # @param shape [Array, nil] Shape of the tensor. If nil, inferred from data structure. - # @param dtype [Symbol] Data type (:float, :double, :int, :long) - # @return [Tensor] - # - # @example Create from nested array (shape inferred) - # Tensor.new([[1.0, 2.0], [3.0, 4.0]]) # shape: [2, 2] - # - # @example Create from flat array with explicit shape - # Tensor.new([1.0, 2.0, 3.0, 4.0], shape: [2, 2]) - # - def new(data, shape: nil, dtype: :float) - if shape.nil? - # Infer shape from nested array structure - shape = infer_shape(data) - flat_data = flatten_nested(data, shape) - else - # Use flat data directly (backward compatibility) - flat_data = data - end - - create(flat_data, shape, dtype) - end - - private - - # Infer the shape from a nested array structure - # @param data [Array] Potentially nested array - # @return [Array] Inferred shape - def infer_shape(data) - return [0] if data.empty? - - shape = [] - current = data - - while current.is_a?(Array) - shape << current.size - break if current.empty? - current = current.first - end - - # Validate that all elements at each level have consistent sizes - validate_shape(data, shape, 0) - - shape - end - - # Validate that the array has consistent shape at all levels - # @param data [Array] The data to validate - # @param expected_shape [Array] The expected shape - # @param depth [Integer] Current depth in the array - # @raise [ArgumentError] If the array is jagged or inconsistent - def validate_shape(data, expected_shape, depth) - return if depth >= expected_shape.size - return if expected_shape[depth] == 0 - - unless data.is_a?(Array) - raise ArgumentError, "Inconsistent nesting depth at level #{depth}: expected Array, got #{data.class}" - end - - unless data.size == expected_shape[depth] - raise ArgumentError, "Jagged array at depth #{depth}: expected size #{expected_shape[depth]}, got #{data.size}" - end - - data.each_with_index do |element, i| - if depth + 1 < expected_shape.size - # Expect more nesting - unless element.is_a?(Array) - raise ArgumentError, "Inconsistent nesting at depth #{depth}, index #{i}: expected Array, got #{element.class}" - end - validate_shape(element, expected_shape, depth + 1) - else - # At leaf level, should be numeric - if element.is_a?(Array) - raise ArgumentError, "Inconsistent nesting at depth #{depth}, index #{i}: unexpected Array at leaf level" - end - end - end - end - - # Flatten a nested array into a 1D array - # @param data [Array] Potentially nested array - # @param shape [Array] The shape (used to handle empty arrays) - # @return [Array] Flat array - def flatten_nested(data, shape) - return [] if shape.include?(0) - deep_flatten(data) - end - - # Recursively flatten an array - # @param data [Array, Numeric] The data to flatten - # @return [Array] Flat array - def deep_flatten(data) - return [data] unless data.is_a?(Array) - data.flat_map { |element| deep_flatten(element) } - end - end - - # Convert tensor to a nested Ruby array matching the tensor's shape - # @return [Array] Nested array with structure matching shape - # - # @example - # tensor = Tensor.new([1, 2, 3, 4], shape: [2, 2]) - # tensor.to_a # => [[1.0, 2.0], [3.0, 4.0]] - # - def to_a - flat = flat_to_a - reshape_flat_to_nested(flat, shape) - end - - # Convert tensor to a flat Ruby array (original behavior) - # @return [Array] Flat array of all values - alias_method :flat_to_a, :_original_to_a - - private - - # Reshape a flat array into nested arrays according to shape - # @param flat [Array] Flat array of values - # @param shape [Array] Target shape - # @return [Array] Nested array - def reshape_flat_to_nested(flat, shape) - return flat if shape.size <= 1 - - # Handle empty dimensions - if shape.include?(0) - return build_empty_nested(shape) - end - - # Calculate strides for each dimension - build_nested(flat, shape, 0, 0).first - end - - # Build nested array structure - # @param flat [Array] Flat data - # @param shape [Array] Shape - # @param dim [Integer] Current dimension - # @param offset [Integer] Current offset in flat array - # @return [Array] [nested_result, new_offset] - def build_nested(flat, shape, dim, offset) - if dim == shape.size - 1 - # Last dimension: slice the flat array - result = flat[offset, shape[dim]] - [result, offset + shape[dim]] - else - # Build sub-arrays - result = [] - current_offset = offset - shape[dim].times do - sub_result, current_offset = build_nested(flat, shape, dim + 1, current_offset) - result << sub_result - end - [result, current_offset] - end - end - - # Build empty nested structure for shapes with zero dimensions - # @param shape [Array] Shape with at least one zero - # @return [Array] Empty nested structure - def build_empty_nested(shape) - return [] if shape.size == 1 - - first_zero = shape.index(0) - - if first_zero == 0 - [] - else - # Build arrays up to the zero dimension - build_empty_recursive(shape, 0) - end - end - - # Recursively build empty nested arrays - # @param shape [Array] Shape - # @param dim [Integer] Current dimension - # @return [Array] Empty nested structure - def build_empty_recursive(shape, dim) - return [] if dim >= shape.size || shape[dim] == 0 - - Array.new(shape[dim]) { build_empty_recursive(shape, dim + 1) } - end - end - - # Extend Model with Ruby-friendly methods - class Model - # Alias predict to forward for more intuitive API - alias_method :predict, :forward - - # Make model callable - def call(inputs) - forward(inputs) - end - end -end +require_relative "executorch/tensor" +require_relative "executorch/module" diff --git a/lib/executorch/method_meta.rb b/lib/executorch/method_meta.rb new file mode 100644 index 0000000..77e17c5 --- /dev/null +++ b/lib/executorch/method_meta.rb @@ -0,0 +1,70 @@ +# frozen_string_literal: true + +module Executorch + # Immutable metadata describing a single input or output slot of a method. + class TensorInfo + attr_reader :tag, :dtype, :shape, :dim_order, :nbytes + + def initialize(tag, dtype, shape, dim_order, nbytes, memory_planned) + @tag = tag + @dtype = dtype + @shape = shape&.freeze + @dim_order = dim_order&.freeze + @nbytes = nbytes + @memory_planned = !!memory_planned + freeze + end + + def tensor? + @tag == :tensor + end + + def memory_planned? + @memory_planned + end + + def ==(other) + other.is_a?(TensorInfo) && + @tag == other.tag && + @dtype == other.dtype && + @shape == other.shape && + @dim_order == other.dim_order && + @nbytes == other.nbytes && + @memory_planned == other.memory_planned? + end + alias eql? == + + def inspect + if tensor? + "#" + else + "#" + end + end + alias to_s inspect + end + + # Immutable metadata snapshot for an ExecuTorch method, readable without + # paying the memory-planning cost of loading the full method. + class MethodMeta + attr_reader :name, :inputs, :outputs, :backends, :planned_memory_bytes + + def initialize(name, inputs, outputs, backends, planned_memory_bytes) + @name = name.dup.freeze + @inputs = inputs.freeze + @outputs = outputs.freeze + @backends = backends.freeze + @planned_memory_bytes = planned_memory_bytes + freeze + end + + def uses_backend?(backend_name) + @backends.include?(backend_name.to_s) + end + + def inspect + "#" + end + alias to_s inspect + end +end diff --git a/lib/executorch/module.rb b/lib/executorch/module.rb new file mode 100644 index 0000000..c68a894 --- /dev/null +++ b/lib/executorch/module.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +module Executorch + class Module + class << self + # Open an ExecuTorch .pte program from disk. + # Defaults to :mmap for copy-on-write page sharing across forked workers. + # Supports an optional block for deterministic resource cleanup. + # + # @param path [String, Pathname] Path to .pte file + # @param load_mode [Symbol] :mmap (default), :file, :mmap_mlock, + # :mmap_mlock_ignore_errors, or :mmap_madvise + # @param data_files [Array, nil] Optional .ptd external weight files + def open(path, load_mode: :mmap, data_files: nil) + mod = _open_file(path, load_mode: load_mode, data_files: data_files) + return mod unless block_given? + + begin + yield mod + ensure + mod.close + end + end + alias load open + end + + # Execute a named method and always return an Array of outputs. + # + # @param method_name [String, Symbol] Method name (e.g. :forward, :encode) + # @param inputs [Array] + # @param out [Tensor, Array, nil] Optional pre-allocated output tensor(s) + # @return [Array] + def execute(method_name, *inputs, out: nil) + _execute(method_name, inputs, out) + end + + # Execute the "forward" method and always return an Array of outputs. + def forward(*inputs, out: nil) + _execute("forward", inputs, out) + end + + # Ergonomic invocation of "forward": returns the single output directly when + # the method has 1 output, or an Array when it has 0 or >1 outputs. + def call(*inputs, out: nil) + outputs = _execute("forward", inputs, out) + outputs.size == 1 ? outputs.first : outputs + end + + def inspect + return "#" if closed? + + "#" + end + alias to_s inspect + end +end diff --git a/lib/executorch/sdk.rb b/lib/executorch/sdk.rb new file mode 100644 index 0000000..eb5e047 --- /dev/null +++ b/lib/executorch/sdk.rb @@ -0,0 +1,251 @@ +# frozen_string_literal: true + +require "digest" +require "fileutils" +require "net/http" +require "rbconfig" +require "tmpdir" +require "uri" +require "zlib" + +module Executorch + # Fetches and extracts the official prebuilt ExecuTorch C++ SDK (headers, + # shared runtime/backend/kernel libraries, pkg-config, and CMake configs) + # from official PyPI wheels with strict SHA-256 verification and zero + # non-stdlib dependencies. + module SDK + VERSION = File.read(File.expand_path("../../.executorch-version", __dir__)).strip.freeze + + # Official ExecuTorch 1.6.0 PyPI wheel manifest (only include/, lib/, share/cmake/ are extracted). + MANIFEST = { + "x86_64-linux" => { + url: "https://files.pythonhosted.org/packages/ef/24/f8fde978e1e5fd629d68c74a3f4acee30acb05f4f90c433cc1a8e29d8eed/executorch-1.6.0-cp312-cp312-manylinux_2_28_x86_64.whl", + sha256: "d05efe9afe00495112ecf304ca548fcd3239d39e96ac25381b528cdbad948b54", + }, + "aarch64-linux" => { + url: "https://files.pythonhosted.org/packages/d5/7f/9028996ec1dead9c57ed2c6384037e3567c2f514e4ed0c54480d2d3eeb48/executorch-1.6.0-cp312-cp312-manylinux_2_28_aarch64.whl", + sha256: "ff595d236f4052a196a03a867ca0f53d2e3b003d00ab871433660360e194e78e", + }, + "arm64-darwin" => { + url: "https://files.pythonhosted.org/packages/c6/47/1e2120ca1ee178e81471d57255ea0f87b6e04272e32ba20e5ed60ebdb46d/executorch-1.6.0-cp312-cp312-macosx_14_0_arm64.whl", + sha256: "02c220037b41a0a6074a94499a747400ef1a5075a3f2b4d83911871c7291a341", + }, + }.freeze + + # Core runtime + CPU/hardware delegate shared libs bundled in fat gems. + VENDOR_LIBS = { + "x86_64-linux" => %w[ + libexecutorch.so + libexecutorch_threadpool.so + libexecutorch_kernels_optimized.so + libexecutorch_kernels_quantized.so + libexecutorch_backend_xnnpack.so + libexecutorch_etdump.so + ], + "aarch64-linux" => %w[ + libexecutorch.so + libexecutorch_threadpool.so + libexecutorch_kernels_optimized.so + libexecutorch_kernels_quantized.so + libexecutorch_kernels_torchao.so + libexecutorch_backend_xnnpack.so + libexecutorch_etdump.so + ], + "arm64-darwin" => %w[ + libexecutorch.dylib + libexecutorch_threadpool.dylib + libexecutorch_kernels_optimized.dylib + libexecutorch_kernels_quantized.dylib + libexecutorch_kernels_torchao.dylib + libexecutorch_backend_xnnpack.dylib + libexecutorch_backend_coreml.dylib + libexecutorch_backend_mlx.dylib + libexecutorch_etdump.dylib + mlx.metallib + ], + }.freeze + + module_function + + def platform_key(os: RbConfig::CONFIG["target_os"], cpu: RbConfig::CONFIG["target_cpu"]) + norm_cpu = case cpu + when /x86_64|amd64/i then "x86_64" + when /aarch64|arm64/i then os =~ /darwin/i ? "arm64" : "aarch64" + else cpu + end + norm_os = case os + when /darwin/i then "darwin" + when /linux/i then "linux" + else os + end + "#{norm_cpu}-#{norm_os}" + end + + def default_cache_dir(key = platform_key) + base = ENV["XDG_CACHE_HOME"] + base = File.join(Dir.home, ".cache") if base.nil? || base.empty? + File.join(base, "executorch-ruby", "sdk-#{VERSION}-#{key}") + end + + def valid_sdk?(dir) + return false unless dir && File.directory?(dir) + + File.exist?(File.join(dir, "include", "executorch", "extension", "module", "module.h")) && + File.directory?(File.join(dir, "lib")) + end + + def ensure_sdk(dest_dir: nil, key: platform_key, io: $stdout) + dest = dest_dir || default_cache_dir(key) + return dest if valid_sdk?(dest) + + entry = MANIFEST[key] + raise "No prebuilt ExecuTorch #{VERSION} SDK manifest for platform '#{key}'. Set --with-executorch-dir or EXECUTORCH_DIR." unless entry + + io&.puts "Fetching official ExecuTorch #{VERSION} C++ SDK for #{key}..." + Dir.mktmpdir("executorch-sdk") do |tmp| + whl_path = File.join(tmp, "executorch.whl") + download_with_redirects(entry[:url], whl_path) + actual_sha = Digest::SHA256.file(whl_path).hexdigest + unless actual_sha == entry[:sha256] + raise "SHA-256 mismatch for ExecuTorch SDK (#{key}): expected #{entry[:sha256]}, got #{actual_sha}" + end + + stage = File.join(tmp, "stage") + extract_sdk_from_wheel(whl_path, stage) + FileUtils.mkdir_p(File.dirname(dest)) + FileUtils.rm_rf(dest) + FileUtils.mv(stage, dest) + end + + raise "Extracted SDK at #{dest} is incomplete" unless valid_sdk?(dest) + + io&.puts "Installed ExecuTorch #{VERSION} C++ SDK to #{dest}" + dest + end + + def download_with_redirects(url, dest, limit = 5) + raise "Too many HTTP redirects downloading #{url}" if limit <= 0 + + uri = URI.parse(url) + Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 30, read_timeout: 120) do |http| + req = Net::HTTP::Get.new(uri) + http.request(req) do |res| + case res + when Net::HTTPSuccess + File.open(dest, "wb") { |f| res.read_body { |chunk| f.write(chunk) } } + when Net::HTTPRedirection + download_with_redirects(res["location"], dest, limit - 1) + else + raise "Failed downloading #{url}: HTTP #{res.code} #{res.message}" + end + end + end + end + + # Minimal pure-Ruby ZIP reader (central directory) extracting ONLY + # executorch/{include,lib,share/cmake}/ from the wheel. + def extract_sdk_from_wheel(whl_path, dest_dir) + File.open(whl_path, "rb") do |f| + size = f.size + search_len = [size, 65_557].min + f.seek(size - search_len) + tail = f.read(search_len) + eocd_idx = tail.rindex("PK\x05\x06") + raise "Invalid wheel archive (missing EOCD)" unless eocd_idx + + _sig, _disk, _cd_disk, _entries_disk, total_entries, cd_size, cd_offset = + tail.byteslice(eocd_idx, 22).unpack("a4vvvvVV") + + # Handle ZIP64 if needed + if total_entries == 0xFFFF || cd_offset == 0xFFFFFFFF + loc_idx = tail.rindex("PK\x06\x07", eocd_idx) + raise "ZIP64 locator missing" unless loc_idx + + zip64_offset = tail.byteslice(loc_idx + 8, 8).unpack1("Q<") + f.seek(zip64_offset) + z64 = f.read(56) + total_entries = z64.byteslice(32, 8).unpack1("Q<") + cd_size = z64.byteslice(40, 8).unpack1("Q<") + cd_offset = z64.byteslice(48, 8).unpack1("Q<") + end + + f.seek(cd_offset) + cd = f.read(cd_size) + pos = 0 + + total_entries.times do + break if pos + 46 > cd.bytesize + + sig = cd.byteslice(pos, 4) + raise "Invalid central directory header" unless sig == "PK\x01\x02" + + method, _time, _date, _crc, comp_size, uncomp_size, name_len, extra_len, comment_len, + _disk_start, _int_attr, _ext_attr, local_offset = + cd.byteslice(pos + 10, 36).unpack("vvvVVVvvvvvVV") + + name = cd.byteslice(pos + 46, name_len) + extra = cd.byteslice(pos + 46 + name_len, extra_len) + pos += 46 + name_len + extra_len + comment_len + + next unless name.start_with?("executorch/include/", "executorch/lib/", "executorch/share/cmake/") + next if name.end_with?("/") + + # Resolve ZIP64 extra fields if 32-bit fields overflowed + if comp_size == 0xFFFFFFFF || uncomp_size == 0xFFFFFFFF || local_offset == 0xFFFFFFFF + ep = 0 + while ep + 4 <= extra.bytesize + eid, esz = extra.byteslice(ep, 4).unpack("vv") + if eid == 0x0001 + ef = extra.byteslice(ep + 4, esz) + off = 0 + if uncomp_size == 0xFFFFFFFF + uncomp_size = ef.byteslice(off, 8).unpack1("Q<") + off += 8 + end + if comp_size == 0xFFFFFFFF + comp_size = ef.byteslice(off, 8).unpack1("Q<") + off += 8 + end + if local_offset == 0xFFFFFFFF + local_offset = ef.byteslice(off, 8).unpack1("Q<") + end + break + end + ep += 4 + esz + end + end + + rel = name.delete_prefix("executorch/") + # Prevent path traversal + raise "Unsafe archive path: #{rel}" if rel.include?("..") || rel.start_with?("/") + + out_path = File.join(dest_dir, rel) + FileUtils.mkdir_p(File.dirname(out_path)) + + f.seek(local_offset) + lh = f.read(30) + raise "Invalid local file header for #{name}" unless lh&.start_with?("PK\x03\x04") + + l_name_len, l_extra_len = lh.byteslice(26, 4).unpack("vv") + f.seek(local_offset + 30 + l_name_len + l_extra_len) + raw = f.read(comp_size) + + data = case method + when 0 then raw + when 8 + z = Zlib::Inflate.new(-Zlib::MAX_WBITS) + begin + z.inflate(raw) + ensure + z.close + end + else + raise "Unsupported ZIP compression method #{method} for #{name}" + end + + File.binwrite(out_path, data) + end + end + end + end +end diff --git a/lib/executorch/tensor.rb b/lib/executorch/tensor.rb new file mode 100644 index 0000000..1e464b8 --- /dev/null +++ b/lib/executorch/tensor.rb @@ -0,0 +1,85 @@ +# frozen_string_literal: true + +module Executorch + class Tensor + class << self + # Create a tensor filled with ones. + def ones(shape, dtype: :float32) + full(shape, 1, dtype: dtype) + end + + # Create a tensor filled with a constant scalar value. + def full(shape, value, dtype: :float32) + raise TypeError, "shape must be an Array" unless shape.is_a?(Array) + + numel = shape.empty? ? 1 : shape.reduce(1, :*) + raise ShapeError, "shape dimensions must be non-negative" if shape.any? { |d| !d.is_a?(Integer) || d < 0 } + + new(Array.new(numel, value), shape: shape, dtype: dtype) + end + + # Build a Tensor from a Numo::NArray (zero-copy byte path). + def from_numo(narray) + dtype = NUMO_TO_DTYPE[narray.class.name] + raise DTypeError, "Unsupported Numo::NArray type: #{narray.class.name}" unless dtype + + from_bytes(narray.to_binary, shape: narray.shape, dtype: dtype) + end + + # Build a Tensor from a Torch::Tensor (torch.rb interop). + def from_torch(torch_tensor) + dtype = TORCH_TO_DTYPE[torch_tensor.dtype] + raise DTypeError, "Unsupported Torch::Tensor dtype: #{torch_tensor.dtype.inspect}" unless dtype + + new(torch_tensor.contiguous.to_a, shape: torch_tensor.shape, dtype: dtype) + end + end + + NUMO_TO_DTYPE = { + "Numo::SFloat" => :float32, + "Numo::DFloat" => :float64, + "Numo::Int8" => :int8, + "Numo::Int16" => :int16, + "Numo::Int32" => :int32, + "Numo::Int64" => :int64, + "Numo::UInt8" => :uint8, + "Numo::UInt16" => :uint16, + "Numo::UInt32" => :uint32, + "Numo::UInt64" => :uint64, + }.freeze + + TORCH_TO_DTYPE = { + float32: :float32, + float64: :float64, + float16: :float16, + bfloat16: :bfloat16, + int8: :int8, + int16: :int16, + int32: :int32, + int64: :int64, + uint8: :uint8, + bool: :bool, + }.freeze + + def empty? + numel == 0 + end + + def to_numo + raise LoadError, "Numo::NArray is not loaded (require 'numo/narray')" unless defined?(::Numo::NArray) + + klass_name = NUMO_TO_DTYPE.key(dtype) + raise DTypeError, "No Numo::NArray equivalent for dtype #{dtype.inspect}" unless klass_name + + klass = Object.const_get(klass_name) + klass.from_binary(to_bytes, shape) + end + + def inspect + return "#" if closed? + + "#" + end + alias to_s inspect + end +end diff --git a/lib/executorch/version.rb b/lib/executorch/version.rb index 4da584d..8c35be2 100644 --- a/lib/executorch/version.rb +++ b/lib/executorch/version.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Executorch - VERSION = "0.1.0" + VERSION = "1.0.0" end diff --git a/mise.toml b/mise.toml new file mode 100644 index 0000000..7f64b26 --- /dev/null +++ b/mise.toml @@ -0,0 +1,2 @@ +[tools] +ruby = "3.4.7" diff --git a/test/fixtures/export_fixtures.py b/test/fixtures/export_fixtures.py new file mode 100644 index 0000000..06135bd --- /dev/null +++ b/test/fixtures/export_fixtures.py @@ -0,0 +1,293 @@ +#!/usr/bin/env python3 +"""Export deterministic ExecuTorch 1.6.0 test fixtures (.pte / .ptd + golden JSON). + +Every model is seeded deterministically and paired with golden PyTorch outputs so +Ruby tests verify exact numerical accuracy, shapes, dtypes, delegates, multi-method +dispatch, external .ptd weights, scalar EValues, and GVL concurrency. +""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +from typing import Any + +import torch +import torch.nn as nn +from executorch.backends.xnnpack.partition.xnnpack_partitioner import XnnpackPartitioner +from executorch.exir import EdgeCompileConfig, ExecutorchBackendConfig, to_edge_transform_and_lower + + +def tensor_to_golden(t: torch.Tensor) -> dict[str, Any]: + cpu = t.detach().cpu().contiguous() + if cpu.dtype == torch.bfloat16 or cpu.dtype == torch.float16: + values = cpu.to(torch.float32).flatten().tolist() + elif cpu.dtype == torch.bool: + values = [bool(x) for x in cpu.flatten().tolist()] + else: + values = cpu.flatten().tolist() + dtype_map = { + torch.float32: "float32", + torch.float64: "float64", + torch.float16: "float16", + torch.bfloat16: "bfloat16", + torch.int8: "int8", + torch.uint8: "uint8", + torch.int16: "int16", + torch.int32: "int32", + torch.int64: "int64", + torch.bool: "bool", + } + return { + "shape": list(cpu.shape), + "dtype": dtype_map[cpu.dtype], + "values": values, + } + + +def export_program( + out_dir: Path, + name: str, + programs: dict[str, torch.export.ExportedProgram], + partitioners: list[Any] | None = None, + external_constants: bool = False, +) -> Path: + edge_kwargs: dict[str, Any] = { + "compile_config": EdgeCompileConfig(_check_ir_validity=False), + } + if partitioners: + edge_kwargs["partitioner"] = partitioners + + edge = to_edge_transform_and_lower(programs, **edge_kwargs) + et_cfg = ExecutorchBackendConfig( + extract_delegate_segments=True, + external_constants=external_constants, + ) + et_prog = edge.to_executorch(config=et_cfg) + + pte_path = out_dir / f"{name}.pte" + with open(pte_path, "wb") as f: + et_prog.write_to_file(f) + + if external_constants: + et_prog.write_tensor_data_to_file(str(out_dir)) + return pte_path + + +class AddMul(nn.Module): + def forward(self, x: torch.Tensor) -> torch.Tensor: + return x * 2.0 + 1.0 + + +class MultiIO(nn.Module): + def forward(self, a: torch.Tensor, b: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + return a + b, a * b + + +class Encoder(nn.Module): + def __init__(self) -> None: + super().__init__() + self.proj = nn.Linear(4, 3) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return torch.relu(self.proj(x)) + + +class Decoder(nn.Module): + def __init__(self) -> None: + super().__init__() + self.proj = nn.Linear(3, 4) + + def forward(self, z: torch.Tensor) -> torch.Tensor: + return self.proj(z) + + +class DtypeEcho(nn.Module): + def forward( + self, + f64: torch.Tensor, + i64: torch.Tensor, + u8: torch.Tensor, + mask: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + return f64 + 0.5, i64 + 1, u8 + 2, torch.logical_not(mask) + + +class SmallCnnXnnpack(nn.Module): + def __init__(self) -> None: + super().__init__() + self.net = nn.Sequential( + nn.Conv2d(3, 8, kernel_size=3, padding=1), + nn.ReLU(), + nn.Conv2d(8, 4, kernel_size=3, padding=1), + nn.ReLU(), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.net(x) + + +class ExternalWeightsMlp(nn.Module): + def __init__(self) -> None: + super().__init__() + self.fc1 = nn.Linear(16, 32) + self.fc2 = nn.Linear(32, 8) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.fc2(torch.relu(self.fc1(x))) + + +class HeavyMlp(nn.Module): + """Big enough (~15-40ms on CPU) to cleanly prove GVL release & parallel scaling.""" + + def __init__(self) -> None: + super().__init__() + self.layers = nn.Sequential( + nn.Linear(512, 1024), + nn.ReLU(), + nn.Linear(1024, 1024), + nn.ReLU(), + nn.Linear(1024, 1024), + nn.ReLU(), + nn.Linear(1024, 256), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.layers(x) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--out", required=True, help="Output directory for fixtures") + args = parser.parse_args() + + out_dir = Path(args.out) + out_dir.mkdir(parents=True, exist_ok=True) + torch.manual_seed(42) + + manifest: dict[str, Any] = { + "torch_version": torch.__version__, + "models": {}, + } + + # 1. add_mul (simple 1-in/1-out) + m = AddMul().eval() + x = torch.tensor([[1.0, 2.0, 3.0]], dtype=torch.float32) + y = m(x) + export_program(out_dir, "add_mul", {"forward": torch.export.export(m, (x,))}) + manifest["models"]["add_mul"] = { + "file": "add_mul.pte", + "inputs": [tensor_to_golden(x)], + "outputs": [tensor_to_golden(y)], + } + + # 2. multi_io (2 inputs, 2 outputs) + m = MultiIO().eval() + a = torch.tensor([[1.0, 2.0], [3.0, 4.0]], dtype=torch.float32) + b = torch.tensor([[10.0, 20.0], [30.0, 40.0]], dtype=torch.float32) + y1, y2 = m(a, b) + export_program(out_dir, "multi_io", {"forward": torch.export.export(m, (a, b))}) + manifest["models"]["multi_io"] = { + "file": "multi_io.pte", + "inputs": [tensor_to_golden(a), tensor_to_golden(b)], + "outputs": [tensor_to_golden(y1), tensor_to_golden(y2)], + } + + # 3. multi_method (encode & decode methods in one .pte) + enc = Encoder().eval() + dec = Decoder().eval() + x_enc = torch.tensor([[0.5, -1.0, 2.0, 0.25]], dtype=torch.float32) + z = enc(x_enc) + x_dec = dec(z) + export_program( + out_dir, + "multi_method", + { + "encode": torch.export.export(enc, (x_enc,)), + "decode": torch.export.export(dec, (z,)), + }, + ) + manifest["models"]["multi_method"] = { + "file": "multi_method.pte", + "methods": { + "encode": {"inputs": [tensor_to_golden(x_enc)], "outputs": [tensor_to_golden(z)]}, + "decode": {"inputs": [tensor_to_golden(z)], "outputs": [tensor_to_golden(x_dec)]}, + }, + } + + # 4. dtypes (float64, int64, uint8, bool) + m = DtypeEcho().eval() + f64 = torch.tensor([1.25, -2.5], dtype=torch.float64) + i64 = torch.tensor([10, -20, 30], dtype=torch.int64) + u8 = torch.tensor([[0, 10, 250]], dtype=torch.uint8) + mask = torch.tensor([True, False, True], dtype=torch.bool) + outs = m(f64, i64, u8, mask) + export_program(out_dir, "dtypes", {"forward": torch.export.export(m, (f64, i64, u8, mask))}) + manifest["models"]["dtypes"] = { + "file": "dtypes.pte", + "inputs": [tensor_to_golden(t) for t in (f64, i64, u8, mask)], + "outputs": [tensor_to_golden(t) for t in outs], + } + + # 5. cnn_xnnpack (real Conv2d lowered to XnnpackBackend) + m = SmallCnnXnnpack().eval() + img = torch.randn(1, 3, 16, 16, dtype=torch.float32) + out_cnn = m(img) + export_program( + out_dir, + "cnn_xnnpack", + {"forward": torch.export.export(m, (img,))}, + partitioners=[XnnpackPartitioner()], + ) + manifest["models"]["cnn_xnnpack"] = { + "file": "cnn_xnnpack.pte", + "inputs": [tensor_to_golden(img)], + "outputs": [tensor_to_golden(out_cnn)], + "expected_backends": ["XnnpackBackend"], + } + + # 6. external_weights (.pte + .ptd) + m = ExternalWeightsMlp().eval() + x_ext = torch.randn(2, 16, dtype=torch.float32) + y_ext = m(x_ext) + ptd_dir = out_dir / "external_weights_data" + ptd_dir.mkdir(exist_ok=True) + export_program( + ptd_dir, + "external_weights", + {"forward": torch.export.export(m, (x_ext,))}, + external_constants=True, + ) + ptd_files = sorted(str(p.relative_to(out_dir)) for p in ptd_dir.glob("*.ptd")) + manifest["models"]["external_weights"] = { + "file": "external_weights_data/external_weights.pte", + "data_files": ptd_files, + "inputs": [tensor_to_golden(x_ext)], + "outputs": [tensor_to_golden(y_ext)], + } + + # 7. heavy_mlp (XNNPACK-delegated batch=32 MLP for GVL & multi-thread proof) + m = HeavyMlp().eval() + x_h = torch.randn(32, 512, dtype=torch.float32) + y_h = m(x_h) + export_program( + out_dir, + "heavy_mlp", + {"forward": torch.export.export(m, (x_h,))}, + partitioners=[XnnpackPartitioner()], + ) + manifest["models"]["heavy_mlp"] = { + "file": "heavy_mlp.pte", + "inputs": [tensor_to_golden(x_h)], + "outputs": [tensor_to_golden(y_h)], + "expected_backends": ["XnnpackBackend"], + } + + (out_dir / "manifest.json").write_text(json.dumps(manifest, indent=2)) + print(f"Exported {len(manifest['models'])} fixture models to {out_dir}") + + +if __name__ == "__main__": + main() diff --git a/test/fixtures/pyproject.toml b/test/fixtures/pyproject.toml new file mode 100644 index 0000000..c6c7312 --- /dev/null +++ b/test/fixtures/pyproject.toml @@ -0,0 +1,8 @@ +[project] +name = "executorch-ruby-fixtures" +version = "1.0.0" +requires-python = ">=3.11,<3.14" +dependencies = [ + "executorch==1.6.0", + "torch>=2.10", +] diff --git a/test/integration_test.rb b/test/integration_test.rb deleted file mode 100644 index 4df5de2..0000000 --- a/test/integration_test.rb +++ /dev/null @@ -1,77 +0,0 @@ -# frozen_string_literal: true - -require "test_helper" - -class IntegrationTest < Minitest::Test - include TestHelper - - # Full workflow test: load model -> check methods -> run inference - def test_full_workflow_with_simple_model - skip_without_models - - # Load model - model = Executorch::Model.new(model_path("simple.pte")) - assert model.loaded? - - # Check methods - assert_includes model.method_names, "forward" - - # Run inference - simple.pte does x * 2 + 1 - input = Executorch::Tensor.new([1.0, 2.0, 3.0], shape: [1, 3], dtype: :float) - outputs = model.forward([input]) - - assert_kind_of Array, outputs - assert_equal 1, outputs.size - - output = outputs.first - assert_kind_of Executorch::Tensor, output - assert_equal [1, 3], output.shape - - # Verify: [1.0, 2.0, 3.0] * 2 + 1 = [3.0, 5.0, 7.0] - # Output shape is [1, 3], so to_a returns [[3.0, 5.0, 7.0]] - expected = [[3.0, 5.0, 7.0]] - assert_equal expected.size, output.to_a.size - expected.first.zip(output.to_a.first).each do |e, a| - assert_in_delta e, a, 0.001 - end - end - - def test_predict_workflow - skip_without_models - - model = Executorch::Model.new(model_path("simple.pte")) - input = Executorch::Tensor.new([1.0, 2.0, 3.0], shape: [1, 3], dtype: :float) - - # Use predict instead of forward - outputs = model.predict([input]) - - assert_kind_of Array, outputs - output = outputs.first - assert_kind_of Executorch::Tensor, output - - # Output shape is [1, 3], so to_a returns [[3.0, 5.0, 7.0]] - expected = [[3.0, 5.0, 7.0]] - assert_equal expected.size, output.to_a.size - expected.first.zip(output.to_a.first).each do |e, a| - assert_in_delta e, a, 0.001 - end - end - - def test_error_handling_invalid_model - # Verify proper error messages for common failure cases - error = assert_raises(RuntimeError) do - Executorch::Model.new("/definitely/not/a/real/path.pte") - end - - assert_match(/error/i, error.message) - end - - def test_version_constant - assert_kind_of String, Executorch::VERSION - assert_match(/\d+\.\d+\.\d+/, Executorch::VERSION) - end - - def test_native_version_constant - assert_kind_of String, Executorch::NATIVE_VERSION - end -end diff --git a/test/model_test.rb b/test/model_test.rb deleted file mode 100644 index 8391825..0000000 --- a/test/model_test.rb +++ /dev/null @@ -1,68 +0,0 @@ -# frozen_string_literal: true - -require "test_helper" - -class ModelTest < Minitest::Test - include TestHelper - - # Tests for Model initialization - def test_model_requires_path - assert_raises(ArgumentError) do - Executorch::Model.new - end - end - - def test_model_raises_on_invalid_path - assert_raises(RuntimeError) do - Executorch::Model.new("/nonexistent/path/model.pte") - end - end - - def test_model_stores_path - skip_without_models - model = Executorch::Model.new(model_path("simple.pte")) - assert_equal model_path("simple.pte"), model.path - end - - def test_model_is_loaded_after_construction - skip_without_models - model = Executorch::Model.new(model_path("simple.pte")) - assert model.loaded? - end - - def test_model_method_names_returns_array - skip_without_models - model = Executorch::Model.new(model_path("simple.pte")) - names = model.method_names - assert_kind_of Array, names - assert names.all? { |n| n.is_a?(String) } - end - - def test_model_has_forward_method - skip_without_models - model = Executorch::Model.new(model_path("simple.pte")) - assert_includes model.method_names, "forward" - end - - def test_model_predict_is_alias_for_forward - skip_without_models - model = Executorch::Model.new(model_path("simple.pte")) - input = Executorch::Tensor.new([1.0, 2.0, 3.0], shape: [1, 3], dtype: :float) - - forward_result = model.forward([input]) - predict_result = model.predict([input]) - - assert_equal forward_result.first.to_a, predict_result.first.to_a - end - - def test_model_is_callable - skip_without_models - model = Executorch::Model.new(model_path("simple.pte")) - input = Executorch::Tensor.new([1.0, 2.0, 3.0], shape: [1, 3], dtype: :float) - - forward_result = model.forward([input]) - call_result = model.call([input]) - - assert_equal forward_result.first.to_a, call_result.first.to_a - end -end diff --git a/test/module_test.rb b/test/module_test.rb new file mode 100644 index 0000000..b53866f --- /dev/null +++ b/test/module_test.rb @@ -0,0 +1,150 @@ +# frozen_string_literal: true + +require_relative "test_helper" + +class ModuleTest < Minitest::Test + include TestHelper + + def test_open_string_and_pathname_with_block_and_load_modes + spec = model_spec(:add_mul) + path = fixture_path(spec["file"]) + input = tensor_from_golden(spec["inputs"].first) + + %i[mmap file mmap_madvise].each do |mode| + closed_mod = nil + Executorch::Module.open(Pathname.new(path), load_mode: mode) do |mod| + closed_mod = mod + refute_predicate mod, :closed? + assert_equal path, mod.source + assert_includes mod.method_names, "forward" + out = mod.call(input) + assert_tensor_matches_golden(out, spec["outputs"].first) + end + assert_predicate closed_mod, :closed? + assert_raises(Executorch::ClosedError) { closed_mod.call(input) } + end + end + + def test_from_bytes_in_memory_load + spec = model_spec(:add_mul) + raw = File.binread(fixture_path(spec["file"])) + mod = Executorch::Module.from_bytes(raw) + assert_includes mod.source, "=, 0 + + # Explicit pre-warm & unload + mod.load_method(:forward) + assert mod.method_loaded?(:forward) + + out = mod.call(tensor_from_golden(spec["inputs"].first)) + assert_tensor_matches_golden(out, spec["outputs"].first, rtol: 1e-2, atol: 1e-3) + + assert_equal true, mod.unload_method(:forward) + refute mod.method_loaded?(:forward) + end + end + + def test_multi_input_and_multi_output + spec = model_spec(:multi_io) + Executorch::Module.open(fixture_path(spec["file"])) do |mod| + a = tensor_from_golden(spec["inputs"][0]) + b = tensor_from_golden(spec["inputs"][1]) + + outs = mod.call(a, b) + assert_instance_of Array, outs + assert_equal 2, outs.size + assert_tensor_matches_golden(outs[0], spec["outputs"][0]) + assert_tensor_matches_golden(outs[1], spec["outputs"][1]) + + # #forward and #execute always return Array + outs2 = mod.execute(:forward, a, b) + assert_equal outs, outs2 + end + end + + def test_multi_method_encode_and_decode + spec = model_spec(:multi_method) + Executorch::Module.open(fixture_path(spec["file"])) do |mod| + assert_equal %w[decode encode], mod.method_names + + enc_spec = spec["methods"]["encode"] + dec_spec = spec["methods"]["decode"] + + z = mod.execute(:encode, tensor_from_golden(enc_spec["inputs"].first)).first + assert_tensor_matches_golden(z, enc_spec["outputs"].first) + + recon = mod.execute("decode", z).first + assert_tensor_matches_golden(recon, dec_spec["outputs"].first) + end + end + + def test_multiple_dtypes_end_to_end + spec = model_spec(:dtypes) + Executorch::Module.open(fixture_path(spec["file"])) do |mod| + inputs = spec["inputs"].map { |d| tensor_from_golden(d) } + outputs = mod.forward(*inputs) + assert_equal 4, outputs.size + outputs.each_with_index do |out, i| + assert_tensor_matches_golden(out, spec["outputs"][i]) + end + end + end + + def test_external_ptd_weights + spec = model_spec(:external_weights) + pte = fixture_path(spec["file"]) + ptds = spec["data_files"].map { |rel| Pathname.new(fixture_path(rel)) } + refute_empty ptds, "expected at least one .ptd external data file" + + Executorch::Module.open(pte, data_files: ptds) do |mod| + out = mod.call(tensor_from_golden(spec["inputs"].first)) + assert_tensor_matches_golden(out, spec["outputs"].first) + end + end + + def test_preallocated_out_tensor_and_zero_copy_io_buffer + spec = model_spec(:add_mul) + Executorch::Module.open(fixture_path(spec["file"])) do |mod| + in_buf = IO::Buffer.new(12) + in_buf.set_string([1.0, 2.0, 3.0].pack("f*")) + inp = Executorch::Tensor.from_buffer(in_buf, shape: [1, 3], dtype: :float32) + + out_buf = IO::Buffer.new(12) + out = Executorch::Tensor.from_buffer(out_buf, shape: [1, 3], dtype: :float32) + + ret = mod.call(inp, out: out) + assert_same out, ret + assert_tensor_matches_golden(out, spec["outputs"].first) + # Verify written straight into out_buf + assert_equal [3.0, 5.0, 7.0], out_buf.get_string.unpack("f*") + + # Mismatched out shape/dtype raises cleanly + bad_shape = Executorch::Tensor.zeros([1, 4], dtype: :float32) + assert_raises(Executorch::ShapeError) { mod.call(inp, out: bad_shape) } + + bad_dtype = Executorch::Tensor.zeros([1, 3], dtype: :float64) + assert_raises(Executorch::DTypeError) { mod.call(inp, out: bad_dtype) } + end + end +end diff --git a/test/runtime_test.rb b/test/runtime_test.rb new file mode 100644 index 0000000..b31d2a2 --- /dev/null +++ b/test/runtime_test.rb @@ -0,0 +1,73 @@ +# frozen_string_literal: true + +require_relative "test_helper" +require "rbconfig" + +class RuntimeTest < Minitest::Test + def test_version_constants + assert_equal "1.0.0", Executorch::VERSION + assert_match(/\A\d+\.\d+\.\d+/, Executorch.executorch_version) + end + + def test_xnnpack_backend_and_kernels_registered + assert_includes Executorch.backends, "XnnpackBackend" + assert_operator Executorch.kernel_count, :>, 50 + end + + def test_num_threads_get_and_set + orig = Executorch.num_threads + assert_kind_of Integer, orig + assert_operator orig, :>=, 1 + + Executorch.num_threads = 2 + assert_equal 2, Executorch.num_threads + ensure + Executorch.num_threads = orig if orig && orig >= 1 + end + + def test_num_threads_validation + assert_raises(ArgumentError) { Executorch.num_threads = 0 } + assert_raises(ArgumentError) { Executorch.num_threads = -4 } + assert_raises(ArgumentError) { Executorch.num_threads = 10_000 } + assert_raises(TypeError) { Executorch.num_threads = "2" } + end + + def test_error_hierarchy + assert_operator Executorch::Error, :<, StandardError + %i[ + LoadError + MethodNotFoundError + OperatorMissingError + DelegateError + ShapeError + DTypeError + ExecutionError + MemoryError + ClosedError + ].each do |name| + klass = Executorch.const_get(name) + assert_operator klass, :<, Executorch::Error, "#{name} must inherit from Executorch::Error" + end + end + + def test_native_extension_exports_only_init_executorch + dlext = RbConfig::CONFIG["DLEXT"] + ext_path = File.expand_path("../lib/executorch/executorch.#{dlext}", __dir__) + assert File.exist?(ext_path), "expected compiled extension at #{ext_path}" + + case RbConfig::CONFIG["target_os"] + when /linux/i + out = `nm -D --defined-only #{ext_path} 2>/dev/null` + assert $?.success?, "nm -D failed on #{ext_path}" + syms = out.lines.map { |l| l.split.last }.compact + assert_equal ["Init_executorch"], syms, "Unexpected exported symbols leak: #{syms.inspect}" + when /darwin/i + out = `nm -gU #{ext_path} 2>/dev/null` + assert $?.success?, "nm -gU failed on #{ext_path}" + syms = out.lines.map { |l| l.split.last }.compact + assert_equal ["_Init_executorch"], syms, "Unexpected exported symbols leak: #{syms.inspect}" + else + flunk "Unsupported target_os for symbol check: #{RbConfig::CONFIG['target_os']}" + end + end +end diff --git a/test/safety_test.rb b/test/safety_test.rb new file mode 100644 index 0000000..a1cea90 --- /dev/null +++ b/test/safety_test.rb @@ -0,0 +1,246 @@ +# frozen_string_literal: true + +require_relative "test_helper" +require "tmpdir" + +class SafetyTest < Minitest::Test + include TestHelper + + # 1. Heap OOB, negative dims, and integer overflows must raise, NEVER crash or leak memory + def test_shape_mismatch_negative_dims_and_integer_overflows + assert_raises(Executorch::ShapeError) { Executorch::Tensor.new([1.0], shape: [100_000]) } + assert_raises(Executorch::ShapeError) { Executorch::Tensor.new([1.0], shape: [-1]) } + assert_raises(Executorch::ShapeError) { Executorch::Tensor.new([1.0], shape: [1 << 32]) } + + raw4 = [1.0, 2.0, 3.0, 4.0].pack("f*") + assert_raises(Executorch::ShapeError) { Executorch::Tensor.from_bytes(raw4, shape: [-2, -2]) } + assert_raises(Executorch::ShapeError) { Executorch::Tensor.from_bytes("", shape: [1 << 30, 1 << 30, 4]) } + assert_raises(Executorch::ShapeError) { Executorch::Tensor.from_bytes(raw4, shape: [2, 3]) } + assert_raises(Executorch::ShapeError) { Executorch::Tensor.from_bytes(raw4, shape: [1, 1]) } + end + + # 2. Reentrant array-shrinking #to_f must not cause heap OOB read + def test_reentrant_mutating_array_does_not_oob + ary = [] + shrinker = Object.new + shrinker.define_singleton_method(:to_f) do + ary.clear + 1.0 + end + ary.push(shrinker, 2.0, 3.0, 4.0) + + assert_raises(ArgumentError) { Executorch::Tensor.new(ary, shape: [4], dtype: :float32) } + end + + # 3. Jagged & malformed nested arrays (including PR #1 regressions) + def test_jagged_and_malformed_nested_arrays_rejected + [ + [[], [1.0, 2.0]], + [[], "garbage", nil], + [[1.0], [[2.0]]], + [[1.0, 2.0], [[3.0], [4.0]]], + [[1.0, 2.0], [3.0]], + [1.0, [2.0]], + ].each do |bad| + assert_raises(ArgumentError, "Expected ArgumentError for #{bad.inspect}") do + Executorch::Tensor.new(bad) + end + end + end + + # 4. IEEE-754 special values & integer range checks (zero C++ UB, zero silent truncation) + def test_nan_inf_and_integer_range_checks + t = Executorch::Tensor.new([Float::NAN, Float::INFINITY, -Float::INFINITY, -0.0], dtype: :float32) + vals = t.to_a + assert vals[0].nan? + assert_equal Float::INFINITY, vals[1] + assert_equal(-Float::INFINITY, vals[2]) + + assert_raises(FloatDomainError) { Executorch::Tensor.new([Float::NAN], dtype: :int64) } + assert_raises(FloatDomainError) { Executorch::Tensor.new([Float::INFINITY], dtype: :int64) } + assert_raises(FloatDomainError) { Executorch::Tensor.new([Float::NAN], dtype: :uint64) } + assert_raises(RangeError) { Executorch::Tensor.new([1 << 40], dtype: :int32) } + assert_raises(RangeError) { Executorch::Tensor.new([-1], dtype: :uint8) } + assert_raises(RangeError) { Executorch::Tensor.new([256], dtype: :uint8) } + assert_raises(Executorch::DTypeError) { Executorch::Tensor.new([1], dtype: :not_a_dtype) } + end + + # 5. Corrupt, empty, truncated, nonexistent, and directory .pte files + def test_corrupt_and_invalid_pte_files + err = assert_raises(Executorch::LoadError) { Executorch::Module.open("/nonexistent/model.pte") } + assert_includes err.message, "/nonexistent/model.pte" + + assert_raises(Executorch::LoadError) { Executorch::Module.open(Dir.tmpdir) } + assert_raises(Executorch::LoadError) { Executorch::Module.from_bytes("") } + assert_raises(Executorch::LoadError) { Executorch::Module.from_bytes("not a flatbuffer") } + + valid_bytes = File.binread(fixture_path(model_spec(:add_mul)["file"])) + assert_raises(Executorch::LoadError) { Executorch::Module.from_bytes(valid_bytes.byteslice(0, 32)) } + + Dir.mktmpdir do |dir| + empty = File.join(dir, "empty.pte") + File.binwrite(empty, "") + assert_raises(Executorch::LoadError) { Executorch::Module.open(empty) } + end + end + + # 6. Invalid inputs to Module#execute (no unbound Rice type crash!) + def test_invalid_inputs_and_missing_method + spec = model_spec(:add_mul) + Executorch::Module.open(fixture_path(spec["file"])) do |mod| + assert_raises(Executorch::MethodNotFoundError) { mod.meta(:does_not_exist) } + assert_raises(Executorch::MethodNotFoundError) { mod.execute(:does_not_exist) } + + # Non-Tensor unsupported Ruby object raises TypeError cleanly + assert_raises(TypeError) { mod.call(Object.new) } + + # Wrong shape / arity raises Executorch::Error with diagnostic info + wrong_shape = Executorch::Tensor.new([[1.0, 2.0, 3.0, 4.0]]) + err = assert_raises(Executorch::Error) { mod.call(wrong_shape) } + assert_kind_of Integer, err.code + refute_nil err.pal_log + refute_empty err.pal_log + + assert_raises(Executorch::Error) { mod.forward } + end + end + + # 7. Sequential execute calls with DISTINCT inputs must NOT alias or overwrite earlier outputs + def test_sequential_execute_outputs_are_independent + spec = model_spec(:add_mul) + Executorch::Module.open(fixture_path(spec["file"])) do |mod| + in1 = Executorch::Tensor.new([[1.0, 2.0, 3.0]]) + in2 = Executorch::Tensor.new([[10.0, 20.0, 30.0]]) + + out1 = mod.call(in1) + out2 = mod.call(in2) + + assert_equal [[3.0, 5.0, 7.0]], out1.to_a + assert_equal [[21.0, 41.0, 61.0]], out2.to_a + assert_equal [[1.0, 2.0, 3.0]], in1.to_a + assert_equal [[10.0, 20.0, 30.0]], in2.to_a + end + end + + # 8. GC.stress and GC.compact stability + def test_gc_stress_and_compaction + spec = model_spec(:add_mul) + Executorch::Module.open(fixture_path(spec["file"])) do |mod| + prev = GC.stress + begin + GC.stress = true + 3.times do |i| + t = Executorch::Tensor.new([[i.to_f, i + 1.0, i + 2.0]]) + out = mod.call(t) + assert_equal [[i * 2.0 + 1.0, (i + 1) * 2.0 + 1.0, (i + 2) * 2.0 + 1.0]], out.to_a + end + ensure + GC.stress = prev + end + + GC.compact if GC.respond_to?(:compact) + # Exercise every cached Ruby class VALUE (MethodMeta, TensorInfo, Tensor, Errors) after GC.compact + meta = mod.meta(:forward) + assert_equal "forward", meta.name + assert_equal 1, meta.inputs.size + assert_raises(Executorch::MethodNotFoundError) { mod.meta(:missing_after_compact) } + out = mod.call(Executorch::Tensor.new([[2.0, 3.0, 4.0]])) + assert_equal [[5.0, 7.0, 9.0]], out.to_a + end + end + + # 9. Multi-threaded GVL release proof & thread-safety under concurrent calls + def test_gvl_released_and_concurrent_thread_safety + spec = model_spec(:heavy_mlp) + pte = fixture_path(spec["file"]) + input = tensor_from_golden(spec["inputs"].first) + + # A. Prove background Ruby thread ticks continuously during native inference + Executorch::Module.open(pte) do |mod| + mod.load_method(:forward) + ready = Queue.new + ticks = 0 + stop = false + ticker = Thread.new do + ready << true + until stop + ticks += 1 + Thread.pass + end + end + ready.pop + + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 2.0 + runs = 0 + while runs < 40 && (ticks < 50 || runs < 5) && Process.clock_gettime(Process::CLOCK_MONOTONIC) < deadline + mod.call(input) + runs += 1 + end + stop = true + ticker.join + + assert_operator ticks, :>, 10, "Background Ruby thread starved (ticks=#{ticks}, runs=#{runs}) — GVL was held!" + end + + # B. 4 threads sharing ONE Module instance serialize safely with exact results + Executorch::Module.open(pte) do |shared| + threads = 4.times.map do + Thread.new do + 5.times do + out = shared.call(input) + assert_tensor_matches_golden(out, spec["outputs"].first, rtol: 1e-2, atol: 1e-3) + end + end + end + threads.each(&:join) + end + + # C. 2 threads with independent Module instances execute cleanly in parallel + threads = 2.times.map do + Thread.new do + Executorch::Module.open(pte) do |mod| + 5.times do + out = mod.call(input) + assert_tensor_matches_golden(out, spec["outputs"].first, rtol: 1e-2, atol: 1e-3) + end + end + end + end + threads.each(&:join) + end + + # 10. Memory stability check (no C++ leak across 2,000 iterations) + def test_no_unbounded_rss_growth + spec = model_spec(:add_mul) + raw_in = [1.0, 2.0, 3.0].pack("f*") + + Executorch::Module.open(fixture_path(spec["file"])) do |mod| + # Warmup + 50.times { mod.call(Executorch::Tensor.from_bytes(raw_in, shape: [1, 3])) } + GC.start(full_mark: true, immediate_sweep: true) + rss_before = current_rss_kb + + 2_000.times do + t = Executorch::Tensor.from_bytes(raw_in, shape: [1, 3]) + out = mod.call(t) + out.to_bytes + end + GC.start(full_mark: true, immediate_sweep: true) + rss_after = current_rss_kb + + if rss_before && rss_after + delta_mb = (rss_after - rss_before) / 1024.0 + assert_operator delta_mb, :<, 32.0, "RSS grew by #{delta_mb.round(2)} MB over 2,000 iterations" + end + end + end + + private + + def current_rss_kb + return nil unless File.readable?("/proc/self/status") + + line = File.readlines("/proc/self/status").find { |l| l.start_with?("VmRSS:") } + line ? line.split[1].to_i : nil + end +end diff --git a/test/support/README.md b/test/support/README.md deleted file mode 100644 index 3e817b4..0000000 --- a/test/support/README.md +++ /dev/null @@ -1,77 +0,0 @@ -# Test Models - -This directory should contain `.pte` (PyTorch ExecuTorch) model files for testing. - -## Creating Test Models - -You need Python with PyTorch and ExecuTorch installed: - -```bash -pip install torch executorch -``` - -### Simple Model (simple.pte) - -Create a simple model that doubles and adds 1: - -```python -# scripts/export_simple_model.py -import torch -from executorch.exir import to_edge - -class SimpleModel(torch.nn.Module): - def forward(self, x): - return x * 2 + 1 - -model = SimpleModel() -example = torch.randn(1, 3) - -# Export to ExecuTorch format -exported = torch.export.export(model, (example,)) -edge = to_edge(exported) -et_program = edge.to_executorch() - -# Save to file -with open("test/support/models/simple.pte", "wb") as f: - et_program.write_to_file(f) - -print("Created simple.pte") -``` - -### Linear Model (linear.pte) - -A model with a linear layer: - -```python -# scripts/export_linear_model.py -import torch -from executorch.exir import to_edge - -class LinearModel(torch.nn.Module): - def __init__(self): - super().__init__() - self.linear = torch.nn.Linear(10, 5) - - def forward(self, x): - return self.linear(x) - -model = LinearModel() -example = torch.randn(1, 10) - -exported = torch.export.export(model, (example,)) -edge = to_edge(exported) -et_program = edge.to_executorch() - -with open("test/support/models/linear.pte", "wb") as f: - et_program.write_to_file(f) - -print("Created linear.pte") -``` - -## Running Export Scripts - -```bash -mkdir -p test/support/models -python scripts/export_simple_model.py -python scripts/export_linear_model.py -``` diff --git a/test/support/models/.gitkeep b/test/support/models/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/test/tensor_test.rb b/test/tensor_test.rb index 1a674eb..1ec0ff6 100644 --- a/test/tensor_test.rb +++ b/test/tensor_test.rb @@ -1,340 +1,171 @@ # frozen_string_literal: true -require "test_helper" +require_relative "test_helper" class TensorTest < Minitest::Test - # =========================================================================== - # Tests for nested array INPUT (Tensor.new with shape inference) - # =========================================================================== - - # --- Basic nested array creation --- - - def test_create_1d_tensor_from_flat_array - tensor = Executorch::Tensor.new([1.0, 2.0, 3.0]) - assert_equal [3], tensor.shape - assert_equal 3, tensor.numel - end - - def test_create_2d_tensor_from_nested_array - tensor = Executorch::Tensor.new([[1.0, 2.0], [3.0, 4.0]]) - assert_equal [2, 2], tensor.shape - assert_equal 4, tensor.numel - end - - def test_create_3d_tensor_from_nested_array - data = [ - [[1.0, 2.0], [3.0, 4.0]], - [[5.0, 6.0], [7.0, 8.0]] - ] - tensor = Executorch::Tensor.new(data) - assert_equal [2, 2, 2], tensor.shape - assert_equal 8, tensor.numel - end - - def test_create_4d_tensor_from_nested_array - # Shape [2, 1, 2, 3] - data = [ - [[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]], - [[[7.0, 8.0, 9.0], [10.0, 11.0, 12.0]]] - ] - tensor = Executorch::Tensor.new(data) - assert_equal [2, 1, 2, 3], tensor.shape - assert_equal 12, tensor.numel - end - - # --- Non-square arrays --- - - def test_create_2d_non_square_tensor - tensor = Executorch::Tensor.new([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) - assert_equal [2, 3], tensor.shape - end - - def test_create_2d_tall_tensor - tensor = Executorch::Tensor.new([[1.0], [2.0], [3.0], [4.0]]) - assert_equal [4, 1], tensor.shape - end - - # --- Single element tensors --- - - def test_create_single_element_1d - tensor = Executorch::Tensor.new([42.0]) - assert_equal [1], tensor.shape - assert_equal 1, tensor.numel - end - - def test_create_single_element_2d - tensor = Executorch::Tensor.new([[42.0]]) - assert_equal [1, 1], tensor.shape - assert_equal 1, tensor.numel - end - - def test_create_single_element_3d - tensor = Executorch::Tensor.new([[[42.0]]]) - assert_equal [1, 1, 1], tensor.shape - assert_equal 1, tensor.numel - end - - def test_create_single_element_4d - tensor = Executorch::Tensor.new([[[[42.0]]]]) - assert_equal [1, 1, 1, 1], tensor.shape - assert_equal 1, tensor.numel - end - - # --- Empty arrays --- - - def test_create_empty_1d_tensor - tensor = Executorch::Tensor.new([]) - assert_equal [0], tensor.shape - assert_equal 0, tensor.numel - end - - def test_create_empty_2d_tensor - tensor = Executorch::Tensor.new([[], []]) - assert_equal [2, 0], tensor.shape - assert_equal 0, tensor.numel - end - - # --- Data types --- - - def test_infer_float_dtype_from_floats - tensor = Executorch::Tensor.new([1.0, 2.0, 3.0]) - assert_equal :float, tensor.dtype - end - - def test_infer_float_dtype_from_integers - # Integers should be coerced to float by default - tensor = Executorch::Tensor.new([1, 2, 3]) - assert_equal :float, tensor.dtype - end - - def test_explicit_dtype_int - tensor = Executorch::Tensor.new([1, 2, 3], dtype: :int) - assert_equal :int, tensor.dtype - end - - def test_explicit_dtype_long - tensor = Executorch::Tensor.new([1, 2, 3], dtype: :long) - assert_equal :long, tensor.dtype - end - - def test_explicit_dtype_double - tensor = Executorch::Tensor.new([1.0, 2.0], dtype: :double) - assert_equal :double, tensor.dtype - end - - def test_nested_array_with_explicit_dtype - tensor = Executorch::Tensor.new([[1, 2], [3, 4]], dtype: :long) - assert_equal [2, 2], tensor.shape - assert_equal :long, tensor.dtype - end - - # --- Error cases: Jagged arrays --- - - def test_jagged_array_raises_error - assert_raises(ArgumentError) do - Executorch::Tensor.new([[1, 2], [3]]) + ALL_DTYPES = %i[ + float32 float64 float16 bfloat16 + uint8 int8 int16 uint16 int32 uint32 int64 uint64 + bool + ].freeze + + def test_all_supported_dtypes_round_trip + ALL_DTYPES.each do |dtype| + input = dtype == :bool ? [true, false, true, false] : [0, 1, 2, 3] + t = Executorch::Tensor.new(input, shape: [2, 2], dtype: dtype) + + assert_equal dtype, t.dtype + assert_equal [2, 2], t.shape + assert_equal 2, t.dim + assert_equal 2, t.ndim + assert_equal 4, t.numel + assert_predicate t, :contiguous? + assert_equal [2, 1], t.strides + assert_equal [0, 1], t.dim_order + + # Nested to_a + if dtype == :bool + assert_equal [[true, false], [true, false]], t.to_a + elsif %i[float32 float64 float16 bfloat16].include?(dtype) + assert_equal [[0.0, 1.0], [2.0, 3.0]], t.to_a + else + assert_equal [[0, 1], [2, 3]], t.to_a + end + + # Binary round-trip + bytes = t.to_bytes + assert_equal Encoding::ASCII_8BIT, bytes.encoding + assert_equal t.nbytes, bytes.bytesize + + t2 = Executorch::Tensor.from_bytes(bytes, shape: [2, 2], dtype: dtype) + assert_equal t, t2 + assert_equal t.to_a, t2.to_a + + # IO::Buffer round-trip + buf = t.to_buffer + assert_instance_of IO::Buffer, buf + assert_equal t.nbytes, buf.size + t3 = Executorch::Tensor.from_buffer(buf, shape: [2, 2], dtype: dtype) + assert_equal t, t3 + assert_equal t.to_a, t3.to_a end end - def test_jagged_array_3d_raises_error - assert_raises(ArgumentError) do - Executorch::Tensor.new([[[1, 2], [3, 4]], [[5], [6]]]) + def test_dtype_aliases_map_to_canonical_symbols + aliases = { + float: :float32, + double: :float64, + half: :float16, + bf16: :bfloat16, + byte: :uint8, + char: :int8, + short: :int16, + int: :int32, + long: :int64, + } + aliases.each do |alias_sym, canonical| + t = Executorch::Tensor.new([1, 2], dtype: alias_sym) + assert_equal canonical, t.dtype end end - def test_deeply_jagged_array_raises_error - assert_raises(ArgumentError) do - Executorch::Tensor.new([[[1, 2]], [[3]]]) - end - end - - def test_mixed_nesting_raises_error - # First element is scalar, second is array - assert_raises(ArgumentError) do - Executorch::Tensor.new([1, [2, 3]]) - end - end - - def test_inconsistent_nesting_depth_raises_error - assert_raises(ArgumentError) do - Executorch::Tensor.new([[1, 2], [[3, 4]]]) - end - end - - # --- Backward compatibility: explicit shape still works --- - - def test_explicit_shape_with_flat_array - tensor = Executorch::Tensor.new([1.0, 2.0, 3.0, 4.0], shape: [2, 2], dtype: :float) - assert_equal [2, 2], tensor.shape - assert_equal :float, tensor.dtype - end - - def test_explicit_shape_overrides_nesting - # Even if data looks nested, explicit shape takes precedence - # This tests backward compatibility - tensor = Executorch::Tensor.new([1.0, 2.0, 3.0, 4.0], shape: [4], dtype: :float) - assert_equal [4], tensor.shape - end - - # =========================================================================== - # Tests for nested array OUTPUT (to_a returns nested structure) - # =========================================================================== - - # --- Basic reshaping --- - - def test_to_a_1d_returns_flat_array - tensor = Executorch::Tensor.new([1.0, 2.0, 3.0], shape: [3], dtype: :float) - assert_equal [1.0, 2.0, 3.0], tensor.to_a - end - - def test_to_a_2d_returns_nested_array - tensor = Executorch::Tensor.new([1.0, 2.0, 3.0, 4.0], shape: [2, 2], dtype: :float) - expected = [[1.0, 2.0], [3.0, 4.0]] - assert_equal expected, tensor.to_a - end - - def test_to_a_2d_non_square - tensor = Executorch::Tensor.new([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape: [2, 3], dtype: :float) - expected = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]] - assert_equal expected, tensor.to_a - end - - def test_to_a_2d_tall - tensor = Executorch::Tensor.new([1.0, 2.0, 3.0, 4.0], shape: [4, 1], dtype: :float) - expected = [[1.0], [2.0], [3.0], [4.0]] - assert_equal expected, tensor.to_a - end - - def test_to_a_3d_returns_nested_array - data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0] - tensor = Executorch::Tensor.new(data, shape: [2, 2, 2], dtype: :float) - expected = [ - [[1.0, 2.0], [3.0, 4.0]], - [[5.0, 6.0], [7.0, 8.0]] - ] - assert_equal expected, tensor.to_a - end - - def test_to_a_4d_returns_nested_array - data = (1..24).map(&:to_f) - tensor = Executorch::Tensor.new(data, shape: [2, 3, 2, 2], dtype: :float) - result = tensor.to_a - - assert_equal 2, result.size - assert_equal 3, result[0].size - assert_equal 2, result[0][0].size - assert_equal 2, result[0][0][0].size - assert_equal 1.0, result[0][0][0][0] - assert_equal 24.0, result[1][2][1][1] - end - - # --- Single element tensors --- - - def test_to_a_single_element_1d - tensor = Executorch::Tensor.new([42.0], shape: [1], dtype: :float) - assert_equal [42.0], tensor.to_a - end - - def test_to_a_single_element_2d - tensor = Executorch::Tensor.new([42.0], shape: [1, 1], dtype: :float) - assert_equal [[42.0]], tensor.to_a - end - - def test_to_a_single_element_3d - tensor = Executorch::Tensor.new([42.0], shape: [1, 1, 1], dtype: :float) - assert_equal [[[42.0]]], tensor.to_a - end - - # --- Empty tensors --- - - def test_to_a_empty_1d - tensor = Executorch::Tensor.new([], shape: [0], dtype: :float) - assert_equal [], tensor.to_a - end - - def test_to_a_empty_2d - tensor = Executorch::Tensor.new([], shape: [2, 0], dtype: :float) - assert_equal [[], []], tensor.to_a - end - - def test_to_a_empty_3d - tensor = Executorch::Tensor.new([], shape: [2, 3, 0], dtype: :float) - expected = [[[], [], []], [[], [], []]] - assert_equal expected, tensor.to_a - end - - # --- Round-trip tests --- - - def test_roundtrip_2d_nested_array - original = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]] - tensor = Executorch::Tensor.new(original) - assert_equal original, tensor.to_a - end - - def test_roundtrip_3d_nested_array - original = [ - [[1.0, 2.0], [3.0, 4.0]], - [[5.0, 6.0], [7.0, 8.0]] - ] - tensor = Executorch::Tensor.new(original) - assert_equal original, tensor.to_a - end - - def test_roundtrip_non_square - original = [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0]] - tensor = Executorch::Tensor.new(original) - assert_equal [3, 4], tensor.shape - assert_equal original, tensor.to_a - end - - def test_roundtrip_with_integers_and_long_dtype - original = [[1, 2], [3, 4]] - tensor = Executorch::Tensor.new(original, dtype: :long) - result = tensor.to_a - assert_equal [[1, 2], [3, 4]], result - end - - # --- Data type preservation in output --- - - def test_to_a_preserves_float_values - tensor = Executorch::Tensor.new([[1.5, 2.5], [3.5, 4.5]]) - result = tensor.to_a - assert_in_delta 1.5, result[0][0], 0.001 - assert_in_delta 4.5, result[1][1], 0.001 - end - - def test_to_a_preserves_integer_values_with_long_dtype - tensor = Executorch::Tensor.new([[100, 200], [300, 400]], dtype: :long) - result = tensor.to_a - assert_equal 100, result[0][0] - assert_equal 400, result[1][1] - end - - # --- Edge case: very deep nesting --- - - def test_5d_tensor_roundtrip - # Shape [2, 1, 2, 1, 3] - original = [ - [[[[1.0, 2.0, 3.0]], [[4.0, 5.0, 6.0]]]], - [[[[7.0, 8.0, 9.0]], [[10.0, 11.0, 12.0]]]] - ] - tensor = Executorch::Tensor.new(original) - assert_equal [2, 1, 2, 1, 3], tensor.shape - assert_equal original, tensor.to_a - end - - # =========================================================================== - # Tests for flat_to_a (backward compatibility method) - # =========================================================================== - - def test_flat_to_a_returns_flat_array - tensor = Executorch::Tensor.new([1.0, 2.0, 3.0, 4.0], shape: [2, 2], dtype: :float) - assert_equal [1.0, 2.0, 3.0, 4.0], tensor.flat_to_a - end - - def test_flat_to_a_for_3d_tensor - data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0] - tensor = Executorch::Tensor.new(data, shape: [2, 2, 2], dtype: :float) - assert_equal data, tensor.flat_to_a + def test_nested_array_shape_inference_and_explicit_nested_reshape + t = Executorch::Tensor.new([[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]]]) + assert_equal [2, 2, 2], t.shape + assert_equal :float32, t.dtype + assert_equal [[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]]], t.to_a + assert_equal [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], t.flat_to_a + + # Explicit shape with nested array now works cleanly + t_flat = Executorch::Tensor.new([[1.0, 2.0], [3.0, 4.0]], shape: [4]) + assert_equal [4], t_flat.shape + assert_equal [1.0, 2.0, 3.0, 4.0], t_flat.to_a + end + + def test_zero_dim_scalar_tensor + t = Executorch::Tensor.new(42.5, dtype: :float32) + assert_equal [], t.shape + assert_equal 0, t.dim + assert_equal 1, t.numel + assert_equal 4, t.nbytes + assert_in_delta 42.5, t.item, 1e-5 + assert_in_delta 42.5, t.to_a, 1e-5 + + t_b = Executorch::Tensor.from_bytes([42.5].pack("f"), shape: [], dtype: :float32) + assert_equal t, t_b + assert_in_delta 42.5, t_b.item, 1e-5 + + t_bool = Executorch::Tensor.new(true, dtype: :bool) + assert_equal [], t_bool.shape + assert_equal true, t_bool.item + assert_equal true, t_bool.to_a + end + + def test_empty_tensors + t0 = Executorch::Tensor.new([], dtype: :float32) + assert_equal [0], t0.shape + assert_equal 0, t0.numel + assert_equal 0, t0.nbytes + assert_predicate t0, :empty? + assert_equal [], t0.to_a + assert_equal "".b, t0.to_bytes + + t20 = Executorch::Tensor.new([[], []], dtype: :int32) + assert_equal [2, 0], t20.shape + assert_equal 0, t20.numel + assert_equal [[], []], t20.to_a + + tb = Executorch::Tensor.from_bytes("", shape: [0], dtype: :float32) + assert_equal t0, tb + end + + def test_factory_constructors_zeros_ones_full + z = Executorch::Tensor.zeros([2, 3], dtype: :float32) + assert_equal [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], z.to_a + + o = Executorch::Tensor.ones([2, 2], dtype: :int64) + assert_equal [[1, 1], [1, 1]], o.to_a + + f = Executorch::Tensor.full([2], 7, dtype: :uint8) + assert_equal [7, 7], f.to_a + end + + def test_zero_copy_io_buffer_reflects_mutations_and_detects_resize + buf = IO::Buffer.new(16) + buf.set_string([1.0, 2.0, 3.0, 4.0].pack("f*")) + t = Executorch::Tensor.from_buffer(buf, shape: [2, 2], dtype: :float32) + assert_equal [[1.0, 2.0], [3.0, 4.0]], t.to_a + + # Mutate underlying IO::Buffer in place — zero-copy view reflects it immediately + buf.set_value(:f32, 0, 99.0) + assert_equal [[99.0, 2.0], [3.0, 4.0]], t.to_a + + # Resizing underlying buffer is caught safely instead of UAF + buf.resize(8) + assert_raises(Executorch::ShapeError) { t.to_a } + end + + def test_equality_inspect_and_close + a = Executorch::Tensor.new([1, 2], dtype: :int32) + b = Executorch::Tensor.new([1, 2], dtype: :int32) + c = Executorch::Tensor.new([1, 2], dtype: :int64) + d = Executorch::Tensor.new([1, 3], dtype: :int32) + + assert_equal a, b + refute_equal a, c + refute_equal a, d + refute_equal a, [1, 2] + + assert_includes a.inspect, "Executorch::Tensor" + assert_includes a.inspect, "dtype=:int32" + refute_predicate a, :closed? + + a.close + assert_predicate a, :closed? + assert_includes a.inspect, "closed" + assert_raises(Executorch::ClosedError) { a.to_a } + assert_raises(Executorch::ClosedError) { a.shape } + # Idempotent close + a.close end end diff --git a/test/test_helper.rb b/test/test_helper.rb index 2a63ea6..1a0b2a3 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,28 +1,58 @@ # frozen_string_literal: true $LOAD_PATH.unshift File.expand_path("../lib", __dir__) - require "executorch" +require "json" +require "pathname" require "minitest/autorun" module TestHelper - # Path to test models directory - def models_dir - File.expand_path("support/models", __dir__) + FIXTURES_DIR = File.expand_path("fixtures/models", __dir__) + MANIFEST_PATH = File.join(FIXTURES_DIR, "manifest.json") + + def fixtures_manifest + @fixtures_manifest ||= begin + unless File.exist?(MANIFEST_PATH) + raise "Missing test fixtures at #{MANIFEST_PATH}. Run `bundle exec rake fixtures:export` first." + end + + JSON.parse(File.read(MANIFEST_PATH)) + end end - # Path to a specific test model - def model_path(name) - File.join(models_dir, name) + def model_spec(name) + fixtures_manifest.fetch("models").fetch(name.to_s) end - # Check if test models are available - def models_available? - File.directory?(models_dir) && !Dir.glob(File.join(models_dir, "*.pte")).empty? + def fixture_path(rel) + File.join(FIXTURES_DIR, rel) end - # Skip test if models are not available - def skip_without_models - skip "Test models not available. See test/support/README.md" unless models_available? + def tensor_from_golden(desc) + dtype = desc.fetch("dtype").to_sym + Executorch::Tensor.new(desc.fetch("values"), shape: desc.fetch("shape"), dtype: dtype) + end + + def assert_tensor_matches_golden(actual, golden, rtol: 1e-3, atol: 1e-4) + assert_instance_of Executorch::Tensor, actual + assert_equal golden.fetch("shape"), actual.shape, "shape mismatch" + assert_equal golden.fetch("dtype").to_sym, actual.dtype, "dtype mismatch" + + got = actual.flat_to_a + exp = golden.fetch("values") + assert_equal exp.size, got.size, "element count mismatch" + + exp.each_with_index do |e, i| + g = got[i] + if e == true || e == false + assert_equal e, g, "bool mismatch at index #{i}" + elsif e.is_a?(Integer) && actual.dtype != :float32 && actual.dtype != :float64 && + actual.dtype != :float16 && actual.dtype != :bfloat16 + assert_equal e, g, "int mismatch at index #{i}" + else + tol = atol + rtol * e.abs + assert_in_delta e, g, tol, "value mismatch at index #{i}: expected #{e}, got #{g}" + end + end end end