tensor_stream-opencl 0.3.1 → 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.
@@ -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