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.
- checksums.yaml +4 -4
- data/.github/workflows/ci.yml +35 -0
- data/CHANGELOG.md +38 -0
- data/Gemfile +16 -0
- data/README.md +28 -0
- data/benchmark/benchmark.rb +67 -46
- data/benchmark.json +704 -0
- data/bin/opencl_check.rb +32 -0
- data/lib/tensor_stream/opencl/array_ops.rb +24 -0
- data/lib/tensor_stream/opencl/images_ops.rb +52 -11
- data/lib/tensor_stream/opencl/nn_ops.rb +35 -219
- data/lib/tensor_stream/opencl/opencl_buffer.rb +12 -0
- data/lib/tensor_stream/opencl/opencl_evaluator.rb +81 -67
- data/lib/tensor_stream/opencl/opencl_template_helper.rb +2 -2
- data/lib/tensor_stream/opencl/random_ops.rb +72 -19
- data/lib/tensor_stream/opencl/version.rb +1 -1
- data/samples/mnist_data_3.0_preload.rb +173 -0
- data/tensor_stream-opencl.gemspec +5 -2
- metadata +44 -14
|
@@ -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
|
-
|
|
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
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
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
|
-
|
|
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
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
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}"
|
|
@@ -622,15 +604,15 @@ module TensorStream
|
|
|
622
604
|
|
|
623
605
|
if assign.container_buffer
|
|
624
606
|
event_wait_list = build_event_wait_list([buffer, assign.container_buffer])
|
|
625
|
-
assign.container_buffer.op = if assign.container_buffer.cl_buffer != buffer.cl_buffer
|
|
626
|
-
_opencl_queue.enqueue_copy_buffer(buffer.cl_buffer, assign.container_buffer.cl_buffer, event_wait_list: event_wait_list)
|
|
627
|
-
else
|
|
628
|
-
buffer.op
|
|
629
|
-
end
|
|
630
607
|
else
|
|
631
|
-
|
|
632
|
-
assign.options[:container].buffer =
|
|
633
|
-
|
|
608
|
+
var_buffer = _create_result_buffer(buffer.data_type, buffer.shape, tensor.name)
|
|
609
|
+
assign.options[:container].buffer = var_buffer
|
|
610
|
+
end
|
|
611
|
+
|
|
612
|
+
assign.container_buffer.op = if assign.container_buffer.cl_buffer != buffer.cl_buffer
|
|
613
|
+
_opencl_queue.enqueue_copy_buffer(buffer.cl_buffer, assign.container_buffer.cl_buffer, event_wait_list: event_wait_list)
|
|
614
|
+
else
|
|
615
|
+
buffer.op
|
|
634
616
|
end
|
|
635
617
|
|
|
636
618
|
assign.container_buffer.dirty = true
|
|
@@ -797,7 +779,7 @@ module TensorStream
|
|
|
797
779
|
|
|
798
780
|
return nil if buffer.nil?
|
|
799
781
|
|
|
800
|
-
cl_buffer = unless value
|
|
782
|
+
cl_buffer = unless array_fast_empty?(value)
|
|
801
783
|
cl_buffer_size = 1 if cl_buffer_size.zero?
|
|
802
784
|
_opencl_context.create_buffer(cl_buffer_size * buffer.element_size)
|
|
803
785
|
end
|
|
@@ -810,8 +792,8 @@ module TensorStream
|
|
|
810
792
|
cl_object.buffer[index] = c
|
|
811
793
|
end
|
|
812
794
|
elsif value.is_a?(Array)
|
|
813
|
-
value.flatten.each_with_index do |element, index|
|
|
814
|
-
|
|
795
|
+
cast_value = value.flatten.each_with_index.map do |element, index|
|
|
796
|
+
if element.is_a?(Tensor)
|
|
815
797
|
read_final_result(complete_eval(element, {}))
|
|
816
798
|
elsif data_type == :boolean
|
|
817
799
|
element ? 1 : 0
|
|
@@ -819,6 +801,10 @@ module TensorStream
|
|
|
819
801
|
Tensor.cast_dtype(element, data_type)
|
|
820
802
|
end
|
|
821
803
|
end
|
|
804
|
+
|
|
805
|
+
cast_value.each_with_index do |v, index|
|
|
806
|
+
cl_object.buffer[index] = v
|
|
807
|
+
end
|
|
822
808
|
elsif value.is_a?(NArray)
|
|
823
809
|
cl_object.buffer = value
|
|
824
810
|
elsif data_type == :boolean
|
|
@@ -850,19 +836,30 @@ module TensorStream
|
|
|
850
836
|
end
|
|
851
837
|
|
|
852
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
|
+
|
|
853
848
|
def _create_result_sub_buffer(parent_buffer, index, data_type, shape, name)
|
|
854
849
|
cache_key ="_sub_result_#{parent_buffer.object_id}_#{name}_#{index}:#{object_id}"
|
|
855
850
|
@context[:_cache][:_cl_buffers][cache_key] ||= begin
|
|
856
851
|
size = shape.empty? || shape == [0] ? 1 : shape.reduce(:*)
|
|
857
852
|
buffer = OpenCLBuffer.allocate_narray_for_type(data_type, size)
|
|
858
853
|
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
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)
|
|
862
859
|
cl_buffer = parent_buffer.cl_buffer.create_sub_buffer(OpenCL::BUFFER_CREATE_TYPE_REGION, region)
|
|
863
860
|
OpenCLBuffer.new(self, data_type: data_type, shape: shape, buffer: buffer, cl_buffer: cl_buffer, name: name)
|
|
864
861
|
else # source buffer already a sub buffer, OpenCL does not allow sub buffers from sub buffers
|
|
865
|
-
_create_result_buffer(
|
|
862
|
+
_create_result_buffer(data_type, shape, name)
|
|
866
863
|
end
|
|
867
864
|
end
|
|
868
865
|
|
|
@@ -887,12 +884,12 @@ module TensorStream
|
|
|
887
884
|
size = shape.empty? || shape == [0] ? 1 : shape.reduce(:*)
|
|
888
885
|
buffer = OpenCLBuffer.allocate_narray_for_type(data_type, size)
|
|
889
886
|
|
|
890
|
-
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)
|
|
891
888
|
region = OpenCL::BufferRegion::new(start, region_size_in_bytes)
|
|
892
889
|
cl_buffer = parent_buffer.cl_buffer.create_sub_buffer(OpenCL::BUFFER_CREATE_TYPE_REGION, region)
|
|
893
890
|
OpenCLBuffer.new(self, data_type: data_type, shape: shape, buffer: buffer, cl_buffer: cl_buffer, name: "#{name}/sub")
|
|
894
891
|
else
|
|
895
|
-
_create_result_buffer(
|
|
892
|
+
_create_result_buffer(data_type, shape, name)
|
|
896
893
|
end
|
|
897
894
|
end
|
|
898
895
|
|
|
@@ -998,6 +995,23 @@ module TensorStream
|
|
|
998
995
|
|
|
999
996
|
arr != 0
|
|
1000
997
|
end
|
|
998
|
+
|
|
999
|
+
##
|
|
1000
|
+
# Fast way to determine if array is "empty" by including nested elements
|
|
1001
|
+
def array_fast_empty?(arr)
|
|
1002
|
+
return true if arr.size.zero?
|
|
1003
|
+
|
|
1004
|
+
arr.each do |a|
|
|
1005
|
+
if a.is_a?(Array)
|
|
1006
|
+
return false if !array_fast_empty?(a)
|
|
1007
|
+
|
|
1008
|
+
next
|
|
1009
|
+
end
|
|
1010
|
+
return false
|
|
1011
|
+
end
|
|
1012
|
+
|
|
1013
|
+
true
|
|
1014
|
+
end
|
|
1001
1015
|
end
|
|
1002
1016
|
end
|
|
1003
1017
|
end
|
|
@@ -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,
|
|
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,
|
|
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 :
|
|
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
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
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
|
-
|
|
31
|
+
norm_min = (minval - mean) / stddev
|
|
32
|
+
norm_max = (maxval - mean) / stddev
|
|
23
33
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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
|
-
|
|
32
|
-
|
|
33
|
-
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
|
|
@@ -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
|
+
|
|
@@ -32,14 +32,17 @@ Gem::Specification.new do |spec|
|
|
|
32
32
|
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
|
|
33
33
|
spec.require_paths = ["lib"]
|
|
34
34
|
|
|
35
|
-
spec.add_development_dependency "bundler"
|
|
35
|
+
spec.add_development_dependency "bundler"
|
|
36
36
|
spec.add_development_dependency "rake", "~> 10.0"
|
|
37
37
|
spec.add_development_dependency "rspec", "~> 3.0"
|
|
38
38
|
spec.add_development_dependency "pry-byebug"
|
|
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.
|
|
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
|
+
|