utils.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # coding=utf-8
  2. # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Utilities for models."""
  16. import math
  17. import torch
  18. from megatron import get_args
  19. def init_method_normal(sigma):
  20. """Init method based on N(0, sigma)."""
  21. def init_(tensor):
  22. return torch.nn.init.normal_(tensor, mean=0.0, std=sigma)
  23. return init_
  24. def scaled_init_method_normal(sigma, num_layers):
  25. """Init method based on N(0, sigma/sqrt(2*num_layers)."""
  26. std = sigma / math.sqrt(2.0 * num_layers)
  27. def init_(tensor):
  28. return torch.nn.init.normal_(tensor, mean=0.0, std=std)
  29. return init_
  30. def attention_mask_func(attention_scores, attention_mask):
  31. attention_scores.masked_fill_(attention_mask, -10000.0)
  32. return attention_scores
  33. def get_linear_layer(rows, columns, init_method):
  34. """Simple linear layer with weight initialization."""
  35. layer = torch.nn.Linear(rows, columns)
  36. init_method(layer.weight)
  37. with torch.no_grad():
  38. layer.bias.zero_()
  39. return layer
  40. @torch.jit.script
  41. def gelu_impl(x):
  42. """OpenAI's gelu implementation."""
  43. return 0.5 * x * (1.0 + torch.tanh(0.7978845608028654 * x *
  44. (1.0 + 0.044715 * x * x)))
  45. def openai_gelu(x):
  46. return gelu_impl(x)
  47. #This is actually Python equivalent of torch.nn.functional.gelu(), also with type hints for ONNX exporter
  48. @torch.jit.script
  49. def erf_gelu(x):
  50. return x * 0.5 * (torch.erf(x / 1.41421).to(dtype=x.dtype)+torch.ones_like(x).to(dtype=x.dtype))