From b9eb21532279aabebe80e0d096567b4be9f72ac9 Mon Sep 17 00:00:00 2001 From: Benjamin Garcia Date: Fri, 20 Nov 2026 12:52:33 -0800 Subject: [PATCH] docs: rewrite README as a clean library introduction and move install notes to CHANGELOG --- CHANGELOG.md | 2 +- README.md | 152 +++++++++++++++++++++++++++------------------------ 2 files changed, 81 insertions(+), 73 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 284d2ce..cc1d4da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,7 +25,7 @@ Complete from-scratch rewrite targeting ExecuTorch 1.6.0 and Ruby >= 3.2. - 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. +- Precompiled platform gems (`x86_64-linux`, `aarch64-linux`, `arm64-darwin`) bundling the official ExecuTorch 1.6.0 shared SDK (XNNPACK, optimized & quantized kernels, CoreML/MLX on Apple Silicon) plus a pure-stdlib SHA-256-verified SDK fetcher for source installs — no Python, CMake, or Buck2 required at install or inference time. - 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 diff --git a/README.md b/README.md index 1ddc8c1..0ebd41d 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,12 @@ -# Executorch for Ruby +# executorch-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) -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. +Native Ruby bindings for Meta's [ExecuTorch](https://pytorch.org/executorch/) runtime (`1.6.0`), built directly on the Ruby C API. -## Why ExecuTorch in Ruby? - -- **`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. - -## Platform & Delegate Support - -| 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`) | - -Requires **Ruby `>= 3.2`**. +Run exported PyTorch models (`.pte` / `.ptd`) in Ruby with precompiled platform gems, GVL-free execution, zero-copy `IO::Buffer` tensors, and hardware delegates (XNNPACK, CoreML, MLX). ## Installation @@ -41,9 +22,20 @@ Or install directly: gem install executorch ``` -## Quick Start: PyTorch to Ruby in 60 Seconds +Requires **Ruby `>= 3.2`**. + +### Supported platforms + +| Platform | Precompiled Gem | Bundled Delegates & Kernels | +|---|---|---| +| `x86_64-linux` | Yes | XNNPACK, Optimized CPU, Quantized | +| `aarch64-linux` | Yes | XNNPACK (KleidiAI), Optimized CPU, Quantized, TorchAO | +| `arm64-darwin` | Yes | XNNPACK, CoreML, MLX, Optimized CPU, Quantized, TorchAO | +| Source (`ruby`) | Yes | Fetches the official ExecuTorch 1.6.0 C++ SDK (or uses `--with-executorch-dir`) | + +## Quick Start -### 1. Export a PyTorch model to `.pte` (once, in Python) +Export a PyTorch model to `.pte` using ExecuTorch: ```python import torch @@ -64,13 +56,11 @@ with open("model.pte", "wb") as f: et_program.write_to_file(f) ``` -### 2. Run it natively in Ruby (no Python required) +Load and run it in Ruby: ```ruby require "executorch" -# 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"] @@ -84,85 +74,106 @@ end ## Usage -### Zero-copy `IO::Buffer` and pre-allocated output reuse +### Modules -For hot inference loops (images, audio, embeddings), avoid array boxing and per-call allocations completely: +`Executorch::Module.open` accepts a `String` or `Pathname`, defaults to `:mmap` loading (sharing read-only weight pages across forked Puma/Unicorn workers), and closes deterministically when given a block. ```ruby -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) - -input = Executorch::Tensor.from_buffer(in_buf, shape: [1, 3], dtype: :float32) -output = Executorch::Tensor.from_buffer(out_buf, shape: [1, 3], dtype: :float32) - -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 -``` - -### Multi-method models, external `.ptd` weights, and in-memory loading +# Load modes: :mmap (default), :file, :mmap_mlock, :mmap_mlock_ignore_errors, :mmap_madvise +mod = Executorch::Module.open(Pathname.new("model.pte"), load_mode: :mmap) +mod.load_method(:forward) # optional pre-warm before serving requests +out = mod.call(input) +mod.close -```ruby -# 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 +# Multi-method programs +Executorch::Module.open("autoencoder.pte") do |m| + z = m.execute(:encode, x).first + reconstructed = m.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) +# External .ptd weight files +Executorch::Module.open("model.pte", data_files: ["weights.ptd"]) do |m| + logits = m.call(tokens) end -# Load straight from memory (e.g. S3 / ActiveStorage) without a tempfile +# Load directly from an in-memory String (e.g. S3 or ActiveStorage) mod = Executorch::Module.from_bytes(pte_bytes) mod.close ``` -### Tensors, dtypes & ecosystem adapters +- `#call(*inputs, out: nil)` runs `"forward"` and returns the single output directly when there is one output, or an `Array` otherwise. +- `#forward(*inputs, out: nil)` and `#execute(name, *inputs, out: nil)` always return an `Array`. +- `#meta(name = :forward)` returns an `Executorch::MethodMeta` describing input/output shapes, dtypes, planned memory size, and lowered backends without loading the full method. + +### Tensors -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. +Supported dtypes: `:float32`, `:float64`, `:float16`, `:bfloat16`, `:uint8`, `:int8`, `:int16`, `:uint16`, `:int32`, `:uint32`, `:int64`, `:uint64`, and `:bool`. Short aliases (`:float`, `:double`, `:half`, `:byte`, `:char`, `:short`, `:int`, `:long`) are accepted at construction. ```ruby 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]] +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 +# Packed 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) +full = Executorch::Tensor.full([2, 3], 7, dtype: :uint8) ``` -Optional adapters are built in for `Numo::NArray` (`Tensor.from_numo` / `Tensor#to_numo`) and `Torch::Tensor` (`Tensor.from_torch`). +Optional adapters are provided for `Numo::NArray` (`Tensor.from_numo` / `Tensor#to_numo`) and `Torch::Tensor` (`Tensor.from_torch`). -### Runtime introspection & typed errors +### Zero-copy `IO::Buffer` and output reuse + +Pass Ruby `IO::Buffer` instances directly into ExecuTorch without copying or allocating intermediate arrays. Pairing `Tensor.from_buffer` with `out:` writes inference outputs straight into a caller-owned buffer: + +```ruby +in_buf = IO::Buffer.for([1.0, 2.0, 3.0].pack("f*")) +out_buf = IO::Buffer.new(12) + +input = Executorch::Tensor.from_buffer(in_buf, shape: [1, 3], dtype: :float32) +output = Executorch::Tensor.from_buffer(out_buf, shape: [1, 3], dtype: :float32) + +Executorch::Module.open("model.pte") do |mod| + mod.call(input, out: output) + p out_buf.get_string.unpack("f*") # => [3.0, 5.0, 7.0] +end +``` + +### Concurrency, runtime introspection & errors ```ruby Executorch.backends # => ["XnnpackBackend"] Executorch.kernel_count # => 263 Executorch.num_threads # => 24 +Executorch.num_threads = 2 # size the ExecuTorch threadpool for multi-worker servers Executorch.executorch_version # => "1.6.0" ``` -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). +- **GVL release & thread safety:** Model loading and execution release the Ruby GVL (`rb_thread_call_without_gvl`). Calls on separate `Module` instances run in parallel across cores; concurrent calls to the same method on a shared `Module` serialize safely via a per-method mutex. +- **Typed errors:** Runtime failures inherit from `Executorch::Error < StandardError` (`LoadError`, `MethodNotFoundError`, `OperatorMissingError`, `DelegateError`, `ShapeError`, `DTypeError`, `ExecutionError`, `MemoryError`, `ClosedError`) and expose `#code` and `#pal_log`. + +## Architecture + +The native extension is written directly against the Ruby C API (no binding generator or runtime gem dependencies) in two layers: + +- **`ext/executorch/core/`** — A `noexcept` C++17 core with zero Ruby headers. Handles ExecuTorch lifecycle, per-method locking, thread-local PAL log capture, overflow-checked shape math, and strided/`NHWC` layout normalization. +- **`ext/executorch/rb_*.cpp`** — A thin Ruby C-API layer managing `TypedData`, `dsize` + `rb_gc_adjust_memory_usage`, `GC.compact`-safe global roots, `rb_io_buffer_lock` around GVL-free execution, and single-pass C++ nested-array flattening. All C++ stack objects are destroyed before any Ruby exception is raised. +- **Symbol isolation:** Compiled with `-fvisibility=hidden` and a linker export map so only `Init_executorch` is exported, avoiding symbol collisions with `torch.rb`, `onnxruntime`, or `ruby-vips`. -### Using a custom ExecuTorch installation +## Custom ExecuTorch builds -If you built ExecuTorch yourself (shared or static), point `extconf.rb` at its absolute prefix: +To compile against a local ExecuTorch installation instead of the default SDK: ```bash bundle config set --local build.executorch --with-executorch-dir=/absolute/path/to/executorch @@ -170,12 +181,9 @@ bundle config set --local build.executorch --with-executorch-dir=/absolute/path/ Or pass `EXECUTORCH_DIR=/absolute/path/to/executorch`. Set `EXECUTORCH_NO_DOWNLOAD=1` to disable automatic SDK fetching. -## Upgrading from 0.1.x +## Changelog -- `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. +See [CHANGELOG.md](CHANGELOG.md) for release notes and migration details. ## Development @@ -184,11 +192,11 @@ bundle install 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) +bundle exec rake test # Runs full test suite ruby bench/run_bench.rb # Runs local latency benchmarks ``` -To build and test under AddressSanitizer + UndefinedBehaviorSanitizer on Linux: +To run the suite under AddressSanitizer + UndefinedBehaviorSanitizer on Linux: ```bash bundle exec rake clean