net_printer.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. ## @package net_printer
  2. # Module caffe2.python.net_printer
  3. from caffe2.proto.caffe2_pb2 import OperatorDef, NetDef
  4. from caffe2.python.checkpoint import Job
  5. from caffe2.python.core import Net, ExecutionStep, Plan
  6. from caffe2.python.task import Task, TaskGroup, WorkspaceType, TaskOutput
  7. from collections import defaultdict
  8. from contextlib import contextmanager
  9. from copy import copy
  10. from future.utils import viewkeys
  11. from itertools import chain
  12. from six import binary_type, text_type
  13. class Visitor(object):
  14. @classmethod
  15. def register(cls, Type):
  16. if not(hasattr(cls, 'visitors')):
  17. cls.visitors = {}
  18. else:
  19. assert Type not in cls.visitors, \
  20. '{} already registered!'.format(Type)
  21. def _register(func):
  22. cls.visitors[Type] = func
  23. return func
  24. return _register
  25. def __call__(self, obj, *args, **kwargs):
  26. if obj is None:
  27. return
  28. Type = type(obj)
  29. if Type not in self.__class__.visitors:
  30. raise TypeError('%s: unsupported object type: %s' % (
  31. self.__class__.__name__, Type))
  32. func = self.__class__.visitors[Type]
  33. return func(self, obj, *args, **kwargs)
  34. class Analyzer(Visitor):
  35. PREFIXES_TO_IGNORE = {'distributed_ctx_init'}
  36. def __init__(self):
  37. self.workspaces = defaultdict(lambda: defaultdict(lambda: 0))
  38. self.workspace_ctx = []
  39. @property
  40. def workspace(self):
  41. return self.workspace_ctx[-1]
  42. @contextmanager
  43. def set_workspace(self, node=None, ws=None, do_copy=False):
  44. if ws is not None:
  45. ws = ws
  46. elif node is not None:
  47. ws = self.workspaces[str(node)]
  48. else:
  49. ws = self.workspace
  50. if do_copy:
  51. ws = copy(ws)
  52. self.workspace_ctx.append(ws)
  53. yield ws
  54. del self.workspace_ctx[-1]
  55. def define_blob(self, blob):
  56. self.workspace[blob] += 1
  57. def need_blob(self, blob):
  58. if any(blob.startswith(p) for p in Analyzer.PREFIXES_TO_IGNORE):
  59. return
  60. assert blob in self.workspace, 'Blob undefined: %s' % blob
  61. @Analyzer.register(OperatorDef)
  62. def analyze_op(analyzer, op):
  63. for x in op.input:
  64. analyzer.need_blob(x)
  65. for x in op.output:
  66. analyzer.define_blob(x)
  67. @Analyzer.register(Net)
  68. def analyze_net(analyzer, net):
  69. for x in net.Proto().op:
  70. analyzer(x)
  71. @Analyzer.register(ExecutionStep)
  72. def analyze_step(analyzer, step):
  73. proto = step.Proto()
  74. with analyzer.set_workspace(do_copy=proto.create_workspace):
  75. if proto.report_net:
  76. with analyzer.set_workspace(do_copy=True):
  77. analyzer(step.get_net(proto.report_net))
  78. all_new_blobs = set()
  79. substeps = step.Substeps() + [step.get_net(n) for n in proto.network]
  80. for substep in substeps:
  81. with analyzer.set_workspace(
  82. do_copy=proto.concurrent_substeps) as ws_in:
  83. analyzer(substep)
  84. if proto.should_stop_blob:
  85. analyzer.need_blob(proto.should_stop_blob)
  86. if proto.concurrent_substeps:
  87. new_blobs = set(viewkeys(ws_in)) - set(viewkeys(analyzer.workspace))
  88. assert len(all_new_blobs & new_blobs) == 0, (
  89. 'Error: Blobs created by multiple parallel steps: %s' % (
  90. ', '.join(all_new_blobs & new_blobs)))
  91. all_new_blobs |= new_blobs
  92. for x in all_new_blobs:
  93. analyzer.define_blob(x)
  94. @Analyzer.register(Task)
  95. def analyze_task(analyzer, task):
  96. # check that our plan protobuf is not too large (limit of 64Mb)
  97. step = task.get_step()
  98. plan = Plan(task.node)
  99. plan.AddStep(step)
  100. proto_len = len(plan.Proto().SerializeToString())
  101. assert proto_len < 2 ** 26, (
  102. 'Due to a protobuf limitation, serialized tasks must be smaller '
  103. 'than 64Mb, but this task has {} bytes.' % proto_len)
  104. is_private = task.workspace_type() != WorkspaceType.GLOBAL
  105. with analyzer.set_workspace(do_copy=is_private):
  106. analyzer(step)
  107. @Analyzer.register(TaskGroup)
  108. def analyze_task_group(analyzer, tg):
  109. for task in tg.tasks_by_node().tasks():
  110. with analyzer.set_workspace(node=task.node):
  111. analyzer(task)
  112. @Analyzer.register(Job)
  113. def analyze_job(analyzer, job):
  114. analyzer(job.init_group)
  115. analyzer(job.epoch_group)
  116. def analyze(obj):
  117. """
  118. Given a Job, visits all the execution steps making sure that:
  119. - no undefined blobs will be found during execution
  120. - no blob with same name is defined in concurrent steps
  121. """
  122. Analyzer()(obj)
  123. class Text(object):
  124. def __init__(self):
  125. self._indent = 0
  126. self._lines_in_context = [0]
  127. self.lines = []
  128. @contextmanager
  129. def context(self, text):
  130. if text is not None:
  131. self.add('with %s:' % text)
  132. self._indent += 4
  133. self._lines_in_context.append(0)
  134. yield
  135. if text is not None:
  136. if self._lines_in_context[-1] == 0:
  137. self.add('pass')
  138. self._indent -= 4
  139. del self._lines_in_context[-1]
  140. def add(self, text):
  141. self._lines_in_context[-1] += 1
  142. self.lines.append((' ' * self._indent) + text)
  143. def __str__(self):
  144. return '\n'.join(self.lines)
  145. class Printer(Visitor, Text):
  146. def __init__(self, factor_prefixes=False, c2_syntax=True):
  147. super(Visitor, self).__init__()
  148. super(Text, self).__init__()
  149. self.factor_prefixes = factor_prefixes
  150. self.c2_syntax = c2_syntax
  151. self.c2_net_name = None
  152. def _sanitize_str(s):
  153. if isinstance(s, text_type):
  154. sanitized = s
  155. elif isinstance(s, binary_type):
  156. sanitized = s.decode('ascii', errors='ignore')
  157. else:
  158. sanitized = str(s)
  159. if len(sanitized) < 64:
  160. return "'%s'" % sanitized
  161. else:
  162. return "'%s'" % sanitized[:64] + '...<+len=%d>' % (len(sanitized) - 64)
  163. def _arg_val(arg):
  164. if arg.HasField('f'):
  165. return str(arg.f)
  166. if arg.HasField('i'):
  167. return str(arg.i)
  168. if arg.HasField('s'):
  169. return _sanitize_str(arg.s)
  170. if arg.floats:
  171. return str(list(arg.floats))
  172. if arg.ints:
  173. return str(list(arg.ints))
  174. if arg.strings:
  175. return str([_sanitize_str(s) for s in arg.strings])
  176. return '[]'
  177. def commonprefix(m):
  178. "Given a list of strings, returns the longest common prefix"
  179. if not m:
  180. return ''
  181. s1 = min(m)
  182. s2 = max(m)
  183. for i, c in enumerate(s1):
  184. if c != s2[i]:
  185. return s1[:i]
  186. return s1
  187. def format_value(val):
  188. if isinstance(val, list):
  189. return '[%s]' % ', '.join("'%s'" % str(v) for v in val)
  190. else:
  191. return str(val)
  192. def factor_prefix(vals, do_it):
  193. vals = [format_value(v) for v in vals]
  194. prefix = commonprefix(vals) if len(vals) > 1 and do_it else ''
  195. joined = ', '.join(v[len(prefix):] for v in vals)
  196. return '%s[%s]' % (prefix, joined) if prefix else joined
  197. def call(op, inputs=None, outputs=None, factor_prefixes=False):
  198. if not inputs:
  199. inputs = ''
  200. else:
  201. inputs_v = [a for a in inputs if not isinstance(a, tuple)]
  202. inputs_kv = [a for a in inputs if isinstance(a, tuple)]
  203. inputs = ', '.join(
  204. x
  205. for x in chain(
  206. [factor_prefix(inputs_v, factor_prefixes)],
  207. ('%s=%s' % kv for kv in inputs_kv),
  208. )
  209. if x
  210. )
  211. call = '%s(%s)' % (op, inputs)
  212. return call if not outputs else '%s = %s' % (
  213. factor_prefix(outputs, factor_prefixes), call)
  214. def format_device_option(dev_opt):
  215. if not dev_opt or not (
  216. dev_opt.device_type or dev_opt.device_id or dev_opt.node_name):
  217. return None
  218. return call(
  219. 'DeviceOption',
  220. [dev_opt.device_type, dev_opt.device_id, "'%s'" % dev_opt.node_name])
  221. @Printer.register(OperatorDef)
  222. def print_op(text, op):
  223. args = [(a.name, _arg_val(a)) for a in op.arg]
  224. dev_opt_txt = format_device_option(op.device_option)
  225. if dev_opt_txt:
  226. args.append(('device_option', dev_opt_txt))
  227. if text.c2_net_name:
  228. text.add(call(
  229. text.c2_net_name + '.' + op.type,
  230. [list(op.input), list(op.output)] + args))
  231. else:
  232. text.add(call(
  233. op.type,
  234. list(op.input) + args,
  235. op.output,
  236. factor_prefixes=text.factor_prefixes))
  237. for arg in op.arg:
  238. if arg.HasField('n'):
  239. with text.context('arg: %s' % arg.name):
  240. text(arg.n)
  241. @Printer.register(NetDef)
  242. def print_net_def(text, net_def):
  243. if text.c2_syntax:
  244. text.add(call('core.Net', ["'%s'" % net_def.name], [net_def.name]))
  245. text.c2_net_name = net_def.name
  246. else:
  247. text.add('# net: %s' % net_def.name)
  248. for op in net_def.op:
  249. text(op)
  250. if text.c2_syntax:
  251. text.c2_net_name = None
  252. @Printer.register(Net)
  253. def print_net(text, net):
  254. text(net.Proto())
  255. def _get_step_context(step):
  256. proto = step.Proto()
  257. if proto.should_stop_blob:
  258. return call('loop'), False
  259. if proto.num_iter and proto.num_iter != 1:
  260. return call('loop', [proto.num_iter]), False
  261. if proto.num_concurrent_instances > 1:
  262. return (
  263. call('parallel',
  264. [('num_instances', proto.num_concurrent_instances)]),
  265. len(step.Substeps()) > 1)
  266. concurrent = proto.concurrent_substeps and len(step.Substeps()) > 1
  267. if concurrent:
  268. return call('parallel'), True
  269. if proto.report_net:
  270. return call('run_once'), False
  271. return None, False
  272. @Printer.register(ExecutionStep)
  273. def print_step(text, step):
  274. proto = step.Proto()
  275. step_ctx, do_substep = _get_step_context(step)
  276. with text.context(step_ctx):
  277. if proto.report_net:
  278. with text.context(call('report_net', [proto.report_interval])):
  279. text(step.get_net(proto.report_net))
  280. substeps = step.Substeps() + [step.get_net(n) for n in proto.network]
  281. for substep in substeps:
  282. sub_proto = (
  283. substep.Proto() if isinstance(substep, ExecutionStep) else None)
  284. if sub_proto is not None and sub_proto.run_every_ms:
  285. substep_ctx = call(
  286. 'reporter',
  287. [str(substep), ('interval_ms', sub_proto.run_every_ms)])
  288. elif do_substep:
  289. title = (
  290. 'workspace'
  291. if sub_proto is not None and sub_proto.create_workspace else
  292. 'step')
  293. substep_ctx = call(title, [str(substep)])
  294. else:
  295. substep_ctx = None
  296. with text.context(substep_ctx):
  297. text(substep)
  298. if proto.should_stop_blob:
  299. text.add(call('yield stop_if', [proto.should_stop_blob]))
  300. def _print_task_output(x):
  301. assert isinstance(x, TaskOutput)
  302. return 'Output[' + ', '.join(str(x) for x in x.names) + ']'
  303. @Printer.register(Task)
  304. def print_task(text, task):
  305. outs = ', '.join(_print_task_output(o) for o in task.outputs())
  306. context = [('node', task.node), ('name', task.name), ('outputs', outs)]
  307. with text.context(call('Task', context)):
  308. text(task.get_step())
  309. @Printer.register(TaskGroup)
  310. def print_task_group(text, tg, header=None):
  311. with text.context(header or call('TaskGroup')):
  312. for task in tg.tasks_by_node().tasks():
  313. text(task)
  314. @Printer.register(Job)
  315. def print_job(text, job):
  316. text(job.init_group, 'Job.current().init_group')
  317. text(job.epoch_group, 'Job.current().epoch_group')
  318. with text.context('Job.current().stop_conditions'):
  319. for out in job.stop_conditions:
  320. text.add(_print_task_output(out))
  321. text(job.download_group, 'Job.current().download_group')
  322. text(job.exit_group, 'Job.current().exit_group')
  323. def to_string(obj, **kwargs):
  324. """
  325. Given a Net, ExecutionStep, Task, TaskGroup or Job, produces a string
  326. with detailed description of the execution steps.
  327. """
  328. printer = Printer(**kwargs)
  329. printer(obj)
  330. return str(printer)
  331. def debug_net(net):
  332. """
  333. Given a Net, produce another net that logs info about the operator call
  334. before each operator execution. Use for debugging purposes.
  335. """
  336. assert isinstance(net, Net)
  337. debug_net = Net(str(net))
  338. assert isinstance(net, Net)
  339. for op in net.Proto().op:
  340. text = Text()
  341. print_op(op, text)
  342. debug_net.LogInfo(str(text))
  343. debug_net.Proto().op.extend([op])
  344. return debug_net