mappings.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. # Copyright (c) Microsoft Corporation.
  2. # SPDX-License-Identifier: Apache-2.0
  3. # DeepSpeed Team
  4. # The file has been adapted from the following Megatron-LM file:
  5. # https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/mpu/mappings.py
  6. # Git commit hash: 9dc3c42a84aa656f583703cf8b6b4f79f712b796
  7. # We retain the following copyright from the original files:
  8. # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
  9. # Licensed under the Apache License, Version 2.0 (the "License");
  10. # you may not use this file except in compliance with the License.
  11. # You may obtain a copy of the License at
  12. #
  13. # http://www.apache.org/licenses/LICENSE-2.0
  14. #
  15. # Unless required by applicable law or agreed to in writing, software
  16. # distributed under the License is distributed on an "AS IS" BASIS,
  17. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. # See the License for the specific language governing permissions and
  19. # limitations under the License.
  20. import torch
  21. import deepspeed
  22. def _gather_tokens(input_, dim=0):
  23. """Gather tensors and concatenate them along a dimension"""
  24. mpu = deepspeed.utils.groups.mpu
  25. input_ = input_.contiguous()
  26. # Size and dimension.
  27. rank = mpu.get_tensor_model_parallel_rank()
  28. tensor_list = [torch.empty_like(input_) for _ in range(mpu.get_tensor_model_parallel_world_size())]
  29. tensor_list[rank] = input_
  30. deepspeed.comm.all_gather(tensor_list, input_, group=mpu.get_tensor_model_parallel_group())
  31. # Note: torch.cat already creates a contiguous tensor.
  32. output = torch.cat(tensor_list, dim=dim).contiguous()
  33. return output
  34. def _drop_tokens(input_, dim=0):
  35. """Divide a tensor among the tensor parallel ranks"""
  36. mpu = deepspeed.utils.groups.mpu
  37. total_chunks = mpu.get_tensor_model_parallel_world_size()
  38. this_chunk = mpu.get_tensor_model_parallel_rank()
  39. assert input_.shape[
  40. dim] % total_chunks == 0, f"input dimension {dim} ({input_.shape[dim]}) is not divisible by tensor parallel world size ({total_chunks})"
  41. chunk_size = input_.shape[dim] // total_chunks
  42. return torch.narrow(input_, dim, this_chunk * chunk_size, chunk_size)
  43. class _GatherTokens(torch.autograd.Function):
  44. """All gather tokens among the tensor parallel ranks"""
  45. @staticmethod
  46. def symbolic(graph, input_, dim):
  47. return _gather_tokens(input_, dim)
  48. @staticmethod
  49. def forward(ctx, input_, dim):
  50. ctx.dim = dim
  51. return _gather_tokens(input_, dim)
  52. @staticmethod
  53. def backward(ctx, grad_output):
  54. return _drop_tokens(grad_output, ctx.dim), None
  55. class _DropTokens(torch.autograd.Function):
  56. "Divide tokens equally among the tensor parallel ranks"
  57. @staticmethod
  58. def symbolic(graph, input_, dim):
  59. return _drop_tokens(input_, dim)
  60. @staticmethod
  61. def forward(ctx, input_, dim):
  62. ctx.dim = dim
  63. return _drop_tokens(input_, dim)
  64. @staticmethod
  65. def backward(ctx, input_):
  66. return _gather_tokens(input_, ctx.dim), None
  67. def gather_tokens(input_, dim=0):
  68. mpu = deepspeed.utils.groups.mpu
  69. if mpu is None or mpu.get_tensor_model_parallel_world_size() == 1:
  70. # no tensor parallelism for non-experts
  71. return input_
  72. return _GatherTokens.apply(input_, dim)
  73. def drop_tokens(input_, dim=0):
  74. mpu = deepspeed.utils.groups.mpu
  75. if mpu is None or mpu.get_tensor_model_parallel_world_size() == 1:
  76. # no tensor parallelism for non-experts
  77. return input_
  78. return _DropTokens.apply(input_, dim)