Caffe2 - Python API
A deep learning, cross platform ML framework
utils.py
1 import re
2 import os
3 from .nested_dict import nested_dict
4 
5 
6 __all__ = [
7  'CodeTemplate', 'IDENT_REGEX', 'YamlLoader', 'nested_dict',
8  'split_name_params', 'write',
9 ]
10 
11 try:
12  from src.ATen.code_template import CodeTemplate
13 except ImportError:
14  from tools.shared.module_loader import import_module
15  CodeTemplate = import_module('code_template', 'aten/src/ATen/code_template.py').CodeTemplate
16 
17 # You should use these lines, rather than doing it manually.
18 # Especially if you see this error!
19 #
20 # File "/usr/local/lib/python2.7/dist-packages/yaml/__init__.py", line 69, in load
21 # loader = Loader(stream)
22 # TypeError: 'module' object is not callable
23 try:
24  # use faster C loader if available
25  from yaml import CLoader as YamlLoader
26 except ImportError:
27  from yaml import Loader as YamlLoader
28 
29 GENERATED_COMMENT = CodeTemplate(
30  "@" + "generated from ${filename}")
31 
32 # Matches "foo" in "foo, bar" but not "foobar". Used to search for the
33 # occurence of a parameter in the derivative formula
34 IDENT_REGEX = r'(^|\W){}($|\W)'
35 
36 
37 # TODO: Use a real parser here; this will get bamboozled
38 # by signatures that contain things like std::array<bool, 2> (note the space)
39 def split_name_params(prototype):
40  name, params = re.match(r'(\w+)\((.*)\)', prototype).groups()
41  return name, params.split(', ')
42 
43 
44 # When tracing, we record inplace operations as out-of-place operations,
45 # because we don't have a story for side effects in the IR yet.
46 #
47 # Doing this un-inplacing is a little delicate however; __and__ is NOT inplace!
48 # TODO: Do something more robust
49 def uninplace_api_name(api_name):
50  if api_name.endswith('_') and not api_name.endswith('__'):
51  api_name = api_name[:-1]
52  if api_name.endswith('_out'):
53  api_name = api_name[:-4]
54  return api_name
55 
56 
57 def write(dirname, name, template, env):
58  env['generated_comment'] = GENERATED_COMMENT.substitute(filename=template.filename)
59  path = os.path.join(dirname, name)
60  # See Note [Unchanging results for ninja]
61  try:
62  with open(path, 'r') as f:
63  old_val = f.read()
64  except IOError:
65  old_val = None
66  new_val = template.substitute(env)
67  if old_val != new_val:
68  with open(path, 'w') as f:
69  print("Writing {}".format(path))
70  f.write(new_val)
71  else:
72  print("Skipped writing {}".format(path))