← Open Source

A ground-up and standalone reimplementation of TensorFlow for ruby. Comes with a pure ruby and OpenCL opcode evaluator.

Model DevelopmentDeep Learning FrameworksRuby
Momentum
+0stars in 24 hours0.0%
502
Stars
16
Forks
+0
This week
3
Contributors
Created 2018-05-11 · Updated 2026-11-23 · #23620 today
Top developers
README

TensorStream

TensorStream is an opensource framework for machine learning for ruby, its goal is to allow machine learning models to be easily built and run them in various hardware like GPUs and CPUs. It is heavily based on TensorFlow with the goal of being able to easily port its higher level libraries and model examples. As such it is also based on data flow graphs wherein you define computations and data flows between those computations in order to achieve the desired output.

TensorStream is designed to support various backends with a Pure Ruby and OpenCL implementation. These implementations are designed to work together, you can perform training on an OpenCL implementation (where you have a GPU) and then run the resulting trained model on a Pure Ruby implementation where you can deploy anywhere that you can run ruby on. TensorStream has been tested to run on most ruby implementations like MRI, JRuby and TruffleRuby.

Goals & Features

  • Easy to use - Improve model readability
  • Replicates most of the commonly used low-level tensorflow ops (tf.add, tf.constant, tf.placeholder, tf.matmul, tf.sin etc...)
  • Supports auto-differentiation using formal derivation, plus faster tape based reverse mode autodiff (tape_gradients / with_tape)
  • Eager execution (define-by-run) mode with immediate tensor values, TF2 style
  • Optional Numo::NArray kernels for elementwise ops, reductions, matmul, softmax/cross-entropy and bias_add (installed automatically when the numo-narray gem is present)
  • Extensible - use your own opcode evaluator (OpenCL and Pure ruby currently supported)
  • wide support - Run on most ruby implementations as well as hardware acceleration on OpenCL supported hardware

Compatibility

TensorStream comes with a pure ruby and OpenCL implementation out of the box. The pure ruby implementation requires Ruby >= 3.1 and is known to work with most ruby implementations including TruffleRuby, JRuby as well as jit enabled versions of mri.

OpenCL is supported only on mri implementations of ruby. This can be enabled by adding OpenCL evaluator gem (Make sure you have OpenCL drivers installed correctly on your system):

gem 'tensor_stream-opencl'

and then (without bundler)

require 'tensor_stream/opencl'

The opencl evaluator works with the numo-narray fast path (values convert at evaluator boundaries) and its full op suite runs in CI against the POCL software device, so it can be developed without GPU drivers. Note that variable storage and optimizer updates run on the ruby evaluator (host side); GPU-resident variable storage is planned. Eager execution always evaluates on the ruby evaluator.

OpenCL is basically a requirement for deep learning and image processing tasks as the ruby implementation is too slow even with jit speedups using latest ruby implementations.

OpenCL kernels used by tensorstream can be found in the tensor_stream-opencl gem (under lib/evaluator/opencl/kernels). These are non specific and should work with any device that supports OpenCL including intel GPUs and CPUs, as well as GPUs from Nvidia and AMD.

Installation

Installation is easy, no need to mess with docker, python, clang or other shennanigans, works with both mri and jruby out of the box.

Add this line to your application's Gemfile:

gem 'tensor_stream'

Note: the jpeg runtime dependency compiles a native extension and needs the libjpeg headers installed (Debian/Ubuntu: sudo apt-get install libjpeg-dev, Fedora: sudo dnf install libjpeg-turbo-devel, macOS: brew install jpeg).

For a large speedup on MRI (flat typed buffers via Numo::NArray for elementwise ops and matmul, ~3-70x depending on the op), add:

gem 'numo-narray'

TensorStream detects it automatically and falls back to pure ruby when absent. On GCC 14+ toolchains, numo-narray 0.9.2.1 needs a legacy C dialect to compile:

bundle config set build.numo-narray "--with-cflags=-std=gnu17"

And then execute:

$ bundle

Or install it yourself as:

$ gem install tensor_stream

Usage

Usage is similar to how you would use TensorFlow except with ruby syntax. There are also enhancements to the syntax to make it as consice as possible.

Linear regression sample:

require 'tensor_stream'

tf = TensorStream

learning_rate = 0.01
training_epochs = 1000
display_step = 50

train_x = [3.3, 4.4, 5.5, 6.71, 6.93, 4.168, 9.779, 6.182, 7.59, 2.167,
           7.042, 10.791, 5.313, 7.997, 5.654, 9.27, 3.1]

train_y = [1.7, 2.76, 2.09, 3.19, 1.694, 1.573, 3.366, 2.596, 2.53, 1.221,
           2.827, 3.465, 1.65, 2.904, 2.42, 2.94, 1.3]

n_samples = train_x.size

x_value = Float.placeholder
y_value = Float.placeholder

# Set model weights
weight = rand.t.var name: "weight"

bias = rand.t.var name: "bias"

# Construct a linear model
pred = x_value * weight + bias

# Mean squared error
cost = ((pred - y_value)**2).reduce / (2 * n_samples)

# Other optimizers --
#
# optimizer = TensorStream::Train::MomentumOptimizer.new(learning_rate, momentum, use_nesterov: true).minimize(cost)
# optimizer = TensorStream::Train::AdamOptimizer.new(learning_rate).minimize(cost)
# optimizer = TensorStream::Train::AdadeltaOptimizer.new(1.0).minimize(cost)
# optimizer = TensorStream::Train::AdagradOptimizer.new(0.01).minimize(cost)
# optimizer = TensorStream::Train::RMSPropOptimizer.new(0.01, centered: true).minimize(cost)
optimizer = TensorStream::Train::GradientDescentOptimizer.new(learning_rate).minimize(cost)

# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer

tf.session do |sess|
  start_time = Time.now
  sess.run(init)

  (0..training_epochs).each do |epoch|
    train_x.zip(train_y).each do |x, y|
      sess.run(optimizer, feed_dict: { x_value => x, y_value => y })
    end

    if (epoch + 1) % display_step == 0
      c = sess.run(cost, feed_dict: { x_value => train_x, y_value => train_y })
      puts("Epoch:", '%04d' % (epoch + 1), "cost=", c, \
           "W=", sess.run(weight), "b=", sess.run(bias))
    end
  end

  puts "Optimization Finished!"
  training_cost = sess.run(cost, feed_dict: { x_value => train_x, y_value => train_y })
  puts "Training cost=", training_cost, "W=", sess.run(weight), "b=", sess.run(bias), '\n'
  puts "time elapsed ", Time.now.to_i - start_time.to_i
end

You can take a look at spec/tensor_stream/operation_spec.rb for a list of supported ops and various examples and test cases used. Of course these contain only a sliver of what TensorFlow can do, so feel free to file a PR to add requested ops and test cases.

Other working samples can also be seen under tensor_stream/samples.

Samples that are used for development and are still being made to work can be found under test_samples

Eager execution

Eager execution evaluates operations immediately as they are created, like TensorFlow 2's eager mode. No sessions, no placeholders, no global_variables_initializer — every op carries its value right away:

require 'tensor_stream'
tf = TensorStream
tf.enable_eager_execution

x = tf.constant([[1.0, 2.0], [3.0, 4.0]])
y = x * 2
y.value # => [[2.0, 4.0], [6.0, 8.0]]

tf.sigmoid(x).value # values flow through chained ops immediately

# variables are created already initialized and update in place
w = tf.variable(tf.zeros([2]), name: "w")
w.assign([3.0, 4.0])
w.value # => [3.0, 4.0]
w.assign_add([1.0, 1.0])

tf.run(x * w) # shortcut for reading eager values (Session#run in deferred mode)

Gradients are captured with a tape while the forward pass runs (requires the numo-narray gem). Any optimizer can then consume the gradient values via apply_tape_gradients:

optimizer = TensorStream::Train::AdamOptimizer.new(0.05)

200.times do
  tf.with_tape do |tape|
    loss = tf.reduce_mean(tf.square(tf.matmul(x, w) + b - target))
    grads = tape.gradients(loss, [w, b], loss.value)
    optimizer.apply_tape_gradients(grads.zip([w, b]))
  end
end

A small layers API plus fit_eager wraps the whole training loop (variables are created on first use and reused across steps by name):

loss_fn = lambda do
  h = tf.layers.dense(x, 16, name: "h", activation: :relu)
  out = tf.layers.dense(h, 4, name: "out")
  tf.reduce_mean(tf.square(out - target))
end

losses = tf.fit_eager(tf.train.adam_optimizer(0.05), steps: 200, &loss_fn)

Despite per-op eager overhead, the tape based eager pipeline is faster than deferred symbolic gradients for training: 20 Adam steps of a 100x50 -> 32 -> 10 dense net take ~324ms eager (fit_eager) versus ~445ms deferred (bench/eager_bench.rb).

Notes:

  • Placeholders are not allowed in eager mode; feed data by creating new constants each step (or stay in deferred mode for placeholder based graphs).
  • Eager ops still build graph nodes, so eager models can still be serialized with the graph serializers.
  • The tape currently supports the core math ops, relu/max, matmul, sum/mean reductions, softmax/log_softmax and softmax cross-entropy; unsupported ops raise instead of returning wrong gradients.

Tape based gradients in deferred mode

tf.tape_gradients(loss, wrt, feed_dict: ...) records the evaluated operations during a normal session run and backpropagates through them, instead of symbolically deriving a gradient program and re-evaluating the forward pass. For supported ops this runs about 2x faster than tf.gradients (see bench/tape_bench.rb):

loss_value, grads = TensorStream.tape_gradients(loss, [w, b], feed_dict: { x_data => xs, y_data => ys })

Python to Ruby guide

Not all ops are available. Available ops are defined in lib/tensor_stream/ops.rb, corresponding gradients are found at lib/tensor_stream/math_gradients.

There are also certain differences with regards to naming conventions, and named parameters:

Variables and Constants

To make referencing python examples easier it is recommended to use "tf" as the TensorStream namespace

At the beginning

tf = TensorStream # recommended to use tf since most sample models on the net use this
ts = TensorStream # use this if you plan to use TensorStream only features, so other devs will know about that

Note the difference in named and optional parameters

Python

w = ts.Variable(0, name='weights')
w = ts.Variable(0, 'weights')

Ruby

w = ts.variable(0, name: 'weights')
c = ts.constant(1.0)

# concise way when initializing using a constant
w = 0.t.var name: 'weights'
c = 1.0.t

Calling .t to Integer, Array and Float types converts it into a tensor

Shapes

Python

x = tf.placeholder(tf.float32, shape=(1024, 1024))
x = tf.placeholder(tf.float32, shape=(None, 1024))

ruby supports symbols for specifying data types, nil can be used for None

Ruby

x = ts.placeholder(:float32, shape: [1024, 1024])
x = ts.placeholder(:float32, shape: [nil, 1024])

# Another a bit more terse way
x = Float.placeholder shape: [1024, 1024]
y = Float.placeholder shape: [nil, 1024]

For debugging, each operation or tensor supports the to_math method

X = ts.placeholder("float")
Y = ts.placeholder("float")
W = ts.variable(rand, name: "weight")
b = ts.variable(rand, name: "bias")
pred = X * W + b
cost = ts.reduce_sum(ts.pow(pred - Y, 2)) / ( 2 * 10)
cost.to_math # "(reduce_sum(|((((Placeholder: * weight) + bias) - Placeholder_2:)^2)|) / 20.0)"

breakpoints can also be set, block will be evaluated during computation

a = ts.constant([2,2])
b = ts.constant([3,3])

f = ts.matmul(a, b).breakpoint! { |tensor, a, b, result_value| binding.pry }

ts.session.run(f)

OpenCL

For OpenCL support, make sure that the required OpenCL drivers for your hardware are correctly installed on your system. Also OpenCL only supports ruby-mri at the moment.

To use, include the following gem in your project:

gem 'tensor_stream-opencl'

To use the opencl evaluator instead of the ruby evaluator simply require it (if using rails this should be loaded automatically).

require 'tensor_stream/opencl'

Adding the OpenCL evaluator should expose additional devices available to tensor_stream

ts.list_local_devices
# ["job:localhost/ts:ruby:cpu", "job:localhost/ts:opencl:apple:0", "job:localhost/ts:opencl:apple:1"]

Here we see 1 "ruby" cpu device and 2 opencl "apple" devices (Intel CPU, Intel Iris GPU)

By default TensorStream will determine using the given evaluators the best possible placement for each tensor operation

require 'tensor_stream/opencl'

# set session to use the opencl evaluator
sess = ts.session

sess.run(....) # do stuff

You can manually place operations using ts.device e.g:

ts = TensorStream
# Creates a graph. place in the first OpenCL CPU device

a, b = ts.device('/cpu:0') do
  a = ts.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape: [2, 3], name: 'a')
  b = ts.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape: [3, 2], name: 'b')
  [a, b]
end

c = ts.device('/device:GPU:0') do
  ts.matmul(a, b)
end

# Creates a session with log_device_placement set to True.
sess = ts.session(log_device_placement: true)
# Runs the op.
print(sess.run(c))

# a : apple:0
# b : apple:0
# a_1 : apple:0
# b_1 : apple:0
# matmul:0 : apple:1
# [[22.0, 28.0], [49.0, 64.0]] => nil

To force the ruby evaluator even with the OpenCL evaluator loaded you can use:

ts.device('/ts:ruby:cpu') do
    # put ops here
end

Note that the OpenCL evaluator provides speedup if you are using large tensors, tensors that are only using scalars like the linear regression sample will actually be slower.

samples/nearest_neighbor.rb contains a sample that uses opencl.

OpenCL support is maintained as a separate project at:

https://github.com/jedld/tensor_stream-opencl

Export Import Models from tensorflow

Experimental support for parsing and exporting pbtext files are supported:

Exporting

a = ts.constant([1.0, 1.0])
b = ts.constant([1.5, 1.5])
f = a + b

File.write('my_model.pbtext', f.graph.as_graph_def)

Importing (Experimental)

Note that not all tensorflow ops are supported, warnings will be showed if a certain operation is not supported yet.

  pbtext = File.read(File.join('linear_regression.pbtxt'))

  # create a graph from pbtext file
  graph = TensorStream::Graph.parse_from_string(pbtext)

  # reference a tensor by name from the created graph,
  # for example you have a tensor named out
  tensor = graph.get_tensor_by_name("out")

  # set graph as default and do operations on it
  graph.as_default do
    sess = ts.session
    expect(tr(sess.run(tensor))).to eq([[1.0, 1.0], [1.0, 1.0]])
  end

Visualization

tensorstream does not support tensorboard yet, but a graphml generator is included:

tf = TensorStream
a = tf.constant(1.0)
b = tf.constant(2.0)
result = a + b
sess = tf.session
sess.run(result)

File.write('gradients.graphml', TensorStream::Graphml.new.get_string(result)) # dump graph only
File.write('gradients.graphml', TensorStream::Graphml.new.get_string(result, sess)) # dump with values from session

the resulting graphml is designed to work with yED, after loading the graph change layout to "Flowchart" for best results

Exporting to TensorFlow

Still in alpha but tensorstream supports TensorFlows as_graph_def serialization method:

tf = TensorStream
a = tf.constant(1.0)
b = tf.constant(2.0)
result = a + b
File.write("model.pbtext", result.graph.as_graph_def)

Performance notes

On MRI, TensorStream automatically uses Numo::NArray flat typed buffers for elementwise math and matmul when the numo-narray gem is installed (see Installation). Representative numbers from the bundled benchmarks (ruby 3.x, linux x86_64):

bench/math_bench.rb   50-op math chain on 250x250 tensors   0.985s  -> 0.065s
bench/math_bench.rb   exp on 500x500                        66ms    -> 19ms
bench/nn_bench.rb     reduce_sum 1000x100                   68ms    -> 11ms
bench/nn_bench.rb     softmax/log_softmax 1000x100          47ms    -> 14ms
bench/nn_bench.rb     cross entropy + gradients 1000x100    240ms   -> 60ms
bench/nn_bench.rb     bias_add 1000x100                     37ms    -> 13ms
bench/tape_bench.rb   dense layer forward+grad 100x50->10   33ms    -> 15ms
bench/tape_bench.rb   dense layer forward+grad 200x200->200 323ms   -> 170ms
bench/eager_bench.rb  adam 20 steps dense net, eager tape   317ms (vs 464ms deferred symbolic)

Comparative performance with respect to other ruby libraries have not yet been performed. However it is notable that TruffleRuby and ruby-2.6.0 performs considerably better with respect to previous versions of ruby(< 2.6)

Benchmarks running samples/linear_regression.rb with tensor_stream 1.0.0 on an AMD(R) Ryzen(TM) 3 1300X CPU

ruby 2.5

$ ruby -v
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux]
$ ruby samples/linear_regression.rb
296 seconds 3000 epochs

ruby 2.6.0

$ ruby -v
ruby 2.6.0p0 (2018-12-25 revision 66547) [x86_64-linux]
$ ruby samples/linear_regression.rb
232 seconds 10000 epochs

ruby --jit samples/linear_regression.rb
222 seconds 10000 epochs

truffleruby

$ ruby -v
truffleruby 1.0.0-rc10, like ruby 2.4.4, GraalVM CE Native [x86_64-linux]
246 seconds 10000 epochs

jruby

$ ruby -v
jruby 9.2.0.0 (2.5.0) 2018-05-24 81156a8 OpenJDK 64-Bit Server VM 25.191-b12 on 1.8.0_191-8u191-b12-0ubuntu0.18.04.1-b12 +jit [linux-x86_64]
205 seconds 10000 epochs

For training large networks that works on images, the opencl evaluator is the only way to go.

Roadmap

  • Expand the layers API (conv/pool layers, more activations, model persistence helpers)
  • Extend tape gradient kernels to the remaining ops (convolutions, pooling, sequence ops)
  • Complete low-level op support
  • SciRuby evaluator
  • TensorFlow savemodel compatibility
  • Docs

Shipped recently: Numo::NArray fast kernels, tape based reverse-mode autodiff, eager execution, and a layers + fit_eager training API.

Issues

  • This is an early preview release and many things still don't work
  • Pure ruby performance has been substantially improved with the optional numo-narray kernels, but the OpenCL evaluator is still the way to go for convnets and very large tensors
  • However if you really need an op supported please feel free to file a pull request with the corresponding failing test (see spec/operation_spec.rb)

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/tensor_stream. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Nearby in the ranking
Similar items

AI Rank for iPhone

Follow AI model rankings

Download on the App Store