Class: TensorStream::GraphBuilder

Inherits:
Object
  • Object
show all
Includes:
OpHelper, StringHelper
Defined in:
lib/tensor_stream/graph_builder.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from StringHelper

#camelize, #constantize, #symbolize_keys, #underscore

Methods included from OpHelper

#_op, #cons, #format_source, #fp_type?, #i_cons, #i_op, #i_var, #int_type?, #reduced_shape, #shape_eval, #shape_full_specified, #shapes_fully_specified_and_equal

Constructor Details

#initialize(graph) ⇒ GraphBuilder

Returns a new instance of GraphBuilder.



8
9
10
# File 'lib/tensor_stream/graph_builder.rb', line 8

def initialize(graph)
  @graph = graph
end

Instance Attribute Details

#graphObject

Returns the value of attribute graph.



6
7
8
# File 'lib/tensor_stream/graph_builder.rb', line 6

def graph
  @graph
end

Instance Method Details

#build(buffer) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/tensor_stream/graph_builder.rb', line 12

def build(buffer)
  protobuf = TensorStream::Protobuf.new
  parsed_tree = protobuf.load_from_string(buffer)
  parsed_tree.each do |node|
    next unless node["type"] == "node"

    # puts "build #{node['name']}"
    options = protobuf.options_evaluator(node)
    options[:name] = node["name"]
    options[:__graph] = @graph
    value = options.delete("value")
    options = symbolize_keys(options)
    case node["op"]
    when "Const"
      dimension = shape_eval(value)
      rank = dimension.size
      options[:value] = value
      options[:const] = true
      TensorStream::Constant.new(options[:dtype] || options[:T], rank, dimension, options)
    when "VariableV2"
      # evaluate options
      shape = options[:shape]
      i_var(options[:dtype] || options[:T], nil, shape, nil, options)
    when "Placeholder"
      shape = options[:shape]
      TensorStream::Placeholder.new(options[:dtype] || options[:T], nil, shape, options)
    else
      op = underscore(node["op"]).to_sym
      puts "warning unsupported op #{op}" unless TensorStream::Evaluator::RubyEvaluator.ops.key?(op)

      # map input tensor
      inputs = node["input"].map { |input|
        input[0] = "" if input.start_with?("^")

        input_indexed, index = input.split(":")

        tensor = if index && index.to_i > 0
          @graph.get_tensor_by_name(input_indexed)[index.to_i]
        else
          @graph.get_tensor_by_name(input)
        end

        raise "tensor not found by name #{input}" if tensor.nil?

        tensor
      }

      options[:data_type] = options.delete(:T)
      Graph.get_default_graph.add_op!(op, *inputs, options)
    end
  end

  @graph
end