Scale certain gradient by a multiplier.
| 219 | |
| 220 | |
| 221 | class 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 |
no outgoing calls
no test coverage detected
searching dependent graphs…