You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

clip_grad.py 2.6 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # pylint: disable=redefined-builtin
  10. from typing import Iterable, Union
  11. from ..core._imperative_rt.core2 import pop_scope, push_scope
  12. from ..functional import clip, concat, minimum, norm
  13. from ..tensor import Tensor
  14. __all__ = ["clip_grad_norm", "clip_grad_value"]
  15. def clip_grad_norm(
  16. tensors: Union[Tensor, Iterable[Tensor]], max_norm: float, ord: float = 2.0,
  17. ):
  18. r"""Clips gradient norm of an iterable of parameters.
  19. The norm is computed over all gradients together, as if they were
  20. concatenated into a single vector. Gradients are modified in-place.
  21. Args:
  22. tensors: an iterable of Tensors or a single Tensor.
  23. max_norm: max norm of the gradients.
  24. ord: type of the used p-norm. Can be ``'inf'`` for infinity norm.
  25. Returns:
  26. total norm of the parameters (viewed as a single vector).
  27. """
  28. push_scope("clip_grad_norm")
  29. if isinstance(tensors, Tensor):
  30. tensors = [tensors]
  31. tensors = [t for t in tensors if t.grad is not None]
  32. if len(tensors) == 0:
  33. pop_scope("clip_grad_norm")
  34. return Tensor(0.0)
  35. norm_ = [norm(t.grad.flatten(), ord=ord) for t in tensors]
  36. if len(norm_) > 1:
  37. norm_ = norm(concat(norm_), ord=ord)
  38. else:
  39. norm_ = norm_[0]
  40. scale = max_norm / (norm_ + 1e-6)
  41. scale = minimum(scale, 1)
  42. for tensor in tensors:
  43. tensor.grad._reset(tensor.grad * scale)
  44. pop_scope("clip_grad_norm")
  45. return norm_
  46. def clip_grad_value(
  47. tensors: Union[Tensor, Iterable[Tensor]], lower: float, upper: float
  48. ):
  49. r"""Clips gradient of an iterable of parameters to a specified lower and
  50. upper. Gradients are modified in-place.
  51. The gradients are clipped in the range:
  52. .. math:: \left[\text{lower}, \text{upper}\right]
  53. Args:
  54. tensors: an iterable of Tensors or a single Tensor.
  55. lower: minimum allowed value of the gradients.
  56. upper: maximum allowed value of the gradients.
  57. """
  58. push_scope("clip_grad_value")
  59. if isinstance(tensors, Tensor):
  60. tensors = [tensors]
  61. for tensor in tensors:
  62. if tensor.grad is None:
  63. continue
  64. tensor.grad._reset(clip(tensor.grad, lower, upper))
  65. pop_scope("clip_grad_value")