model_helper.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. ## @package model_helper
  2. # Module caffe2.python.model_helper
  3. from caffe2.python import core, scope, workspace
  4. from caffe2.python.helpers.db_input import db_input
  5. from caffe2.python.modeling import parameter_info
  6. from caffe2.python.modeling.parameter_sharing import (
  7. parameter_sharing_context,
  8. )
  9. from caffe2.python.optimizer_context import (
  10. OptimizerContext,
  11. DEFAULT_OPTIM,
  12. )
  13. from caffe2.python.regularizer_context import RegularizerContext
  14. from future.utils import viewitems, viewkeys
  15. from itertools import chain
  16. import logging
  17. # _known_working_ops are operators that do not need special care.
  18. _known_working_ops = [
  19. "Accuracy",
  20. "Adam",
  21. "Add",
  22. "Adagrad",
  23. "SparseAdagrad",
  24. "Adadelta",
  25. "SparseAdadelta",
  26. "AveragedLoss",
  27. "Cast",
  28. "Checkpoint",
  29. "ConstantFill",
  30. "Copy",
  31. "CopyGPUToCPU",
  32. "CopyCPUToGPU",
  33. "DequeueBlobs",
  34. "EnsureCPUOutput",
  35. "ExpandDims",
  36. "Flatten",
  37. "FlattenToVec",
  38. "LabelCrossEntropy",
  39. "LearningRate",
  40. "MakeTwoClass",
  41. "MatMul",
  42. "NCCLAllreduce",
  43. "NHWC2NCHW",
  44. "PackSegments",
  45. "Print",
  46. "PRelu",
  47. "ReduceFrontSum",
  48. "Scale",
  49. "ScatterWeightedSum",
  50. "Sigmoid",
  51. "SortedSegmentSum",
  52. "Snapshot", # Note: snapshot is deprecated, use Checkpoint
  53. "Softmax",
  54. "SoftmaxWithLoss",
  55. "SquaredL2Distance",
  56. "Squeeze",
  57. "StopGradient",
  58. "Summarize",
  59. "Tanh",
  60. "Transpose",
  61. "UnpackSegments",
  62. "WeightedSum",
  63. "YellowFin"
  64. ]
  65. class ModelHelper(object):
  66. """A helper model so we can manange models more easily. It contains net def
  67. and parameter storages. You can add an Operator yourself, e.g.
  68. model = model_helper.ModelHelper(name="train_net")
  69. # init your weight and bias as w and b
  70. w = model.param_init_net.XavierFill(...)
  71. b = model.param_init_net.ConstantFill(...)
  72. fc1 = model.FC([input, w, b], output, **kwargs)
  73. or you can use helper functions in brew module without manually
  74. defining parameter initializations and operators.
  75. model = model_helper.ModelHelper(name="train_net")
  76. fc1 = brew.fc(model, input, output, dim_in, dim_out, **kwargs)
  77. """
  78. def __init__(self, name=None, init_params=True, allow_not_known_ops=True,
  79. skip_sparse_optim=False, param_model=None, arg_scope=None):
  80. self.name = name or "model"
  81. self.net = core.Net(self.name)
  82. if param_model is not None:
  83. self.param_init_net = param_model.param_init_net
  84. self.param_to_grad = param_model.param_to_grad
  85. self.params = param_model.params
  86. self._parameters_info = param_model._parameters_info
  87. self._computed_params = param_model._computed_params
  88. else:
  89. self.param_init_net = core.Net(self.name + '_init')
  90. self.param_to_grad = {}
  91. self.params = []
  92. self._parameters_info = {}
  93. self._computed_params = []
  94. self._param_info_deprecated = []
  95. self._devices = []
  96. self.gradient_ops_added = False
  97. self.init_params = init_params
  98. self.allow_not_known_ops = allow_not_known_ops
  99. self.skip_sparse_optim = skip_sparse_optim
  100. self.weights = []
  101. self.biases = []
  102. self._arg_scope = {
  103. 'order': "NCHW",
  104. 'use_cudnn': True,
  105. 'cudnn_exhaustive_search': False,
  106. }
  107. if arg_scope is not None:
  108. # Please notice value as None is not acceptable. We are not checking it
  109. # here because we already have check in MakeArgument.
  110. self._arg_scope.update(arg_scope)
  111. @property
  112. def arg_scope(self):
  113. return self._arg_scope
  114. def get_name(self):
  115. return self.name
  116. def _infer_param_shape(self, param):
  117. for op in self.param_init_net.Proto().op:
  118. if str(param) in op.output:
  119. for arg in op.arg:
  120. if arg.name == "shape":
  121. return list(arg.ints)
  122. return None
  123. def _update_param_info_deprecated(self):
  124. assert len(self._param_info_deprecated) <= len(self.params)
  125. for param in self.params[len(self._param_info_deprecated):]:
  126. if not isinstance(param, core.BlobReference):
  127. raise ValueError(
  128. "Param %s must be a BlobReference!" % str(param))
  129. self._param_info_deprecated.append(parameter_info.ParameterInfo(
  130. param_id=len(self._param_info_deprecated),
  131. param=param,
  132. shape=self._infer_param_shape(param)))
  133. for info in self._param_info_deprecated:
  134. info.grad = self.param_to_grad.get(info.name)
  135. def _normalize_tags(self, tags):
  136. tags = tags or []
  137. return set(tags) if isinstance(tags, list) else set([tags])
  138. def create_param(self, param_name, shape, initializer, tags=None):
  139. """
  140. Creates parameter with a given name and initializer.
  141. If param_name is instance of BlobRefernce - then this blob will be used
  142. to store parameter (no any logic will affect it's location).
  143. If param_name is instance of a string type, then the final blob will
  144. be created in the CurrentNameScope with the respect of all parameter
  145. sharing logic, i.e. 'resolved_name_scope/param_name'.
  146. Parameter sharing logic is going to override CurrentNameScope according
  147. to the rules that are specified through ParameterSharing contexts,
  148. all ParameterSharing contexts are applied recursively until there are no
  149. extra overrides present, where on each step the best match will be
  150. applied first.
  151. The following examples should clarify the way ParameterSharing logic
  152. works:
  153. As an example if this function is called with parameter 'w':
  154. a. Call from some scope 'global_scope' with no Parameter sharing:
  155. 'global_scope/w'
  156. b. Call from scope 'scope_b', with override {'scope_b': 'scope_a'}:
  157. 'scope_a/w'
  158. c. Call from scope 'scope_a', with override {'scope_a': ''}:
  159. 'scope_a/w'
  160. d. Call from scope 'scope_b/shared', with overrides
  161. {'scope_b/shared': 'scope_b', 'scope_b': 'scope_a'}:
  162. 'scope_a/w'
  163. d. Call from scope 'scope_b/unshared', with overrides
  164. {'scope_b/shared': 'scope_b', 'scope_b': 'scope_a'}:
  165. 'scope_a/unshared/w'
  166. """
  167. # ParameterSharing works only for case when param_name is instance of
  168. # a string type. If param_name is a BlobReference - no attempt for
  169. # ParameterSharing will be applied.
  170. if isinstance(param_name, core.BlobReference):
  171. param_name = str(param_name)
  172. elif isinstance(param_name, str):
  173. # Parameter name will be equal to current Namescope that got
  174. # resolved with the respect of parameter sharing of the scopes.
  175. param_name = parameter_sharing_context.get_parameter_name(
  176. param_name)
  177. else:
  178. raise TypeError("Unsupported type for param_name")
  179. if param_name in self._parameters_info:
  180. assert self._parameters_info[param_name].shape == shape
  181. return self._parameters_info[param_name].blob
  182. param_info = initializer.create_param(
  183. param_name=core.BlobReference(param_name),
  184. init_net=self.param_init_net,
  185. shape=shape,
  186. )
  187. optim_context = OptimizerContext.current()
  188. for tag in self._normalize_tags(tags):
  189. if optim_context.has_optimizer(tag):
  190. # param_info will check optimizer has not been set
  191. param_info.optimizer = optim_context.get_optimizer(tag)
  192. if not param_info.optimizer and optim_context.has_optimizer(DEFAULT_OPTIM):
  193. param_info.optimizer = optim_context.get_optimizer(DEFAULT_OPTIM)
  194. reg_context = RegularizerContext.current()
  195. param_info.regularizer = reg_context
  196. self._parameters_info[param_name] = param_info
  197. # Add param to legacy structs as well, so all other functions for
  198. # parameters are still working.
  199. self.AddParameter(param_info.blob, tags)
  200. return param_info.blob
  201. def get_param_info(self, param):
  202. assert isinstance(param, core.BlobReference), \
  203. "Param {} is not a BlobReference".format(param)
  204. return self._parameters_info.get(param, None)
  205. # This method is deprecated, use create_param method which
  206. # also does parameter initialization when needed
  207. def add_param_DEPRECATED(self, param, key=None, shape=None, length=None):
  208. logging.warning("add_param method is DEPRECATED")
  209. self._update_param_info_deprecated()
  210. self.AddParameter(param)
  211. if key is not None and self.net.input_record() is not None:
  212. idx = self.net.input_record().field_blobs().index(key)
  213. key = self.net.input_record().field_names()[idx]
  214. shape = shape if shape is not None else self._infer_param_shape(param)
  215. if not isinstance(param, core.BlobReference):
  216. raise ValueError("Param %s must be a BlobReference!" % str(param))
  217. self._param_info_deprecated.append(parameter_info.ParameterInfo(
  218. param_id=len(self._param_info_deprecated),
  219. param=param,
  220. shape=shape,
  221. key=key,
  222. length=length,
  223. ))
  224. return self._param_info_deprecated[-1]
  225. def AddParameter(self, param, tags=None):
  226. assert isinstance(param, core.BlobReference)
  227. tags = self._normalize_tags(tags)
  228. if parameter_info.ParameterTags.COMPUTED_PARAM in tags:
  229. self._computed_params.append(param)
  230. else:
  231. self.params.append(param)
  232. if parameter_info.ParameterTags.WEIGHT in tags:
  233. self.weights.append(param)
  234. if parameter_info.ParameterTags.BIAS in tags:
  235. self.biases.append(param)
  236. @staticmethod
  237. def _NormalizeNamescope(namescope):
  238. if namescope is None:
  239. return scope.CurrentNameScope()
  240. elif namescope == '' or namescope.endswith(scope._NAMESCOPE_SEPARATOR):
  241. return namescope
  242. else:
  243. return namescope + scope._NAMESCOPE_SEPARATOR
  244. def GetParams(self, namescope=None, top_scope=False):
  245. '''
  246. Returns the params in current namescope
  247. '''
  248. namescope = ModelHelper._NormalizeNamescope(namescope)
  249. if namescope == '':
  250. return self.params[:]
  251. else:
  252. return [p for p in self.params if
  253. p.GetNameScope().startswith(namescope)]
  254. def Proto(self):
  255. return self.net.Proto()
  256. def InitProto(self):
  257. return self.param_init_net.Proto()
  258. def RunAllOnGPU(self, *args, **kwargs):
  259. self.param_init_net.RunAllOnGPU(*args, **kwargs)
  260. self.net.RunAllOnGPU(*args, **kwargs)
  261. def CreateDB(self, blob_out, db, db_type, **kwargs):
  262. dbreader = self.param_init_net.CreateDB(
  263. [], blob_out, db=db, db_type=db_type, **kwargs)
  264. return dbreader
  265. def AddGradientOperators(self, *args, **kwargs):
  266. if self.gradient_ops_added:
  267. raise RuntimeError("You cannot run AddGradientOperators twice.")
  268. self.Validate()
  269. self.gradient_ops_added = True
  270. self.grad_map = self.net.AddGradientOperators(*args, **kwargs)
  271. self.param_to_grad = self.get_param_to_grad(self.params)
  272. # Populate ParameterInfo for all parameters if missing
  273. # and add gradient blob information. So optimizers can use it
  274. for param, grad in self.param_to_grad.items():
  275. param_info = self.get_param_info(param)
  276. if param_info:
  277. param_info.grad = grad
  278. else:
  279. self._parameters_info[param] = parameter_info.ParameterInfo(
  280. param_id=None,
  281. param=param,
  282. grad=grad,
  283. )
  284. return self.grad_map
  285. def get_param_to_grad(self, params):
  286. '''
  287. Given a list of parameters returns a dict from a parameter
  288. to a corresponding gradient
  289. '''
  290. param_to_grad = {}
  291. if not self.gradient_ops_added:
  292. raise RuntimeError("You need to run AddGradientOperators first.")
  293. # We need to use empty namescope when creating the gradients
  294. # to prevent duplicating the namescope prefix for gradient blobs.
  295. for p in params:
  296. if str(p) in self.grad_map:
  297. param_to_grad[p] = self.grad_map[str(p)]
  298. return param_to_grad
  299. def GetOptimizationParamInfo(self, params=None):
  300. '''
  301. Returns a map for param => grad.
  302. If params is not specified, all parameters will be considered.
  303. '''
  304. if not self.gradient_ops_added:
  305. raise RuntimeError("Need to call AddGradientOperators first")
  306. param_to_grad = self.param_to_grad
  307. if params:
  308. param_to_grad = self.get_param_to_grad(params)
  309. return [
  310. self.get_param_info(param) for param, grad in viewitems(param_to_grad)
  311. if (
  312. not self.skip_sparse_optim or
  313. not isinstance(grad, core.GradientSlice)
  314. )
  315. ]
  316. def _Validate(self):
  317. '''
  318. Check for duplicate params
  319. '''
  320. params_list = [str(p) for p in self.params]
  321. params_set = set(params_list)
  322. dupes = []
  323. if len(params_set) != len(params_list):
  324. params_list = sorted(params_list)
  325. for j, p in enumerate(params_list):
  326. if j > 0 and params_list[j - 1] == p:
  327. if p not in dupes:
  328. dupes.append(p)
  329. return dupes
  330. def Validate(self):
  331. dupes = self._Validate()
  332. assert dupes == [], "Duplicate params: {}".format(dupes)
  333. def GetComputedParams(self, namescope=None):
  334. '''
  335. Returns the computed params in current namescope. 'Computed params'
  336. are such parameters that are not optimized via gradient descent but are
  337. directly computed from data, such as the running mean and variance
  338. of Spatial Batch Normalization.
  339. '''
  340. namescope = ModelHelper._NormalizeNamescope(namescope)
  341. if namescope == '':
  342. return self._computed_params[:]
  343. else:
  344. return [p for p in self._computed_params
  345. if p.GetNameScope().startswith(namescope)]
  346. def GetAllParams(self, namescope=None):
  347. return self.GetParams(namescope) + self.GetComputedParams(namescope)
  348. def TensorProtosDBInput(
  349. self, unused_blob_in, blob_out, batch_size, db, db_type, **kwargs
  350. ):
  351. """TensorProtosDBInput."""
  352. assert len(unused_blob_in) == 0, \
  353. """You cannot pass reader to model_helper.TensorProtosDBInput.
  354. Use model.net.TensorProtosDBInput instead to create the op."""
  355. return db_input(
  356. self, blob_out, batch_size, db, db_type, **kwargs)
  357. def GetDevices(self):
  358. assert len(self._devices) > 0, \
  359. "Use data_parallel_model to run model on multiple GPUs."
  360. return self._devices
  361. def __getattr__(self, op_type):
  362. """Catch-all for all other operators, mostly those without params."""
  363. if op_type.startswith('__'):
  364. raise AttributeError(op_type)
  365. if not core.IsOperator(op_type):
  366. raise AttributeError(
  367. 'Method ' + op_type + ' is not a registered operator.' +
  368. ' Did you mean: [' +
  369. ','.join(workspace.C.nearby_opnames(op_type)) + ']'
  370. )
  371. if op_type not in _known_working_ops:
  372. if not self.allow_not_known_ops:
  373. raise AttributeError(
  374. "Operator {} is not known to be safe".format(op_type))
  375. logging.warning("You are creating an op that the ModelHelper "
  376. "does not recognize: {}.".format(op_type))
  377. return self.net.__getattr__(op_type)
  378. def __dir__(self):
  379. return sorted(set(chain(
  380. dir(type(self)),
  381. viewkeys(self.__dict__),
  382. _known_working_ops
  383. )))
  384. def GetCompleteNet(self):
  385. r""" Return param_init_net + net Net.
  386. Returns:
  387. 'core.Net' containing param_init_net and net
  388. """
  389. new_net = self.param_init_net.Clone(
  390. self.name + "_complete_net", keep_schema=True)
  391. # add init net info to debug info
  392. for op in new_net.Proto().op:
  393. op.debug_info = op.debug_info + "/param_init_net"
  394. new_net.AppendNet(self.net)
  395. # keep the execution optimization
  396. if self.net.Proto().HasField("type"):
  397. new_net.Proto().type = self.net.Proto().type
  398. return new_net
  399. def ConstructInitTrainNetfromNet(self, net):
  400. r""" construct init net and train net from complete_net
  401. Inputs:
  402. net: 'core.Net' containing param_init_net and train net
  403. """
  404. param_op_mask = []
  405. train_op_mask = []
  406. for idx, op in enumerate(net.Proto().op):
  407. if op.debug_info.endswith("/param_init_net"):
  408. param_op_mask.append(idx)
  409. else:
  410. train_op_mask.append(idx)
  411. self.param_init_net = net.Clone(
  412. net.Name() + "/generated_param_init_net",
  413. keep_schema=True,
  414. op_id_mask=param_op_mask,
  415. update_external_list=True,
  416. )
  417. self.net = net.Clone(
  418. net.Name() + "/generated_net",
  419. keep_schema=True,
  420. op_id_mask=train_op_mask,
  421. update_external_list=True,
  422. )
  423. def ExtractPredictorNet(
  424. net_proto,
  425. input_blobs,
  426. output_blobs,
  427. device=None,
  428. renames=None,
  429. disabled_inputs=None,
  430. ):
  431. '''
  432. Takes a model net for training and returns a net which can be
  433. used for prediction. For example, all gradient operators and
  434. input operators are removed.
  435. @param net_proto protobuf of the net you want to process (net.Proto())
  436. @param input_blobs list/set of blob names that are the inputs of predictor
  437. @param output_blobs list/set of blob names that are outputs of predictor
  438. @param device optional device option that is assigned
  439. @param renames dictionary of blob name to a new name (optional)
  440. @param disabled_inputs optional set of blobs that are 'switched off'. This
  441. will cause branches with those blobs as inputs to be removed
  442. '''
  443. predict_net = core.Net(net_proto.name + "_predict")
  444. predict_proto = predict_net.Proto()
  445. orig_external_inputs = set(net_proto.external_input)
  446. orig_external_outputs = set(net_proto.external_output)
  447. input_blobs = {str(b) for b in input_blobs}
  448. known_blobs = set(orig_external_inputs).union(input_blobs)
  449. output_blobs = {str(b) for b in output_blobs}
  450. external_inputs = set(input_blobs)
  451. external_outputs = set(output_blobs)
  452. if renames is None:
  453. renames = {}
  454. if disabled_inputs is not None:
  455. known_blobs = known_blobs - set(disabled_inputs)
  456. ops = list(net_proto.op)
  457. # Find the range of ops that we should include
  458. try:
  459. first_op_with_input = min(
  460. [
  461. j for j in range(len(ops))
  462. if input_blobs.intersection(ops[j].input) and ops[j].type !=
  463. 'StopGradient'
  464. ]
  465. )
  466. except ValueError:
  467. raise Exception("No ops with input={}".format(input_blobs))
  468. try:
  469. last_op_with_output = max(
  470. [
  471. j for j in range(len(ops))
  472. if output_blobs.intersection(ops[j].output)
  473. ]
  474. )
  475. except ValueError:
  476. raise Exception("No ops with output={}".format(output_blobs))
  477. def validate_op(op):
  478. # Check that the op does not have is_test = 0 set. This is a common
  479. # pitfall with SpatialBN op, at lest.
  480. for arg in op.arg:
  481. if arg.name == "is_test" and arg.i == 0:
  482. raise Exception(
  483. "An operator had is_test=0, did you try to extract a " +
  484. "predictor from a train model (instead of test model)?" +
  485. " Op was: {}".format(str(op))
  486. )
  487. def rename_list(proto_list):
  488. # proto lists don't support assignments
  489. new_list = proto_list[:]
  490. for j, b in enumerate(new_list):
  491. if b in renames:
  492. new_list[j] = renames[b]
  493. del proto_list[:]
  494. proto_list.extend(new_list)
  495. # Iterate through the ops and only include those whose inputs
  496. # we can satisfy.
  497. for op in ops[first_op_with_input:(last_op_with_output + 1)]:
  498. if known_blobs.issuperset(op.input):
  499. # Special handling for recurrent nets
  500. # TODO: when standard argument type for "nets" is introduced,
  501. # this can be more general
  502. if op.type == 'RecurrentNetwork':
  503. for arg in op.arg:
  504. if arg.name == 'backward_step_net':
  505. arg.ClearField(str('n'))
  506. elif arg.name == 'step_net':
  507. for step_op in arg.n.op:
  508. rename_list(step_op.input)
  509. rename_list(step_op.output)
  510. if device is not None:
  511. step_op.device_option.device_type = device.device_type
  512. step_op.device_option.device_id = device.device_id
  513. rename_list(arg.n.external_input)
  514. rename_list(arg.n.external_output)
  515. # Add additional external inputs
  516. external_inputs.update(
  517. set(arg.n.external_input).intersection(
  518. orig_external_inputs
  519. )
  520. )
  521. if device is not None:
  522. op.device_option.device_type = device.device_type
  523. op.device_option.device_id = device.device_id
  524. validate_op(op)
  525. predict_proto.op.extend([op])
  526. known_blobs.update(op.output)
  527. external_inputs.update(
  528. set(op.input).intersection(orig_external_inputs)
  529. )
  530. external_outputs.update(
  531. set(op.output).intersection(orig_external_outputs)
  532. )
  533. else:
  534. logging.debug(
  535. "Op {} had unknown inputs: {}".format(
  536. op.type, set(op.input).difference(known_blobs)
  537. )
  538. )
  539. # Predictor net's external inputs and outputs include only those
  540. # that are part of this net.
  541. predict_proto.external_input.extend(external_inputs)
  542. predict_proto.external_output.extend(external_outputs)
  543. rename_list(predict_proto.external_input)
  544. rename_list(predict_proto.external_output)
  545. renamed_input_blobs = []
  546. for b in input_blobs:
  547. if b in renames:
  548. renamed_input_blobs.append(renames[b])
  549. else:
  550. renamed_input_blobs.append(b)
  551. for op in predict_proto.op:
  552. rename_list(op.input)
  553. rename_list(op.output)
  554. return predict_net, list(
  555. set(predict_proto.external_input) - set(renamed_input_blobs)
  556. )