tensor_stream-opencl 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: d2a9a1d1add56659374f7246f35cd956eba86c9416a1e012abc44fe9bdb857ab
4
- data.tar.gz: 6acf877d4b85f93facc750d9541221b0e2a8775d608e7160654c2421411d7a3b
3
+ metadata.gz: 1c00d22564cef50ae50f6302975c6bd35d1e594d70f3645f2c2fa5f7bf31ad8c
4
+ data.tar.gz: 31bb29c838d9ee652d52b9053781110b13e4b80937d777e368df54349c1ea2a9
5
5
  SHA512:
6
- metadata.gz: 7c9d3d3391d2bc228f5daed33a83fe750ca61bde20b71ce07fe2a73df32661fb910d1bcac5cbcb6a025e04808ac90174a0040dd13f23bc40b134a3196cef50ee
7
- data.tar.gz: 6aabe002d353b02647810c8aea9e521ad1bb4029ccfd2c7cfd78f8609f6826c4260ef5f3ff02170d3a2f55f588f68aad8a1613efac8b586f0751c72e492287f0
6
+ metadata.gz: 4aca3b8e774e9ff7b8b50fb25511616069bb5357d8b0c9dab1af2b8681a5aabd6b580e57912750c2fa6326a29dd9b4ef10ade9685d897e1c004f54a5022c0bcd
7
+ data.tar.gz: d5f689330ef270475a5ea907cded4d1c9c1abdc160e1f565974a9e4b5dfd39bf0b3d5c42444252f0c1efc73d3a6001c8b8be0282aa065412feeb20082d4404eb
@@ -0,0 +1,35 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [master]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: ubuntu-latest
11
+ strategy:
12
+ fail-fast: false
13
+ matrix:
14
+ ruby: ["3.1", "3.3", "3.4"]
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - name: Clone core next to this repo (shared spec support + path gem)
18
+ run: git clone --depth 1 https://github.com/jedld/tensor_stream.git ../tensor_stream
19
+ - name: Install system dependencies (POCL OpenCL ICD + jpeg gem headers)
20
+ run: sudo apt-get update -q && sudo apt-get install -yq --no-install-recommends pocl-opencl-icd ocl-icd-libopencl1 libjpeg-dev
21
+ - name: Verify OpenCL device is visible
22
+ run: ls /etc/OpenCL/vendors && cat /etc/OpenCL/vendors/*.icd && ldconfig -p | grep -i libopencl
23
+ - name: Set up Ruby ${{ matrix.ruby }}
24
+ uses: ruby/setup-ruby@v1
25
+ with:
26
+ ruby-version: ${{ matrix.ruby }}
27
+ - name: Install gems
28
+ run: |
29
+ # numo-narray and narray need a legacy C dialect on GCC 14+
30
+ # runners (C23 removed K&R-style empty parameter lists)
31
+ bundle config set --local build.numo-narray "--with-cflags=-std=gnu17"
32
+ bundle config set --local build.narray "--with-cflags=-std=gnu17"
33
+ bundle install --jobs 4 --retry 3
34
+ - name: Run specs (OpenCL evaluator on POCL CPU device)
35
+ run: bundle exec rspec
data/CHANGELOG.md ADDED
@@ -0,0 +1,38 @@
1
+ # Changelog
2
+
3
+ ## [0.4.0] - 2026-12-06
4
+
5
+ ### Fixed
6
+ - Kernel template compilation on Ruby 3+: the removed positional
7
+ `ERB.new(src, nil, '%')` form now uses `trim_mode:`; previously every
8
+ kernel compile raised.
9
+ - Heap corruption in the softmax family (`softmax`, `log_softmax`,
10
+ `softmax_cross_entropy_with_logits(_v2)`, `sparse_*`, `*_grad`):
11
+ rank-1 logits were misread as `shape[0]` rows of that same width, so
12
+ kernels wrote `n^2` elements into `n`-element buffers.
13
+ - `unstack`/`split`: sub-buffer regions that violate
14
+ `CL_DEVICE_MEM_BASE_ADDR_ALIGN` (e.g. small slices) now fall back to
15
+ discrete device buffers with a rect copy instead of failing with
16
+ `CL_MISALIGNED_SUB_BUFFER_OFFSET` on strict ICDs (POCL).
17
+ - Inputs arriving from the ruby evaluator's numo-narray fast path are
18
+ converted to ruby arrays before being packed into GPU buffers.
19
+ - Implemented the evaluator storage-manager hook required by core
20
+ (`get_storage_manager`).
21
+ - Latent NameError in the sub-buffer fallback branches.
22
+
23
+ ### Changed
24
+ - Requires `tensor_stream >= 1.3`.
25
+ - The GPU-resident "variable container" model was removed:
26
+ `variable_v2`, `assign*`, `apply_*` optimizers and `save_ts/restore_ts`
27
+ now execute on the ruby evaluator, matching core's host-side variable
28
+ storage (values transition to GPU buffers per op). Device-resident
29
+ variable storage with on-device apply kernels is future work.
30
+ - `narray_ffi` is now an explicit dependency.
31
+ - CI runs the full shared-op suite against the POCL software OpenCL
32
+ ICD (Ruby 3.1/3.3/3.4), so no GPU drivers are needed to develop the
33
+ backend; GPU-device-specific specs self-skip when no GPU is present.
34
+ - Added `bin/opencl_check.rb` smoke tool; README documents the
35
+ compatibility and development setup.
36
+
37
+ ## [0.3.2] and earlier
38
+ - See git history.
data/Gemfile CHANGED
@@ -4,3 +4,19 @@ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
4
 
5
5
  # Specify your gem's dependencies in tensor_stream-opencl.gemspec
6
6
  gemspec
7
+
8
+ gem "benchmark"
9
+ gem "drb"
10
+ gem "mutex_m"
11
+ gem "bigdecimal"
12
+
13
+ # develop against the local core checkout when present (monorepo style
14
+ # sibling checkout); CI tracks core master until 1.3+ is pushed to
15
+ # rubygems, after which the released gem dependency also resolves
16
+ if Dir.exist?(File.expand_path("../tensor_stream", __dir__))
17
+ gem "tensor_stream", path: "../tensor_stream"
18
+ else
19
+ gem "tensor_stream", github: "jedld/tensor_stream"
20
+ end
21
+
22
+ gem "numo-narray"
data/README.md CHANGED
@@ -81,10 +81,38 @@ ts.device('/device:GPU:1') do
81
81
  end
82
82
  ```
83
83
 
84
+ ## Compatibility and architecture notes
85
+
86
+ - Requires tensor_stream >= 1.3 (works with the numo-narray fast path: values
87
+ coming from the ruby evaluator are converted to OpenCL buffers at
88
+ evaluator transitions).
89
+ - Tested on Ruby 3.1–3.4. CI runs the full shared op suite against a POCL
90
+ (software) OpenCL device, so no GPU is needed to develop or verify the
91
+ backend. Ruby 4.x is not supported yet: the opencl_ruby_ffi/narray_ffi
92
+ native extensions corrupt memory there (crashes surface mid-suite).
93
+ - Variable storage is host side (the ruby evaluator owns `variable_v2` /
94
+ `assign` / `apply_*` optimizer ops); values cross to GPU buffers per op.
95
+ GPU-resident variable storage with on-device apply kernels is planned.
96
+ - Eager execution (`tf.enable_eager_execution`) always evaluates on the
97
+ ruby evaluator; the OpenCL evaluator is for session/graph execution.
98
+
84
99
  ## Development
85
100
 
86
101
  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.
87
102
 
103
+ The specs need an OpenCL device. Without GPU drivers, install the POCL
104
+ software ICD (`sudo apt-get install pocl-opencl-icd` on Debian/Ubuntu);
105
+ CI uses exactly this. If your system loader doesn't pick it up
106
+ automatically, point `opencl_ruby_ffi` at it:
107
+
108
+ ```sh
109
+ export OCL_ICD_VENDORS=/path/to/vendors.d # directory containing pocl.icd
110
+ export LD_LIBRARY_PATH=/path/to/lib # contains libpocl.so
111
+ ```
112
+
113
+ Run `bundle exec ruby bin/opencl_check.rb` for a quick device + evaluator
114
+ smoke test before running the full suite.
115
+
88
116
  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](https://rubygems.org).
89
117
 
90
118
  ## Contributing
@@ -0,0 +1,32 @@
1
+ $LOAD_PATH.unshift File.expand_path("../../tensor_stream/lib", __dir__)
2
+ $LOAD_PATH.unshift File.expand_path("../lib", __dir__)
3
+ require "tensor_stream"
4
+ require "tensor_stream/opencl"
5
+
6
+ tf = TensorStream
7
+ puts "evaluators: #{TensorStream::Evaluator.default_evaluators.collect { |k| k.name }.join(', ')}"
8
+ begin
9
+ devices = TensorStream::Evaluator::OpenclEvaluator.query_supported_devices
10
+ puts "opencl devices: #{devices.collect { |d| "#{d.evaluator}:#{d.name}" }.inspect}"
11
+ rescue => e
12
+ puts "device query error: #{e.class}: #{e.message[0, 120]}"
13
+ end
14
+
15
+ x = tf.constant([[1.0, 2.0], [3.0, 4.0]])
16
+ y = tf.constant([[10.0, 20.0], [30.0, 40.0]])
17
+ ops = [
18
+ ["add", x + y],
19
+ ["mul", x * y],
20
+ ["matmul", tf.matmul(x, y)],
21
+ ["sigmoid", tf.sigmoid(x)],
22
+ ["reduce_sum", tf.reduce_sum(x, 1)],
23
+ ["square", tf.square(x)],
24
+ ]
25
+ sess = tf.session(log_device_placement: false)
26
+ ops.each do |name, t|
27
+ begin
28
+ p [name, sess.run(t)]
29
+ rescue => e
30
+ puts "#{name}: ERROR #{e.class}: #{e.message[0, 160]}"
31
+ end
32
+ end
@@ -472,6 +472,30 @@ module TensorStream
472
472
  convert_to_opencl(r, [r.size], data_type: tensor.options[:output_type], name: tensor.name)
473
473
  end
474
474
  end
475
+
476
+ register_op :gather do |context, tensor, inputs|
477
+ params, indexes = inputs
478
+ raise TensorStream::ValueError, "axis !=0 not supported" if tensor.options[:axis] != 0
479
+
480
+ new_shape = [indexes.buffer.size]
481
+ target_shape = params.shape.dup
482
+ target_shape.shift
483
+ new_shape += target_shape
484
+
485
+ target_shape_size = target_shape.empty? ? 1 : target_shape.reduce(:*)
486
+
487
+ output_buffer = _create_result_buffer(tensor.data_type, new_shape, tensor.name)
488
+ event_wait_list = build_event_wait_list(inputs)
489
+
490
+ output_buffer.op = indexes.buffer.to_a.map.with_index do |target_index, index|
491
+ source_ptr = target_index * target_shape_size * params.buffer.element_size
492
+ dest_ptr = index * target_shape_size * params.buffer.element_size
493
+ region = [target_shape_size * params.buffer.element_size, 1, 1]
494
+ raise TensorStream::ValueError, "Index out of bounds #{target_index} >= #{params.shape.reduce(:*)}" if target_index >= params.shape.first
495
+ _opencl_queue.enqueue_copy_buffer_rect(params.cl_buffer, output_buffer.cl_buffer, region, src_origin: [source_ptr, 0, 0], dst_origin: [dest_ptr, 0, 0], event_wait_list: event_wait_list) rescue binding.pry
496
+ end
497
+ output_buffer
498
+ end
475
499
  end
476
500
  end
477
501
  end
@@ -11,7 +11,7 @@ module TensorStream
11
11
  resample_method = tensor.options[:resample_method] || :bilinear
12
12
  channels = 4 if channels.zero?
13
13
 
14
- image = ChunkyPNG::Image.from_blob(content.buffer.to_a.pack('C*'))
14
+ image = ChunkyPNG::Image.from_blob(content.sync!.buffer.to_a.pack('C*'))
15
15
 
16
16
  if resample_new_shape
17
17
  case resample_method
@@ -27,24 +27,65 @@ module TensorStream
27
27
  output_buffer = _create_result_buffer(tensor.data_type, [image.height, image.width, channels], "out_#{tensor.name}", allocate_host: true)
28
28
 
29
29
  image.grayscale! if channels == 1
30
- image.pixels.each_with_index do |pixel, index|
30
+ image_data = image.pixels.each_with_index.map do |pixel, index|
31
31
  start_index = index * channels
32
32
  if channels == 4
33
- output_buffer.buffer[start_index] = ChunkyPNG::Color.r(pixel)
34
- output_buffer.buffer[start_index + 1] = ChunkyPNG::Color.g(pixel)
35
- output_buffer.buffer[start_index + 2] = ChunkyPNG::Color.b(pixel)
36
- output_buffer.buffer[start_index + 3] = ChunkyPNG::Color.a(pixel)
33
+ [
34
+ ChunkyPNG::Color.r(pixel),
35
+ ChunkyPNG::Color.g(pixel),
36
+ ChunkyPNG::Color.b(pixel),
37
+ ChunkyPNG::Color.a(pixel)
38
+ ]
37
39
  elsif channels == 3
38
- output_buffer.buffer[start_index] = ChunkyPNG::Color.r(pixel)
39
- output_buffer.buffer[start_index + 1] = ChunkyPNG::Color.g(pixel)
40
- output_buffer.buffer[start_index + 2] = ChunkyPNG::Color.b(pixel)
40
+ [
41
+ ChunkyPNG::Color.r(pixel),
42
+ ChunkyPNG::Color.g(pixel),
43
+ ChunkyPNG::Color.b(pixel)
44
+ ]
41
45
  elsif channels == 1
42
- output_buffer.buffer[start_index] = ChunkyPNG::Color.r(pixel)
46
+ ChunkyPNG::Color.r(pixel)
43
47
  else
44
48
  raise "Invalid channel value #{channels}"
45
49
  end
46
- end
50
+ end.flatten
51
+
52
+ output_buffer.buffer = NArray.to_na(image_data)
53
+ write_op = _opencl_queue.enqueue_write_buffer(output_buffer.cl_buffer, output_buffer.buffer)
54
+ output_buffer.op = write_op
55
+ output_buffer
56
+ end
57
+
58
+ register_op :decode_jpg do |context, tensor, inputs|
59
+ require 'jpeg'
60
+
61
+ content = _run(inputs[0], context)
62
+ channels = tensor.options[:channels]
63
+ resample_new_shape = tensor.options[:new_shape]
64
+ resample_method = tensor.options[:resample_method] || :bilinear
65
+ channels = 3 if channels.zero?
66
+ jpeg_buffer = content.sync!.buffer.to_a.pack('C*')
67
+
68
+ image = Jpeg::Image.open_buffer(jpeg_buffer)
69
+
70
+ source_channels = image.color_info == :gray ? 1 : 3
71
+ output_buffer = _create_result_buffer(tensor.data_type, [image.height, image.width, channels], "out_#{tensor.name}", allocate_host: false)
72
+
73
+
74
+ image_data = image.raw_data.map do |pixel|
75
+ if source_channels == channels
76
+ pixel
77
+ elsif source_channels = 1 && channels == 3
78
+ [pixel, pixel, pixel]
79
+ elsif source_channels = 3 && channels == 1
80
+ raise TensorStream::ValueError, "color to grayscale not supported for jpg"
81
+ end
82
+ end.flatten
83
+
84
+ raise TensorStream::ValueError, "float output not supported for jpg decode" if fp_type?(tensor.data_type)
85
+
86
+ output_buffer.buffer = NArray.to_na(image_data)
47
87
 
88
+ raise TensorStream::ValueError, "image size mismatch #{output_buffer.shape.reduce(:*)} != #{output_buffer.buffer.size}" if output_buffer.buffer.size != output_buffer.shape.reduce(:*)
48
89
  write_op = _opencl_queue.enqueue_write_buffer(output_buffer.cl_buffer, output_buffer.buffer)
49
90
  output_buffer.op = write_op
50
91
  output_buffer
@@ -5,213 +5,11 @@ module TensorStream
5
5
  def NNOps.included(klass)
6
6
  klass.class_eval do
7
7
 
8
- # Fast in place multiply subtract assign
9
- register_op :apply_gradient_descent do |_context, tensor, inputs|
10
- _target_var, learning_rate, delta = inputs
11
-
12
- assign = tensor.inputs[0] || tensor
13
-
14
- assign.container_buffer.dirty = true # force buffer copy when variable is read externally
15
- output_buffer = assign.container_buffer
16
-
17
- work_group = [output_buffer.total_elements]
18
-
19
- event_wait_list = build_event_wait_list([assign.container_buffer, learning_rate, delta])
20
-
21
- event = call_program("apply_gradient", output_buffer.data_type,
22
- work_group,
23
- delta.cl_buffer,
24
- learning_rate.cl_buffer,
25
- output_buffer.cl_buffer, event_wait_list: event_wait_list)
26
- output_buffer.op = event
27
- output_buffer
28
- end
29
-
30
- # updates for gradient descent with momentum
31
- register_op :apply_momentum do |_context, tensor, inputs|
32
- target_var, momentum_var, learning_rate, grad, momentum = inputs
33
-
34
- assign = tensor.inputs[0] || tensor
35
- assign_acc = tensor.inputs[1]
36
- assign.container_buffer.dirty = true # force buffer copy when variable is read externally
37
- assign_acc.container_buffer.dirty = true # force buffer copy when variable is read externally
38
-
39
- output_buffer = assign.container_buffer
40
-
41
- work_group = [output_buffer.total_elements]
42
-
43
- event_wait_list = build_event_wait_list([assign.container_buffer, assign_acc.container_buffer, learning_rate, grad, momentum])
44
- method_call = :"apply_momentum_#{output_buffer.data_type}"
45
- event = _cl_program("apply_momentum", nesterov: tensor.options[:use_nesterov], dtype: output_buffer.data_type).
46
- send(method_call, _opencl_queue, work_group, grad.cl_buffer,
47
- learning_rate.cl_buffer, momentum.cl_buffer, output_buffer.cl_buffer,
48
- assign_acc.container_buffer.cl_buffer, event_wait_list: event_wait_list)
49
- output_buffer.op = event
50
- assign_acc.container_buffer.op = event
51
- output_buffer
52
- end
53
-
54
- register_op :apply_adadelta do |context, tensor, inputs|
55
- _target_var, _accum, _accum_update, lr, rho, epsilon, grad = inputs
56
- assign = tensor.inputs[0] || tensor
57
- assign_acc = tensor.inputs[1]
58
- assign_acc_update = tensor.inputs[2]
59
-
60
- # mark variable buffers as dirty
61
- assign.container_buffer.dirty = true # force buffer copy when variable is read externally
62
- assign_acc.container_buffer.dirty = true # force buffer copy when variable is read externally
63
- assign_acc_update.container_buffer.dirty = true # force buffer copy when variable is read externally
64
-
65
- output_buffer = assign.container_buffer
66
-
67
- work_group = [output_buffer.total_elements]
68
-
69
- event_wait_list = build_event_wait_list(inputs)
70
- event = call_program('apply_adadelta', output_buffer.data_type,
71
- work_group,
72
- lr.cl_buffer,
73
- rho.cl_buffer,
74
- epsilon.cl_buffer,
75
- grad.cl_buffer,
76
- assign.container_buffer.cl_buffer,
77
- assign_acc.container_buffer.cl_buffer,
78
- assign_acc_update.container_buffer.cl_buffer,
79
- event_wait_list: event_wait_list)
80
- output_buffer.op = event
81
- assign_acc.container_buffer.op = event
82
- assign_acc_update.container_buffer.op = event
83
- output_buffer
84
- end
85
-
86
- # Adam optimization algorithm
87
- register_op :apply_adam do |_context, tensor, inputs|
88
- _target_var, _m, _v, beta1_power, beta2_power, lr_t, beta1_t, beta2_t, epsilon_t, grad = inputs
89
-
90
- assign = tensor.inputs[0] || tensor
91
- assign_m = tensor.inputs[1]
92
- assign_v = tensor.inputs[2]
93
-
94
- # mark variable buffers as dirty
95
- assign.container_buffer.dirty = true # force buffer copy when variable is read externally
96
- assign_m.container_buffer.dirty = true # force buffer copy when variable is read externally
97
- assign_v.container_buffer.dirty = true # force buffer copy when variable is read externally
98
-
99
- output_buffer = assign.container_buffer
100
-
101
- work_group = [output_buffer.total_elements]
102
-
103
- event_wait_list = build_event_wait_list(inputs)
104
- event = call_program("apply_adam", output_buffer.data_type,
105
- work_group,
106
- grad.cl_buffer,
107
- lr_t.cl_buffer,
108
- beta1_power.cl_buffer,
109
- beta2_power.cl_buffer,
110
- beta1_t.cl_buffer,
111
- beta2_t.cl_buffer,
112
- epsilon_t.cl_buffer,
113
- assign_m.container_buffer.cl_buffer,
114
- assign.container_buffer.cl_buffer,
115
- assign_v.container_buffer.cl_buffer,
116
- event_wait_list: event_wait_list)
117
- output_buffer.op = event
118
- assign_m.container_buffer.op = event
119
- assign_v.container_buffer.op = event
120
- output_buffer
121
- end
122
-
123
- register_op :apply_adagrad do |context, tensor, inputs|
124
- _target_var, _accum, lr, grad = inputs
125
-
126
- assign = tensor.inputs[0] || tensor
127
- assign_acc = tensor.inputs[1]
128
-
129
- assign.container_buffer.dirty = true
130
- assign_acc.container_buffer.dirty = true
131
- output_buffer = assign.container_buffer
132
-
133
- work_group = [output_buffer.total_elements]
134
-
135
- event_wait_list = build_event_wait_list(inputs)
136
- event = call_program('apply_adagrad',
137
- output_buffer.data_type,
138
- work_group,
139
- lr.cl_buffer,
140
- grad.cl_buffer,
141
- assign.container_buffer.cl_buffer,
142
- assign_acc.container_buffer.cl_buffer,
143
- event_wait_list: event_wait_list)
144
- output_buffer.op = event
145
- assign_acc.container_buffer.op = event
146
- output_buffer
147
- end
148
-
149
- register_op :apply_centered_rms_prop do |context, tensor, inputs|
150
- var, mg, ms, mom, lr, rho, momentum, epsilon, grad = inputs
151
-
152
- assign = tensor.inputs[0]
153
- assign_mg = tensor.inputs[1]
154
- assign_ms = tensor.inputs[2]
155
- assign_mom = tensor.inputs[3]
156
-
157
- assign.container_buffer.dirty = true
158
- assign_mg.container_buffer.dirty = true
159
- assign_ms.container_buffer.dirty = true
160
- assign_mom.container_buffer.dirty = true
161
- output_buffer = assign.container_buffer
162
- event_wait_list = build_event_wait_list(inputs)
163
- work_group = [output_buffer.total_elements]
164
-
165
- event = call_program('apply_centered_rms_prop', output_buffer.data_type, work_group,
166
- lr.cl_buffer,
167
- rho.cl_buffer,
168
- momentum.cl_buffer,
169
- epsilon.cl_buffer,
170
- grad.cl_buffer,
171
- assign.container_buffer.cl_buffer,
172
- assign_ms.container_buffer.cl_buffer,
173
- assign_mg.container_buffer.cl_buffer,
174
- assign_mom.container_buffer.cl_buffer,
175
- event_wait_list: event_wait_list)
176
-
177
- output_buffer.op = event
178
- assign_mg.container_buffer.op = event
179
- assign_ms.container_buffer.op = event
180
- assign_mom.container_buffer.op = event
181
- output_buffer
182
- end
183
-
184
- register_op :apply_rms_prop do |_context, tensor, inputs|
185
- var, ms, mom, lr, rho, momentum, epsilon, grad = inputs
186
-
187
- assign = tensor.inputs[0]
188
- assign_ms = tensor.inputs[1]
189
- assign_mom = tensor.inputs[2]
190
-
191
- assign.container_buffer.dirty = true
192
- assign_ms.container_buffer.dirty = true
193
- assign_mom.container_buffer.dirty = true
194
- output_buffer = assign.container_buffer
195
- event_wait_list = build_event_wait_list(inputs)
196
- work_group = [output_buffer.total_elements]
197
-
198
- event = call_program('apply_rms_prop', output_buffer.data_type,
199
- work_group,
200
- lr.cl_buffer,
201
- rho.cl_buffer,
202
- momentum.cl_buffer,
203
- epsilon.cl_buffer,
204
- grad.cl_buffer,
205
- assign.container_buffer.cl_buffer,
206
- assign_ms.container_buffer.cl_buffer,
207
- assign_mom.container_buffer.cl_buffer,
208
- event_wait_list: event_wait_list)
209
-
210
- output_buffer.op = event
211
- assign_ms.container_buffer.op = event
212
- assign_mom.container_buffer.op = event
213
- output_buffer
214
- end
8
+ # NOTE: apply_* optimizer ops are intentionally NOT registered:
9
+ # they assumed GPU-resident variable containers, a model the
10
+ # core no longer provides. Training updates run on the ruby
11
+ # evaluator; GPU-resident apply kernels are a future
12
+ # optimization once variable storage can live on device.
215
13
 
216
14
  register_op :softmax do |_context, tensor, inputs|
217
15
  a = inputs[0]
@@ -219,12 +17,15 @@ module TensorStream
219
17
  dtype = tensor.data_type
220
18
  output_buffer = _create_result_buffer(tensor.data_type, a.shape, tensor.name)
221
19
 
222
- m, n = a.shape
20
+ # rank-1 inputs are a single row of a.shape[0] columns.
21
+ # A plain m, n = a.shape misreads them as a.shape[0] rows
22
+ # of that width, so the kernel writes rows^2 elements and
23
+ # overflows the output buffers (heap corruption).
24
+ m, n = a.shape.size == 1 ? [1, a.shape[0]] : a.shape
223
25
 
224
26
  raise "unsupported rank " if a.shape.size > 2
225
27
 
226
28
  work_group = [m]
227
- n = m if n.nil?
228
29
  cl_n = OpenCL::Int1.new(n || 1)
229
30
 
230
31
  event = _cl_program("softmax", dtype: dtype).send(:"softmax_#{dtype}", _opencl_queue, work_group, cl_n, a.cl_buffer, output_buffer.cl_buffer, event_wait_list: event_wait_list)
@@ -238,12 +39,15 @@ module TensorStream
238
39
  dtype = tensor.data_type
239
40
  output_buffer = _create_result_buffer(tensor.data_type, a.shape, tensor.name)
240
41
 
241
- m, n = a.shape
42
+ # rank-1 inputs are a single row of a.shape[0] columns.
43
+ # A plain m, n = a.shape misreads them as a.shape[0] rows
44
+ # of that width, so the kernel writes rows^2 elements and
45
+ # overflows the output buffers (heap corruption).
46
+ m, n = a.shape.size == 1 ? [1, a.shape[0]] : a.shape
242
47
 
243
48
  raise "unsupported rank " if a.shape.size > 2
244
49
 
245
50
  work_group = [m]
246
- n = m if n.nil?
247
51
  cl_n = OpenCL::Int1.new(n || 1)
248
52
 
249
53
  event = _cl_program("log_softmax", dtype: dtype).send(:"log_softmax_#{dtype}", _opencl_queue, work_group, cl_n, a.cl_buffer, output_buffer.cl_buffer, event_wait_list: event_wait_list)
@@ -259,12 +63,15 @@ module TensorStream
259
63
  output_buffer = _create_result_buffer(tensor.data_type, a.shape, tensor.name)
260
64
  output_buffer_backprop = _create_result_buffer(tensor.data_type, a.shape, "#{tensor.name}_2")
261
65
  rank = a.shape.size - 1
262
- m, n = a.shape
66
+ # rank-1 inputs are a single row of a.shape[0] columns.
67
+ # A plain m, n = a.shape misreads them as a.shape[0] rows
68
+ # of that width, so the kernel writes rows^2 elements and
69
+ # overflows the output buffers (heap corruption).
70
+ m, n = a.shape.size == 1 ? [1, a.shape[0]] : a.shape
263
71
 
264
72
  raise "unsupported rank " if a.shape.size > 2
265
73
 
266
74
  work_group = [m]
267
- n = m if n.nil?
268
75
  cl_n = OpenCL::Int1.new(n || 1)
269
76
 
270
77
  event = _cl_program("softmax_cross", dtype: dtype).send(:"softmax_cross_#{dtype}", _opencl_queue, work_group, cl_n, a.cl_buffer, b.cl_buffer,
@@ -284,12 +91,15 @@ module TensorStream
284
91
  dtype = tensor.data_type
285
92
  output_buffer = _create_result_buffer(tensor.data_type, a.shape, tensor.name)
286
93
 
287
- m, n = a.shape
94
+ # rank-1 inputs are a single row of a.shape[0] columns.
95
+ # A plain m, n = a.shape misreads them as a.shape[0] rows
96
+ # of that width, so the kernel writes rows^2 elements and
97
+ # overflows the output buffers (heap corruption).
98
+ m, n = a.shape.size == 1 ? [1, a.shape[0]] : a.shape
288
99
 
289
100
  raise "unsupported rank " if a.shape.size > 2
290
101
 
291
102
  work_group = [m]
292
- n = m if n.nil?
293
103
  cl_n = OpenCL::Int1.new(n || 1)
294
104
 
295
105
  event = _cl_program("softmax_cross_grad", dtype: dtype).send(:"softmax_cross_grad_#{dtype}", _opencl_queue, work_group, cl_n, a.cl_buffer, b.cl_buffer, c.cl_buffer, output_buffer.cl_buffer, event_wait_list: event_wait_list)
@@ -316,12 +126,15 @@ module TensorStream
316
126
  output_buffer = _create_result_buffer(tensor.data_type, a.shape, tensor.name)
317
127
  output_buffer_backprop = _create_result_buffer(tensor.data_type, a.shape, "#{tensor.name}_2")
318
128
  rank = a.shape.size - 1
319
- m, n = a.shape
129
+ # rank-1 inputs are a single row of a.shape[0] columns.
130
+ # A plain m, n = a.shape misreads them as a.shape[0] rows
131
+ # of that width, so the kernel writes rows^2 elements and
132
+ # overflows the output buffers (heap corruption).
133
+ m, n = a.shape.size == 1 ? [1, a.shape[0]] : a.shape
320
134
 
321
135
  raise "unsupported rank " if a.shape.size > 2
322
136
 
323
137
  work_group = [m]
324
- n = m if n.nil?
325
138
  cl_n = OpenCL::Int1.new(n || 1)
326
139
 
327
140
  event = _cl_program("softmax_cross", dtype: dtype).send(:"softmax_cross_#{dtype}", _opencl_queue, work_group, cl_n, a.cl_buffer, b.cl_buffer,
@@ -340,10 +153,13 @@ module TensorStream
340
153
  dtype = tensor.data_type
341
154
  output_buffer = _create_result_buffer(tensor.data_type, a.shape, tensor.name)
342
155
 
343
- m, n = a.shape
156
+ # rank-1 inputs are a single row of a.shape[0] columns.
157
+ # A plain m, n = a.shape misreads them as a.shape[0] rows
158
+ # of that width, so the kernel writes rows^2 elements and
159
+ # overflows the output buffers (heap corruption).
160
+ m, n = a.shape.size == 1 ? [1, a.shape[0]] : a.shape
344
161
  raise "unsupported rank " if a.shape.size > 2
345
162
  work_group = [m]
346
- n = m if n.nil?
347
163
  cl_n = OpenCL::Int1.new(n || 1)
348
164
  event = _cl_program('softmax_grad', dtype: dtype, size: n).
349
165
  send(:"softmax_grad_#{dtype}", _opencl_queue, work_group, cl_n, a.cl_buffer,
@@ -110,6 +110,18 @@ module TensorStream
110
110
  data_type == :boolean ? process_function_op(result) { |a, _b| a != 0 } : result
111
111
  end
112
112
 
113
+ def sync!
114
+ buffer! if buffer.is_a?(LazyBuffer)
115
+
116
+ if dirty
117
+ read_event = command_queue.enqueue_read_buffer(cl_buffer, buffer, event_wait_list: [op].compact)
118
+ OpenCL.wait_for_events([read_event])
119
+ self.dirty = false
120
+ end
121
+
122
+ self
123
+ end
124
+
113
125
  def self.nil_buffer(owner, name, data_type)
114
126
  OpenCLBuffer.new(owner, name: name, data_type: data_type, shape: [0], buffer: nil, cl_buffer: nil)
115
127
  end
@@ -69,6 +69,12 @@ module TensorStream
69
69
  end
70
70
 
71
71
  class << self
72
+ # variable storage is host side (the ruby evaluator executes
73
+ # variable ops; opencl ops do not include them)
74
+ def get_storage_manager
75
+ TensorStream::RubyStorageManager.current_storage_manager
76
+ end
77
+
72
78
  def query_supported_devices
73
79
  devices = query_devices_with_score
74
80
  devices.sort_by { |a| a[1] }.map do |d|
@@ -138,14 +144,24 @@ module TensorStream
138
144
  def convert_from_buffer(tensor, result)
139
145
  if result.buffer.is_a?(TensorStream::Evaluator::OutputGroup)
140
146
  converted_outputs = result.buffer.outputs.zip(result.buffer.data_types).map do |output, data_type|
147
+ output = numo_to_ruby(output)
141
148
  convert_to_opencl([output].flatten, shape_eval(output), data_type: data_type, name: tensor.name)
142
149
  end
143
150
  TensorStream::Evaluator::OutputGroup.new(converted_outputs, result.buffer.data_types)
144
151
  else
145
- convert_to_opencl([result.buffer].flatten, shape_eval(result.buffer), data_type: result.data_type, name: tensor.name)
152
+ raw = numo_to_ruby(result.buffer)
153
+ convert_to_opencl([raw].flatten, shape_eval(raw), data_type: result.data_type, name: tensor.name)
146
154
  end
147
155
  end
148
156
 
157
+ # the ruby evaluator may hand over Numo::NArray buffers (numo fast
158
+ # path); opencl kernels pack from plain ruby arrays
159
+ def numo_to_ruby(value)
160
+ return value unless defined?(Numo::NArray) && value.is_a?(Numo::NArray)
161
+
162
+ value.to_a
163
+ end
164
+
149
165
  # Generate OpenCL instruction to read back from GPU memory to Host memory for a tensor
150
166
  def enqueue_buffer_read(tensor, context)
151
167
  buffer = _run(tensor, context)
@@ -345,8 +361,10 @@ module TensorStream
345
361
  perform_transition(tensor, tensor, @context[:_cache][:placement][tensor.name][1], execution_context)
346
362
  elsif tensor.is_a?(Operation)
347
363
  eval_operation(tensor, child_context)
364
+ elsif tensor.is_a?(Variable)
365
+ eval_operation(tensor.op, child_context)
348
366
  else
349
- raise "invalid tensor type!"
367
+ raise "invalid tensor type! #{tensor.class}"
350
368
  end
351
369
 
352
370
  execution_context.deep_merge!(returns: child_context[:returns])
@@ -377,32 +395,11 @@ module TensorStream
377
395
  end
378
396
  end
379
397
 
380
- register_op :assign, noop: true do |context, tensor, inputs|
381
- assign_var(tensor, inputs[1], context)
382
- end
383
-
384
- register_op :assign_add do |context, tensor, inputs|
385
- value = execute_2_operand_func('add', tensor, inputs[0], inputs[1])
386
- assign_var(tensor, value, context)
387
- end
388
-
389
- register_op :assign_sub do |context, tensor, inputs|
390
- value = execute_2_operand_func('sub', tensor, inputs[0], inputs[1])
391
- assign_var(tensor, value, context)
392
- end
393
-
394
- register_op %i[variable variable_v2], noop: true do |_context, tensor, _inputs|
395
- assign = tensor.inputs[0] || tensor
396
-
397
- if assign.container_buffer.nil?
398
- value = assign.container
399
- raise "Variable #{tensor.name} not initialized!" if value.nil?
400
-
401
- assign.options[:container].buffer = convert_to_opencl(value, shape_eval(value), data_type: tensor.data_type, name: assign.name)
402
- assign.options[:container].value = value
403
- end
404
- assign.container_buffer
405
- end
398
+ # NOTE: variable ops (:variable_v2, :assign, :assign_add, :assign_sub)
399
+ # are intentionally NOT registered here. Since core 1.0.10 variable
400
+ # storage is host side (RubyStorageManager) and the old container
401
+ # buffer model no longer exists; the ruby evaluator owns these ops
402
+ # and values transition to GPU buffers via convert_from_buffer.
406
403
 
407
404
  register_op :placeholder, noop: true do |context, tensor, _inputs|
408
405
  ph = @context[tensor.name.to_sym].tap do |c|
@@ -510,34 +507,19 @@ module TensorStream
510
507
  end
511
508
 
512
509
  register_op :const do |_context, tensor, inputs|
513
- wrap_opencl(tensor.const_value, name: tensor.name, data_type: tensor.data_type)
510
+ cache_key = "const_#{tensor.graph.object_id}_opencl_#{tensor.name}:#{object_id}"
511
+ @context[:_cache][cache_key] ||= wrap_opencl(tensor.const_value, name: tensor.name, data_type: tensor.data_type)
514
512
  end
515
513
 
516
514
  register_op :size do |_context, tensor, inputs|
517
515
  wrap_opencl(inputs[0].buffer.size, name: tensor.name, data_type: tensor.options[:out_type] || :int32)
518
516
  end
519
517
 
520
- register_op :restore_ts do |context, tensor, inputs|
521
- inputs = inputs.dup
522
- filename = inputs.shift
523
- tensor_names = inputs
524
-
525
- filename = read_final_result(complete_eval(filename, context))
526
- tensor_names.map! { |n| read_final_result(complete_eval(n, context)) }
527
-
528
- input_dump = YAML.safe_load(File.read(filename), [Symbol])
529
- vars = tensor.graph.get_collection(GraphKeys::GLOBAL_VARIABLES)
530
-
531
- vars.select! { |v| input_dump['variables'].key?(v.name) && tensor_names.include?(v.name) }
532
- vars.each do |variable|
533
- data = TensorStream::Packer.unpack(Zlib::Inflate.inflate(Base64.decode64(input_dump['variables'][variable.name]['data'])), variable.data_type)
534
- shape = input_dump['variables'][variable.name]['shape']
535
- variable.buffer = convert_to_opencl(data, shape, data_type: variable.data_type, name: variable.name)
536
- variable.value = TensorShape.reshape(data, shape)
537
- end
538
-
539
- nil
540
- end
518
+ # NOTE: :restore_ts / :save_ts are intentionally NOT registered:
519
+ # variable storage is host side (RubyStorageManager), so save and
520
+ # restore run on the ruby evaluator. The old implementation wrote
521
+ # into per-variable GPU container buffers, a model the core no
522
+ # longer provides.
541
523
 
542
524
  def eval_operation(tensor, child_context)
543
525
  cache_key = "#{tensor.graph.object_id}_opencl_#{tensor.name}:#{object_id}"
@@ -854,19 +836,30 @@ module TensorStream
854
836
  end
855
837
 
856
838
  # automatically use sub buffers
839
+ # sub buffer regions must start/end on device memory alignment
840
+ # boundaries (CL_DEVICE_MEM_BASE_ADDR_ALIGN, in bits; 128 bytes on
841
+ # many CPU devices). Split/unstack piece sizes rarely satisfy that,
842
+ # so fall back to discrete buffers + device side copies.
843
+ def _sub_buffer_aligned?(start, length)
844
+ align = _opencl_queue.device.mem_base_addr_align / 8
845
+ (start % align).zero? && (length % align).zero?
846
+ end
847
+
857
848
  def _create_result_sub_buffer(parent_buffer, index, data_type, shape, name)
858
849
  cache_key ="_sub_result_#{parent_buffer.object_id}_#{name}_#{index}:#{object_id}"
859
850
  @context[:_cache][:_cl_buffers][cache_key] ||= begin
860
851
  size = shape.empty? || shape == [0] ? 1 : shape.reduce(:*)
861
852
  buffer = OpenCLBuffer.allocate_narray_for_type(data_type, size)
862
853
 
863
- if parent_buffer.cl_buffer.associated_memobject.nil?
864
- start = index * buffer.size * buffer.element_size
865
- region = OpenCL::BufferRegion::new(start, buffer.size * buffer.element_size)
854
+ region_size_in_bytes = buffer.size * buffer.element_size
855
+ start = index * region_size_in_bytes
856
+
857
+ if parent_buffer.cl_buffer.associated_memobject.nil? && _sub_buffer_aligned?(start, region_size_in_bytes)
858
+ region = OpenCL::BufferRegion::new(start, region_size_in_bytes)
866
859
  cl_buffer = parent_buffer.cl_buffer.create_sub_buffer(OpenCL::BUFFER_CREATE_TYPE_REGION, region)
867
860
  OpenCLBuffer.new(self, data_type: data_type, shape: shape, buffer: buffer, cl_buffer: cl_buffer, name: name)
868
861
  else # source buffer already a sub buffer, OpenCL does not allow sub buffers from sub buffers
869
- _create_result_buffer(tensor.data_type, shape, name)
862
+ _create_result_buffer(data_type, shape, name)
870
863
  end
871
864
  end
872
865
 
@@ -891,12 +884,12 @@ module TensorStream
891
884
  size = shape.empty? || shape == [0] ? 1 : shape.reduce(:*)
892
885
  buffer = OpenCLBuffer.allocate_narray_for_type(data_type, size)
893
886
 
894
- if parent_buffer.cl_buffer.associated_memobject.nil?
887
+ if parent_buffer.cl_buffer.associated_memobject.nil? && _sub_buffer_aligned?(start, region_size_in_bytes)
895
888
  region = OpenCL::BufferRegion::new(start, region_size_in_bytes)
896
889
  cl_buffer = parent_buffer.cl_buffer.create_sub_buffer(OpenCL::BUFFER_CREATE_TYPE_REGION, region)
897
890
  OpenCLBuffer.new(self, data_type: data_type, shape: shape, buffer: buffer, cl_buffer: cl_buffer, name: "#{name}/sub")
898
891
  else
899
- _create_result_buffer(tensor.data_type, shape, name)
892
+ _create_result_buffer(data_type, shape, name)
900
893
  end
901
894
  end
902
895
 
@@ -11,7 +11,7 @@ class OpenclTemplateHelper
11
11
  current_scope.local_variable_set(k.to_sym, v)
12
12
  end
13
13
 
14
- ERB.new(@source, nil, '%').result(current_scope)
14
+ ERB.new(@source, trim_mode: '%').result(current_scope)
15
15
  end
16
16
 
17
17
  def floating_point?(dtype)
@@ -25,7 +25,7 @@ class OpenclTemplateHelper
25
25
  locals.each do |k, v|
26
26
  current_scope.local_variable_set(k.to_sym, v)
27
27
  end
28
- ERB.new(source, nil, '%').result(current_scope)
28
+ ERB.new(source, trim_mode: '%').result(current_scope)
29
29
  end
30
30
 
31
31
  def dtype_to_c_type(dtype)
@@ -6,34 +6,57 @@ module TensorStream
6
6
 
7
7
  def RandomOps.included(klass)
8
8
  klass.class_eval do
9
- register_op :random_uniform do |context, tensor, inputs|
10
- maxval = tensor.options.fetch(:maxval, 1)
11
- minval = tensor.options.fetch(:minval, 0)
9
+ register_op :truncated_normal do |context, tensor, inputs|
12
10
  seed = tensor.options[:seed]
11
+ random = _get_randomizer(tensor, seed)
12
+ r = RandomGaussian.new(tensor.options.fetch(:mean), tensor.options.fetch(:stddev), -> { random.rand })
13
+ generator = -> { r.rand }
14
+ buffer = _randomizer(context, tensor, inputs, generator)
15
+ buffer.sync!
16
+ mean = buffer.buffer.mean
17
+ random_values = buffer.buffer
18
+ stddev = Math.sqrt(random_values.map { |v| (v - mean)**2 }.sum / (random_values.size - 1))
19
+ minval = random_values.min
20
+ maxval = random_values.max
21
+ max_iterations = 100
13
22
 
14
- rand_buffer = @context[:_cache][:_cl_buffers]["_rand"] ||= begin
15
- @context[:_cache][:_cl_buffers]["_rand_seed_ptr"] = 0
16
- random = _get_randomizer(tensor, seed)
17
- rand_table = RAND_TABLE_SIZE.times.map { random.rand }
18
- convert_to_opencl(rand_table, [RAND_TABLE_SIZE], data_type: tensor.data_type, name: "rand_#{tensor.data_type}")
23
+ if (minval.infinite? && minval < 0.0) || (maxval < mean)
24
+ # Reverse all calculations. normMin and normMax will be flipped.
25
+ a = minval
26
+ minval = maxval
27
+ maxval = a
28
+ stddev = -stddev
19
29
  end
20
- @context[:_cache][:_cl_buffers]["_rand_seed_ptr"] ||= 0
21
30
 
22
- seed_ptr = @context[:_cache][:_cl_buffers]["_rand_seed_ptr"]
31
+ norm_min = (minval - mean) / stddev
32
+ norm_max = (maxval - mean) / stddev
23
33
 
24
- shape = read_final_result(complete_eval(inputs[0], context))
25
- shape = shape || tensor.shape.shape
26
- workgroup = [shape.reduce(:*) || 1 ]
27
- cl_seed_ptr = OpenCL::Int1.new(seed_ptr)
28
- cl_min = OpenCL::Float1.new(minval)
29
- cl_max = OpenCL::Float1.new(maxval)
34
+ val = random_values.map { |v|
35
+ iterations = 0
36
+ pick = v
37
+ while (pick > norm_max) || (pick < norm_min)
38
+ pick = generator.call
39
+ iterations += 1
40
+ if iterations > max_iterations
41
+ pick = v
42
+ break
43
+ end
44
+ end
30
45
 
31
- @context[:_cache][:_cl_buffers]["_rand_seed_ptr"] = (seed_ptr + (shape.reduce(:*) || 0) ) % RAND_TABLE_SIZE
32
- buffer = _create_result_buffer(tensor.data_type, shape, tensor.name)
33
- buffer.op = _cl_program("random_uniform", dtype: tensor.data_type, tsize: RAND_TABLE_SIZE).send(:"random_uniform_#{tensor.data_type}", _opencl_queue, workgroup, cl_seed_ptr, cl_min, cl_max, rand_buffer.cl_buffer, buffer.cl_buffer)
46
+ pick
47
+ }
48
+ buffer.buffer = val
49
+ buffer.op = _opencl_queue.enqueue_write_buffer(buffer.cl_buffer, buffer.buffer)
34
50
  buffer
35
51
  end
36
52
 
53
+ register_op :random_uniform do |context, tensor, inputs|
54
+ seed = tensor.options[:seed]
55
+ random = _get_randomizer(tensor, seed)
56
+ generator = ->() { random.rand }
57
+ _randomizer(context, tensor, inputs, generator)
58
+ end
59
+
37
60
  def _get_randomizer(tensor, seed)
38
61
  if tensor.graph.random_seed && seed
39
62
  Random.new(tensor.graph.random_seed ^ seed)
@@ -47,6 +70,36 @@ module TensorStream
47
70
  Random.new
48
71
  end
49
72
  end
73
+
74
+ def _randomizer(context, tensor, inputs, func)
75
+ maxval = tensor.options.fetch(:maxval, 1)
76
+ minval = tensor.options.fetch(:minval, 0)
77
+ seed = tensor.options[:seed]
78
+ table_size = tensor.options[:pre_gen_table_size] || RAND_TABLE_SIZE
79
+
80
+ seed_ptr_key_name = "_rand_seed_ptr_#{tensor.operation}_#{seed}"
81
+ rand_buffer = @context[:_cache][:_cl_buffers]["_rand_#{tensor.operation}_#{seed}"] ||= begin
82
+ @context[:_cache][:_cl_buffers][seed_ptr_key_name] = 0
83
+ rand_table = table_size.times.map { func.call }
84
+ convert_to_opencl(rand_table, [table_size], data_type: tensor.data_type, name: "rand_#{tensor.operation}_#{seed}_#{tensor.data_type}")
85
+ end
86
+
87
+ @context[:_cache][:_cl_buffers][seed_ptr_key_name] ||= 0
88
+
89
+ seed_ptr = @context[:_cache][:_cl_buffers][seed_ptr_key_name]
90
+
91
+ shape = read_final_result(complete_eval(inputs[0], context))
92
+ shape = shape || tensor.shape.shape
93
+ workgroup = [shape.reduce(:*) || 1 ]
94
+ cl_seed_ptr = OpenCL::Int1.new(seed_ptr)
95
+ cl_min = OpenCL::Float1.new(minval)
96
+ cl_max = OpenCL::Float1.new(maxval)
97
+
98
+ @context[:_cache][:_cl_buffers][seed_ptr_key_name] = (seed_ptr + (shape.reduce(:*) || 0) ) % RAND_TABLE_SIZE
99
+ buffer = _create_result_buffer(tensor.data_type, shape, tensor.name)
100
+ buffer.op = _cl_program("random_uniform", dtype: tensor.data_type, tsize: RAND_TABLE_SIZE).send(:"random_uniform_#{tensor.data_type}", _opencl_queue, workgroup, cl_seed_ptr, cl_min, cl_max, rand_buffer.cl_buffer, buffer.cl_buffer)
101
+ buffer
102
+ end
50
103
  end
51
104
  end
52
105
  end
@@ -1,5 +1,5 @@
1
1
  module TensorStream
2
2
  module Opencl
3
- VERSION = "0.3.2"
3
+ VERSION = "0.4.0"
4
4
  end
5
5
  end
@@ -0,0 +1,173 @@
1
+ # A ruby port of the example code discussed by Martin Gorner in
2
+ # "TensorFlow and Deep Learning without a PhD, Part 1 (Google Cloud Next '17)""
3
+ #
4
+ # https://www.youtube.com/watch?v=u4alGiomYP4
5
+ #
6
+ # Requirements:
7
+ # mnist-learn gem
8
+ # opencl_ruby_ffi gem
9
+ require "bundler/setup"
10
+ require 'tensor_stream'
11
+ require 'mnist-learn'
12
+ require 'pry-byebug'
13
+ require 'csv'
14
+
15
+ # Enable OpenCL hardware accelerated computation, not using OpenCL can be very slow
16
+ require 'tensor_stream/opencl'
17
+
18
+ tf = TensorStream
19
+ puts "Tensorstream version #{tf.__version__} with OpenCL lib #{TensorStream::Opencl::VERSION}"
20
+
21
+ # Import MNIST data
22
+ puts "downloading minst data"
23
+ # Download images and labels into mnist.test (10K images+labels) and mnist.train (60K images+labels)
24
+ mnist = Mnist.read_data_sets('/tmp/data', one_hot: true)
25
+
26
+ puts "downloading finished"
27
+
28
+ # neural network structure for this sample:
29
+ #
30
+ # · · · · · · · · · · (input data, 1-deep) X [batch, 28, 28, 1]
31
+ # @ @ @ @ @ @ @ @ @ @ -- conv. layer 5x5x1=>4 stride 1 W1 [5, 5, 1, 4] B1 [4]
32
+ # ∶∶∶∶∶∶∶∶∶∶∶∶∶∶∶∶∶∶∶ Y1 [batch, 28, 28, 4]
33
+ # @ @ @ @ @ @ @ @ -- conv. layer 5x5x4=>8 stride 2 W2 [5, 5, 4, 8] B2 [8]
34
+ # ∶∶∶∶∶∶∶∶∶∶∶∶∶∶∶ Y2 [batch, 14, 14, 8]
35
+ # @ @ @ @ @ @ -- conv. layer 4x4x8=>12 stride 2 W3 [4, 4, 8, 12] B3 [12]
36
+ # ∶∶∶∶∶∶∶∶∶∶∶ Y3 [batch, 7, 7, 12] => reshaped to YY [batch, 7*7*12]
37
+ # \x/x\x\x/ -- fully connected layer (relu) W4 [7*7*12, 200] B4 [200]
38
+ # · · · · Y4 [batch, 200]
39
+ # \x/x\x/ -- fully connected layer (softmax) W5 [200, 10] B5 [10]
40
+ # · · · Y [batch, 10]
41
+
42
+
43
+ # input X: 28x28 grayscale images, the first dimension (None) will index the images in the mini-batch
44
+ selection = tf.placeholder(:int32)
45
+
46
+ x = tf.placeholder(:float32)
47
+ y_ = tf.placeholder(:float32)
48
+
49
+ # step for variable learning rate
50
+ step = tf.placeholder(:int32)
51
+
52
+ pkeep = tf.placeholder(:float32)
53
+
54
+ # three convolutional layers with their channel counts, and a
55
+ # fully connected layer (tha last layer has 10 softmax neurons)
56
+
57
+ K = 4 # first convolutional layer output depth
58
+ L = 8 # second convolutional layer output depth
59
+ M = 12 # third convolutional layer
60
+ N = 200 # fully connected layer
61
+
62
+
63
+ w1 = tf.variable(tf.truncated_normal([6, 6, 1, K], stddev: 0.1))
64
+ b1 = tf.variable(tf.ones([K])/10)
65
+
66
+ w2 = tf.variable(tf.truncated_normal([5, 5, K, L], stddev: 0.1))
67
+ b2 = tf.variable(tf.ones([L])/10)
68
+
69
+ w3 = tf.variable(tf.truncated_normal([4, 4, L, M], stddev: 0.1))
70
+ b3 = tf.variable(tf.ones([M])/10)
71
+
72
+ w4 = tf.variable(tf.truncated_normal([7 * 7 * M, N], stddev: 0.1))
73
+ b4 = tf.variable(tf.ones([N])/10)
74
+
75
+ w5 = tf.variable(tf.truncated_normal([N, 10], stddev: 0.1))
76
+ b5 = tf.variable(tf.ones([10])/10)
77
+
78
+ # load train images to memory
79
+ images = mnist.train.images
80
+ labels = mnist.train.labels
81
+ test_images = mnist.test.images
82
+ test_labels = mnist.test.labels
83
+
84
+ all_train_images = tf.constant(images, name: 'train_images')
85
+ all_train_labels = tf.constant(labels, name: 'train_labels')
86
+ all_test_images = tf.constant(test_images, name: 'test_images')
87
+ all_test_labels = tf.constant(test_labels, name: 'test_labels')
88
+
89
+ # The model
90
+ stride = 1 # output is 28x28
91
+
92
+ train_x = tf.cast(tf.gather(all_train_images, selection), :float32)
93
+ train_y = tf.cast(tf.gather(all_train_labels, selection), :float32)
94
+
95
+ test_x = tf.cast(all_train_images, :float32)
96
+ test_y = tf.cast(all_train_labels, :float32)
97
+
98
+ y1 = tf.nn.relu(tf.nn.conv2d(tf.reshape(x, [-1, 28, 28, 1]), w1, [1, stride, stride, 1], 'SAME') + b1)
99
+ stride = 2 # output is 14x14
100
+ y2 = tf.nn.relu(tf.nn.conv2d(y1, w2, [1, stride, stride, 1], 'SAME') + b2)
101
+ stride = 2 # output is 7x7
102
+ y3 = tf.nn.relu(tf.nn.conv2d(y2, w3, [1, stride, stride, 1], 'SAME') + b3)
103
+
104
+ # reshape the output from the third convolution for the fully connected layer
105
+ yy = tf.reshape(y3, [-1, 7 * 7 * M])
106
+ y4 = tf.nn.relu(tf.matmul(yy, w4) + b4)
107
+ YY4 = tf.nn.dropout(y4, pkeep)
108
+ ylogits = tf.matmul(YY4, w5) + b5
109
+
110
+ # model
111
+ y = tf.nn.softmax(ylogits, name: 'out')
112
+
113
+
114
+
115
+ # training step, learning rate = 0.003
116
+
117
+
118
+ # cross-entropy loss function (= -sum(Y_i * log(Yi)) ), normalised for batches of 100 images
119
+ # TensorFlow provides the softmax_cross_entropy_with_logits function to avoid numerical stability
120
+ # problems with log(0) which is NaN
121
+ cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits: ylogits, labels: y_)
122
+ cross_entropy = tf.reduce_mean(cross_entropy)*100
123
+
124
+ is_correct = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
125
+ accuracy = tf.reduce_mean(tf.cast(is_correct, :float32))
126
+
127
+ # training step, learning rate = 0.003
128
+ lr = 0.0001.t + tf.train.exponential_decay(0.003, step, 2000, 1/Math::E)
129
+ train_step = TensorStream::Train::AdamOptimizer.new(lr).minimize(cross_entropy)
130
+
131
+ sess = tf.session(profile_enabled: true)
132
+ # Add ops to save and restore all the variables.
133
+
134
+ init = tf.global_variables_initializer
135
+
136
+ sess.run(init)
137
+
138
+ #Setup save and restore
139
+ model_save_path = "test_models/mnist_data_3.0_preload"
140
+ saver = tf::Train::Saver.new
141
+ saver.restore(sess, model_save_path)
142
+
143
+
144
+ test_data = { x => test_x, y_ => test_y, pkeep => 1.0 }
145
+
146
+ selections = (0...60_000).to_a
147
+
148
+ (0..10001).each do |i|
149
+ # load batch of images and correct answers
150
+ current_selection = selections.sample(100)
151
+ train_data = { x => train_x, y_ => train_y, selection => current_selection, step => i, pkeep => 0.75 }
152
+
153
+ # train
154
+ sess.run(train_step, feed_dict: train_data)
155
+
156
+ if (i % 10 == 0)
157
+ # result = TensorStream::ReportTool.profile_for(sess)
158
+ # File.write("profile.csv", result.map(&:to_csv).join("\n"))
159
+ # success? add code to print it
160
+ a_train, c_train, l = sess.run([accuracy, cross_entropy, lr], feed_dict: { x => train_x, y_ => train_y, selection => current_selection, step => i, pkeep => 1.0})
161
+ puts "#{i}: accuracy:#{a_train} loss:#{c_train} (lr:#{l})"
162
+ end
163
+
164
+ if (i % 100 == 0)
165
+ # success on test data?
166
+ a_test, c_test = sess.run([accuracy, cross_entropy], feed_dict: test_data)
167
+ puts("#{i}: ******** test accuracy: #{a_test} test loss: #{c_test}")
168
+
169
+ # save current state of the model
170
+ # save_path = saver.save(sess, model_save_path)
171
+ end
172
+ end
173
+
@@ -39,7 +39,10 @@ Gem::Specification.new do |spec|
39
39
  spec.add_development_dependency "awesome_print"
40
40
  spec.add_development_dependency "mnist-learn"
41
41
  spec.add_development_dependency "simplecov"
42
- spec.add_dependency "tensor_stream", "1.0.7"
42
+ spec.add_dependency "tensor_stream", ">= 1.3"
43
43
  spec.add_dependency "opencl_ruby_ffi"
44
+ spec.add_dependency "narray_ffi"
44
45
  spec.add_dependency "oily_png"
46
+ spec.add_dependency "jpeg"
45
47
  end
48
+
metadata CHANGED
@@ -1,14 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: tensor_stream-opencl
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.2
4
+ version: 0.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Joseph Dayo
8
- autorequire:
9
8
  bindir: exe
10
9
  cert_chain: []
11
- date: 2019-06-09 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
12
11
  dependencies:
13
12
  - !ruby/object:Gem::Dependency
14
13
  name: bundler
@@ -112,16 +111,16 @@ dependencies:
112
111
  name: tensor_stream
113
112
  requirement: !ruby/object:Gem::Requirement
114
113
  requirements:
115
- - - '='
114
+ - - ">="
116
115
  - !ruby/object:Gem::Version
117
- version: 1.0.7
116
+ version: '1.3'
118
117
  type: :runtime
119
118
  prerelease: false
120
119
  version_requirements: !ruby/object:Gem::Requirement
121
120
  requirements:
122
- - - '='
121
+ - - ">="
123
122
  - !ruby/object:Gem::Version
124
- version: 1.0.7
123
+ version: '1.3'
125
124
  - !ruby/object:Gem::Dependency
126
125
  name: opencl_ruby_ffi
127
126
  requirement: !ruby/object:Gem::Requirement
@@ -136,6 +135,20 @@ dependencies:
136
135
  - - ">="
137
136
  - !ruby/object:Gem::Version
138
137
  version: '0'
138
+ - !ruby/object:Gem::Dependency
139
+ name: narray_ffi
140
+ requirement: !ruby/object:Gem::Requirement
141
+ requirements:
142
+ - - ">="
143
+ - !ruby/object:Gem::Version
144
+ version: '0'
145
+ type: :runtime
146
+ prerelease: false
147
+ version_requirements: !ruby/object:Gem::Requirement
148
+ requirements:
149
+ - - ">="
150
+ - !ruby/object:Gem::Version
151
+ version: '0'
139
152
  - !ruby/object:Gem::Dependency
140
153
  name: oily_png
141
154
  requirement: !ruby/object:Gem::Requirement
@@ -150,6 +163,20 @@ dependencies:
150
163
  - - ">="
151
164
  - !ruby/object:Gem::Version
152
165
  version: '0'
166
+ - !ruby/object:Gem::Dependency
167
+ name: jpeg
168
+ requirement: !ruby/object:Gem::Requirement
169
+ requirements:
170
+ - - ">="
171
+ - !ruby/object:Gem::Version
172
+ version: '0'
173
+ type: :runtime
174
+ prerelease: false
175
+ version_requirements: !ruby/object:Gem::Requirement
176
+ requirements:
177
+ - - ">="
178
+ - !ruby/object:Gem::Version
179
+ version: '0'
153
180
  description: OpenCL evaluator for tensor_stream
154
181
  email:
155
182
  - joseph.dayo@gmail.com
@@ -157,10 +184,12 @@ executables: []
157
184
  extensions: []
158
185
  extra_rdoc_files: []
159
186
  files:
187
+ - ".github/workflows/ci.yml"
160
188
  - ".gitignore"
161
189
  - ".rspec"
162
190
  - ".rubocop.yml"
163
191
  - ".travis.yml"
192
+ - CHANGELOG.md
164
193
  - CODE_OF_CONDUCT.md
165
194
  - Gemfile
166
195
  - LICENSE.txt
@@ -173,6 +202,7 @@ files:
173
202
  - benchmark_ryzen.txt
174
203
  - benchmark_ryzen_nvidia.txt
175
204
  - bin/console
205
+ - bin/opencl_check.rb
176
206
  - bin/setup
177
207
  - lib/tensor_stream/opencl.rb
178
208
  - lib/tensor_stream/opencl/array_ops.rb
@@ -266,6 +296,7 @@ files:
266
296
  - samples/mnist_data_2.2.rb
267
297
  - samples/mnist_data_2.3.rb
268
298
  - samples/mnist_data_3.0.rb
299
+ - samples/mnist_data_3.0_preload.rb
269
300
  - samples/mnist_image.ipynb
270
301
  - samples/multigpu.rb
271
302
  - samples/nearest_neighbor.rb
@@ -276,7 +307,6 @@ licenses:
276
307
  - MIT
277
308
  metadata:
278
309
  allowed_push_host: https://rubygems.org
279
- post_install_message:
280
310
  rdoc_options: []
281
311
  require_paths:
282
312
  - lib
@@ -291,8 +321,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
291
321
  - !ruby/object:Gem::Version
292
322
  version: '0'
293
323
  requirements: []
294
- rubygems_version: 3.0.3
295
- signing_key:
324
+ rubygems_version: 4.0.20
296
325
  specification_version: 4
297
326
  summary: OpenCL evaluator for tensor_stream
298
327
  test_files: []