MCPcopy Index your code
hub / github.com/tensorpack/tensorpack / ScaleGradient

Class ScaleGradient

tensorpack/tfutils/gradproc.py:221–264  ·  view source on GitHub ↗

Scale certain gradient by a multiplier.

Source from the content-addressed store, hash-verified

219
220
221class ScaleGradient(MapGradient):
222 """
223 Scale certain gradient by a multiplier.
224 """
225
226 def __init__(self, multipliers, verbose=True):
227 """
228 Args:
229 multipliers (tuple or list): tuple of (regex, float), or list of such tuples.
230 verbose (bool): whether to print logs or not
231
232 Example:
233 Use double learning rate for all the bias (as in caffe), and freeze layer0:
234
235 .. code-block:: python
236
237 from tensorpack.tfutils import optimizer, gradproc
238 opt = optimizer.apply_grad_processors(
239 opt, [gradproc.ScaleGradient(
240 [('.*/b', 2.), ('layer0/.*', 0.)]
241 )])
242 """
243 if not isinstance(multipliers, list):
244 multipliers = [multipliers]
245 self.multipliers = multipliers
246 assert verbose in [True, False], verbose
247 self._verbose = verbose
248 super(ScaleGradient, self).__init__(self._mapper)
249
250 def _mapper(self, grad, var):
251 varname = var.op.name
252 for regex, val in self.multipliers:
253 # always match against the whole name
254 if not regex.endswith('$'):
255 regex = regex + '$'
256
257 if re.match(regex, varname):
258 if self._verbose:
259 logger.info("Gradient of '{}' is multipled by {}".format(varname, val))
260 if val != 0: # skip zero to speed up
261 return grad * val
262 else:
263 return None
264 return grad

Callers 1

buildMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…