Caffe2 - Python API
A deep learning, cross platform ML framework
split_types.py
1 import os
2 import sys
3 
4 this_file = os.path.dirname(os.path.abspath(__file__))
5 generated_dir = os.path.abspath(os.path.join(this_file, '..', '..', 'torch', 'csrc', 'generated'))
6 
7 line_start = '//generic_include '
8 
9 types = [
10  'Double',
11  'Float',
12  'Half',
13  'Long',
14  'Int',
15  'Short',
16  'Char',
17  'Byte'
18 ]
19 
20 generic_include = '#define {lib}_GENERIC_FILE "{path}"'
21 generate_include = '#include "{lib}/{lib}Generate{type}Type.h"'
22 
23 
24 def get_gen_path_prefix(file_name):
25  gen_name_prefix = file_name[len('torch/csrc/'):].replace('/', '_').replace('.cpp', '')
26  gen_path_prefix = os.path.join(generated_dir, gen_name_prefix)
27  return gen_path_prefix
28 
29 
30 def split_types_ninja(file_name, w):
31  gen_path_prefix = get_gen_path_prefix(file_name)
32  to_build = [gen_path_prefix + t + '.cpp' for t in types]
33  myself = 'tools/setup_helpers/split_types.py'
34  cmd = "{} {} '{}'".format(sys.executable, myself, file_name)
35  w.writer.build(
36  to_build, 'do_cmd', [file_name, myself],
37  variables={
38  'cmd': cmd,
39  })
40  return to_build
41 
42 
43 def split_types(file_name, ninja_global):
44  # when ninja is enabled we just generate the build rule here
45  if ninja_global is not None:
46  return split_types_ninja(file_name, ninja_global)
47 
48  assert file_name.startswith('torch/csrc/')
49  if not os.path.exists(generated_dir):
50  os.makedirs(generated_dir)
51 
52  with open(file_name, 'r') as f:
53  lines = f.read().split('\n')
54 
55  # Find //generic_include
56  for i, l in enumerate(lines):
57  if l.startswith(line_start):
58  args = l[len(line_start):]
59  lib_prefix, generic_file = filter(bool, args.split())
60  break
61  else:
62  raise RuntimeError("generic include not found")
63 
64  gen_name_prefix = file_name[len('torch/csrc/'):].replace('/', '_').replace('.cpp', '')
65  gen_path_prefix = os.path.join(generated_dir, gen_name_prefix)
66 
67  prefix = '\n'.join(lines[:i])
68  suffix = '\n'.join(lines[i + 1:])
69 
70  to_build = []
71 
72  g_include = generic_include.format(lib=lib_prefix, path=generic_file)
73  for t in types:
74  t_include = generate_include.format(lib=lib_prefix, type=t)
75  gen_path = gen_path_prefix + t + '.cpp'
76  to_build.append(gen_path)
77  with open(gen_path, 'w') as f:
78  f.write(prefix + '\n' +
79  g_include + '\n' +
80  t_include + '\n' +
81  suffix)
82  return to_build
83 
84 # when called from ninja
85 if __name__ == '__main__':
86  file_name = sys.argv[1].strip("'")
87  split_types(file_name, None)
Module caffe2.python.layers.split.