Module: Torch::Native::Generator

Defined in:
lib/torch/native/generator.rb

Class Method Summary collapse

Class Method Details

.generate_cpp_functionsObject



10
11
12
13
14
15
# File 'lib/torch/native/generator.rb', line 10

def generate_cpp_functions
  functions = grouped_functions
  generate_cpp_file("torch", :define_singleton_method, functions[:torch])
  generate_cpp_file("tensor", :define_method, functions[:tensor])
  generate_cpp_file("nn", :define_singleton_method, functions[:nn])
end

.grouped_functionsObject



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
66
67
68
69
70
# File 'lib/torch/native/generator.rb', line 17

def grouped_functions
  functions = functions()

  # skip functions
  skip_args = ["bool[3]", "Dimname", "MemoryFormat", "Layout", "Storage", "ConstQuantizerPtr"]

  # remove functions
  functions.reject! do |f|
    f.ruby_name.start_with?("_") ||
    f.ruby_name.end_with?("_backward") ||
    f.args.any? { |a| a[:type].include?("Dimname") }
  end

  # separate out into todo
  todo_functions, functions =
    functions.partition do |f|
      f.args.any? do |a|
        a[:type].include?("?") && !["Tensor?", "Generator?", "int?", "ScalarType?"].include?(a[:type]) ||
        skip_args.any? { |sa| a[:type].include?(sa) } ||
        # native_functions.yaml is missing size argument for normal
        # https://pytorch.org/cppdocs/api/function_namespacetorch_1a80253fe5a3ded4716ec929a348adb4b9.html
        (f.base_name == "normal" && !f.out?)
      end
    end

  # generate additional functions for optional arguments
  # there may be a better way to do this
  optional_functions, functions = functions.partition { |f| f.args.any? { |a| a[:type] == "int?" } }
  optional_functions.each do |f|
    next if f.ruby_name == "cross"
    next if f.ruby_name.start_with?("avg_pool") && f.out?

    opt_args = f.args.select { |a| a[:type] == "int?" }
    if opt_args.size == 1
      sep = f.name.include?(".") ? "_" : "."
      f1 = Function.new(f.function.merge("func" => f.func.sub("(", "#{sep}#{opt_args.first[:name]}(").gsub("int?", "int")))
      # TODO only remove some arguments
      f2 = Function.new(f.function.merge("func" => f.func.sub(/, int\?.+\) ->/, ") ->")))
      functions << f1
      functions << f2
    end
  end

  # todo_functions.each do |f|
  #   puts f.func
  #   puts
  # end

  nn_functions, other_functions = functions.partition { |f| f.python_module == "nn" }
  torch_functions = other_functions.select { |f| f.variants.include?("function") }
  tensor_functions = other_functions.select { |f| f.variants.include?("method") }

  {torch: torch_functions, tensor: tensor_functions, nn: nn_functions}
end