vocab_parallel_embedding.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. from typing import Optional, Sequence
  2. import torch
  3. from torch.nn.parameter import Parameter
  4. from aphrodite.modeling.layers.linear import UnquantizedLinearMethod
  5. from aphrodite.modeling.megatron.parallel_state import (
  6. get_tensor_model_parallel_rank,
  7. get_tensor_model_parallel_world_size,
  8. )
  9. from aphrodite.modeling.megatron.utils import divide
  10. from aphrodite.modeling.megatron.communication_op import (
  11. tensor_model_parallel_all_reduce)
  12. from aphrodite.modeling.utils import set_weight_attrs
  13. DEFAULT_VOCAB_PADDING_SIZE = 64
  14. def pad_vocab_size(vocab_size: int,
  15. pad_to: int = DEFAULT_VOCAB_PADDING_SIZE) -> int:
  16. """Pad the vocab size to the given value."""
  17. return ((vocab_size + pad_to - 1) // pad_to) * pad_to
  18. def vocab_range_from_per_partition_vocab_size(per_partition_vocab_size: int,
  19. rank: int) -> Sequence[int]:
  20. index_f = rank * per_partition_vocab_size
  21. index_l = index_f + per_partition_vocab_size
  22. return index_f, index_l
  23. def vocab_range_from_global_vocab_size(global_vocab_size: int, rank: int,
  24. world_size: int) -> Sequence[int]:
  25. per_partition_vocab_size = divide(global_vocab_size, world_size)
  26. return vocab_range_from_per_partition_vocab_size(per_partition_vocab_size,
  27. rank)
  28. class VocabParallelEmbedding(torch.nn.Module):
  29. """Embedding parallelized in the vocabulary dimension.
  30. Adapted from torch.nn.Embedding, note that we pad the vocabulary size to
  31. make sure it is divisible by the number of model parallel GPUs.
  32. Args:
  33. num_embeddings: vocabulary size.
  34. embedding_dim: size of hidden state.
  35. params_dtype: type of the parameters.
  36. org_num_embeddings: original vocabulary size (without LoRA).
  37. padding_size: padding size for the vocabulary.
  38. """
  39. def __init__(self,
  40. num_embeddings: int,
  41. embedding_dim: int,
  42. params_dtype: Optional[torch.dtype] = None,
  43. linear_method=None,
  44. org_num_embeddings: Optional[int] = None,
  45. padding_size: int = DEFAULT_VOCAB_PADDING_SIZE,
  46. is_input_emb: bool = True):
  47. super().__init__()
  48. # Keep the input dimensions.
  49. self.num_embeddings = num_embeddings
  50. self.org_vocab_size = org_num_embeddings or num_embeddings
  51. self.num_embeddings_padded = pad_vocab_size(num_embeddings,
  52. padding_size)
  53. self.embedding_dim = embedding_dim
  54. if params_dtype is None:
  55. params_dtype = torch.get_default_dtype()
  56. self.tp_size = get_tensor_model_parallel_world_size()
  57. # Divide the weight matrix along the vocaburaly dimension.
  58. self.vocab_start_index, self.vocab_end_index = (
  59. vocab_range_from_global_vocab_size(
  60. self.num_embeddings_padded, get_tensor_model_parallel_rank(),
  61. self.tp_size))
  62. self.num_embeddings_per_partition = (self.vocab_end_index -
  63. self.vocab_start_index)
  64. idx = 0 if is_input_emb else 1
  65. if linear_method is None or not linear_method.quant_config.quant_vocab(
  66. )[idx]:
  67. linear_method = UnquantizedLinearMethod()
  68. self.linear_method = linear_method
  69. self.linear_weights = self.linear_method.create_weights(
  70. self.embedding_dim, [self.num_embeddings_per_partition],
  71. self.embedding_dim, self.num_embeddings_padded, params_dtype)
  72. for name, weight in self.linear_weights.items():
  73. if isinstance(weight, torch.nn.parameter.Parameter):
  74. self.register_parameter(name, weight)
  75. set_weight_attrs(weight, {"weight_loader": self.weight_loader})
  76. def weight_loader(self, param: Parameter, loaded_weight: torch.Tensor):
  77. output_dim = getattr(param, "output_dim", None)
  78. if output_dim is not None:
  79. assert loaded_weight.shape[output_dim] == self.org_vocab_size
  80. loaded_weight = loaded_weight.narrow(
  81. output_dim, self.vocab_start_index,
  82. min(self.vocab_end_index - self.vocab_start_index,
  83. self.org_vocab_size - self.vocab_start_index))
  84. if isinstance(param, torch.nn.parameter.UninitializedParameter):
  85. vocab_shape = list(loaded_weight.shape)
  86. if output_dim is not None:
  87. vocab_shape[output_dim] = self.num_embeddings_per_partition
  88. param.materialize(vocab_shape, dtype=loaded_weight.dtype)
  89. if output_dim is not None:
  90. param.data.narrow(
  91. output_dim, 0,
  92. loaded_weight.shape[output_dim]).copy_(loaded_weight)
  93. else:
  94. param.data.copy_(loaded_weight)
  95. def forward(self, input_):
  96. if self.tp_size > 1:
  97. # Build the mask.
  98. input_mask = ((input_ < self.vocab_start_index) |
  99. (input_ >= self.vocab_end_index))
  100. # Mask the input.
  101. masked_input = input_.clone() - self.vocab_start_index
  102. masked_input[input_mask] = 0
  103. else:
  104. masked_input = input_
  105. # Get the embeddings.
  106. output_parallel = self.linear_method.apply_embedding(
  107. self.linear_weights, masked_input)
  108. # output_parallel = F.embedding(masked_input, self.weight)
  109. if self.tp_size > 1:
  110. output_parallel[input_mask, :] = 0.0
  111. # Reduce across all the model parallel GPUs.
  112. output = tensor_model_parallel_all_reduce(output_parallel)
  113. return output
  114. class ParallelLMHead(VocabParallelEmbedding):
  115. """Parallelized LM head.
  116. Output logits weight matrices used in the Sampler. The weight and bias
  117. tensors are padded to make sure they are divisible by the number of
  118. model parallel GPUs.
  119. Args:
  120. num_embeddings: vocabulary size.
  121. embedding_dim: size of hidden state.
  122. bias: whether to use bias.
  123. params_dtype: type of the parameters.
  124. org_num_embeddings: original vocabulary size (without LoRA).
  125. padding_size: padding size for the vocabulary.
  126. """
  127. def __init__(self,
  128. num_embeddings: int,
  129. embedding_dim: int,
  130. bias: bool = False,
  131. params_dtype: Optional[torch.dtype] = None,
  132. linear_method=None,
  133. org_num_embeddings: Optional[int] = None,
  134. padding_size: int = DEFAULT_VOCAB_PADDING_SIZE):
  135. super().__init__(num_embeddings, embedding_dim, params_dtype,
  136. linear_method, org_num_embeddings, padding_size,
  137. False)
  138. if bias:
  139. self.bias = Parameter(
  140. torch.empty(self.num_embeddings_per_partition,
  141. dtype=params_dtype))
  142. set_weight_attrs(self.bias, {
  143. "output_dim": 0,
  144. "weight_loader": self.weight_loader
  145. })
  146. else:
  147. self.register_parameter("bias", None)
  148. def forward(self, input_):
  149. logits = self.linear_method.apply_weights(self.linear_weights, input_)
  150. if self.bias is not None:
  151. logits += self.bias
  152. return logits