Float16 optimizer for fp16 and bf16 data types. Arguments: optimizer: base optimizer such as Adam or SGD clip_grad: clip gradeints with this global L2 norm. Note that clipping is ignored if clip_grad == 0 log_num_zeros_in_grad: return number of zeros in the g
| 143 | |
| 144 | |
| 145 | class Float16OptimizerWithFloat16Params(MegatronOptimizer): |
| 146 | """Float16 optimizer for fp16 and bf16 data types. |
| 147 | |
| 148 | Arguments: |
| 149 | optimizer: base optimizer such as Adam or SGD |
| 150 | clip_grad: clip gradeints with this global L2 norm. Note |
| 151 | that clipping is ignored if clip_grad == 0 |
| 152 | log_num_zeros_in_grad: return number of zeros in the gradients. |
| 153 | params_have_main_grad: flag indicating if parameters have |
| 154 | a `main_grad` field. If this is set, we are assuming |
| 155 | that the model parameters are store in the `main_grad` |
| 156 | field instead of the typical `grad` field. This happens |
| 157 | for the DDP cases where there is a contihuous buffer |
| 158 | holding the gradients. For example for bfloat16, we want |
| 159 | to do gradient accumulation and all-reduces in float32 |
| 160 | and as a result we store those gradients in the main_grad. |
| 161 | Note that main grad is not necessarily in float32. |
| 162 | bf16: if true, the model is running in bfloat16. |
| 163 | grad_scaler: used for scaling gradients. Note that this can be |
| 164 | None. This case happens when `bf16 = True` and we don't |
| 165 | use any loss scale. Note that for `bf16 = True`, we can have |
| 166 | a constnat gradient scaler. Also for `bf16 = False`, we |
| 167 | always require a grad scaler. |
| 168 | """ |
| 169 | |
| 170 | def __init__( |
| 171 | self, |
| 172 | optimizer, |
| 173 | clip_grad, |
| 174 | log_num_zeros_in_grad, |
| 175 | params_have_main_grad, |
| 176 | bf16, |
| 177 | grad_scaler, |
| 178 | ): |
| 179 | |
| 180 | super(Float16OptimizerWithFloat16Params, self).__init__( |
| 181 | optimizer, clip_grad, log_num_zeros_in_grad, params_have_main_grad |
| 182 | ) |
| 183 | |
| 184 | self.bf16 = bf16 |
| 185 | self.grad_scaler = grad_scaler |
| 186 | # None grad scaler is only supported for bf16. |
| 187 | if self.grad_scaler is None: |
| 188 | assert self.bf16, "fp16 expects a grad scaler." |
| 189 | |
| 190 | # Tensor used to determine if a nan/if has happend. |
| 191 | # Any non-zero value indicates inf/nan. |
| 192 | # Note that we keep this for the cases that grad scaler is none. |
| 193 | # We still record nan/inf if we have a bfloat16 with a grad scaler. |
| 194 | if self.grad_scaler: |
| 195 | self.found_inf = torch.cuda.FloatTensor([0.0]) |
| 196 | |
| 197 | # Dummy tensor needed for apex multi-apply tensor. |
| 198 | # For bfloat, we don't have multi-tensor apply and for now |
| 199 | # we set it to none so the multi-tensor apply gets ignored. |
| 200 | if bf16: |
| 201 | self._dummy_overflow_buf = None |
| 202 | else: |
no outgoing calls
no test coverage detected