|
12 | 12 |
|
13 | 13 | import numpy as np
|
14 | 14 | import torch
|
| 15 | +from typing import Union, Iterable |
15 | 16 |
|
16 | 17 | LOGGER = logging.getLogger(__name__)
|
17 | 18 |
|
@@ -72,3 +73,64 @@ def apply_mask(hidden_states, masks):
|
72 | 73 | hidden_dim = hidden_states.shape[-1]
|
73 | 74 | hidden_states.view(-1, hidden_dim)[~masks.view(-1).type(torch.ByteTensor), :] = 0
|
74 | 75 | return hidden_states
|
| 76 | + |
| 77 | + |
| 78 | +def clip_grad_norm_( |
| 79 | + parameters: Union[torch.Tensor, Iterable[torch.Tensor]], |
| 80 | + max_norm: float, |
| 81 | + norm_type: float = 2.0, |
| 82 | + error_if_nonfinite: bool = False, |
| 83 | +) -> torch.Tensor: |
| 84 | + r""" |
| 85 | + Implementation of torch.nn.utils.clip_grad_norm_ in torch==1.13 |
| 86 | + This is to support sparse gradient with gradient clipping. |
| 87 | + REF: https://pytorch.org/docs/1.13/_modules/torch/nn/utils/clip_grad.html#clip_grad_norm_ |
| 88 | +
|
| 89 | + Clips gradient norm of an iterable of parameters. |
| 90 | +
|
| 91 | + The norm is computed over all gradients together, as if they were |
| 92 | + concatenated into a single vector. Gradients are modified in-place. |
| 93 | +
|
| 94 | + Args: |
| 95 | + parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a |
| 96 | + single Tensor that will have gradients normalized |
| 97 | + max_norm (float or int): max norm of the gradients |
| 98 | + norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for |
| 99 | + infinity norm. |
| 100 | + error_if_nonfinite (bool): if True, an error is thrown if the total |
| 101 | + norm of the gradients from :attr:`parameters` is ``nan``, |
| 102 | + ``inf``, or ``-inf``. Default: False (will switch to True in the future) |
| 103 | +
|
| 104 | + Returns: |
| 105 | + Total norm of the parameter gradients (viewed as a single vector). |
| 106 | + """ |
| 107 | + if isinstance(parameters, torch.Tensor): |
| 108 | + parameters = [parameters] |
| 109 | + grads = [p.grad for p in parameters if p.grad is not None] |
| 110 | + max_norm = float(max_norm) |
| 111 | + norm_type = float(norm_type) |
| 112 | + if len(grads) == 0: |
| 113 | + return torch.tensor(0.0) |
| 114 | + device = grads[0].device |
| 115 | + if norm_type == "inf": |
| 116 | + norms = [g.detach().abs().max().to(device) for g in grads] |
| 117 | + total_norm = norms[0] if len(norms) == 1 else torch.max(torch.stack(norms)) |
| 118 | + else: |
| 119 | + total_norm = torch.norm( |
| 120 | + torch.stack([torch.norm(g.detach(), norm_type).to(device) for g in grads]), norm_type |
| 121 | + ) |
| 122 | + if error_if_nonfinite and torch.logical_or(total_norm.isnan(), total_norm.isinf()): |
| 123 | + raise RuntimeError( |
| 124 | + f"The total norm of order {norm_type} for gradients from " |
| 125 | + "`parameters` is non-finite, so it cannot be clipped. To disable " |
| 126 | + "this error and scale the gradients by the non-finite norm anyway, " |
| 127 | + "set `error_if_nonfinite=False`" |
| 128 | + ) |
| 129 | + clip_coef = max_norm / (total_norm + 1e-6) |
| 130 | + # Note: multiplying by the clamped coef is redundant when the coef is clamped to 1, but doing so |
| 131 | + # avoids a `if clip_coef < 1:` conditional which can require a CPU <=> device synchronization |
| 132 | + # when the gradients do not reside in CPU memory. |
| 133 | + clip_coef_clamped = torch.clamp(clip_coef, max=1.0) |
| 134 | + for g in grads: |
| 135 | + g.detach().mul_(clip_coef_clamped.to(g.device)) |
| 136 | + return total_norm |
0 commit comments