block.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. """
  2. Bloom intermediate layer
  3. Based on https://github.com/huggingface/transformers/commit/ca2a55e9dfb245527b5e1c954fec6ffbb7aef07b
  4. See commit history for authorship.
  5. """
  6. import math
  7. import torch
  8. import torch.nn as nn
  9. import torch.nn.quantized.dynamic.modules.linear
  10. from petals.bloom.ops import (
  11. BloomGelu,
  12. BloomScaledSoftmax,
  13. attention_mask_func,
  14. build_alibi_tensor,
  15. dropout_add,
  16. pre_process_alibi_for_pad,
  17. split_tensor_along_last_dim,
  18. )
  19. class BloomAttention(nn.Module):
  20. def __init__(self, config, layer_number=None):
  21. super().__init__()
  22. self.hidden_size = config.hidden_size
  23. self.num_heads = config.n_head
  24. self.head_dim = self.hidden_size // self.num_heads
  25. self.split_size = self.hidden_size
  26. self.attention_softmax_in_fp32 = config.attention_softmax_in_fp32
  27. self.masked_softmax_fusion = config.masked_softmax_fusion
  28. self.hidden_dropout = config.hidden_dropout
  29. if self.head_dim * self.num_heads != self.hidden_size:
  30. raise ValueError(
  31. f"`hidden_size` must be divisible by num_heads (got `hidden_size`: {self.hidden_size} and `num_heads`:"
  32. f" {self.num_heads})."
  33. )
  34. # Layer-wise attention scaling
  35. self.layer_number = max(1, layer_number)
  36. self.norm_factor = math.sqrt(self.head_dim) * self.layer_number
  37. # Scaled Softmax
  38. self.scale_mask_softmax = BloomScaledSoftmax(
  39. self.masked_softmax_fusion,
  40. attention_mask_func,
  41. self.attention_softmax_in_fp32,
  42. self.layer_number,
  43. )
  44. self.query_key_value = nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=True)
  45. self.dense = nn.Linear(self.hidden_size, self.hidden_size)
  46. self.attention_dropout = nn.Dropout(config.attention_dropout)
  47. def forward(
  48. self,
  49. hidden_states,
  50. residual,
  51. layer_past=None,
  52. attention_mask=None,
  53. alibi=None,
  54. head_mask=None,
  55. use_cache=False,
  56. output_attentions=False,
  57. ):
  58. if alibi is None:
  59. current_sequence_length = hidden_states.shape[1] + (0 if layer_past is None else layer_past[0].shape[1])
  60. alibi = build_alibi_tensor(
  61. current_sequence_length, n_head=self.num_heads, dtype=hidden_states.dtype, device=hidden_states.device
  62. )
  63. # hidden_states: [batch_size, seq_length, hidden_size]
  64. # apply preprocessing if the input is padded
  65. if attention_mask is not None:
  66. alibi = pre_process_alibi_for_pad(alibi, attention_mask)
  67. # otherwise repeat alibi tensor with the batch size
  68. else:
  69. alibi = alibi.repeat(hidden_states.shape[0], 1, 1)
  70. mixed_x_layer = self.query_key_value(hidden_states)
  71. # [batch_size, seq_length, 3 x hidden_size] --> [batch_size, seq_length, num_heads, 3 x head_dim]
  72. new_tensor_shape = mixed_x_layer.size()[:-1] + (self.num_heads, 3 * self.head_dim)
  73. mixed_x_layer = mixed_x_layer.view(*new_tensor_shape)
  74. # [batch_size, seq_length, num_heads, 3 x head_dim] --> 3 [batch_size, seq_length, num_heads, head_dim]
  75. (query_layer, key_layer, value_layer) = split_tensor_along_last_dim(mixed_x_layer, 3)
  76. if layer_past is not None:
  77. past_key, past_value = layer_past
  78. key_layer = torch.cat((past_key.type_as(key_layer), key_layer), dim=1)
  79. value_layer = torch.cat((past_value.type_as(value_layer), value_layer), dim=1)
  80. if use_cache is True:
  81. present = (key_layer, value_layer)
  82. else:
  83. present = None
  84. # [batch_size, head_dim, q_length, k_length]
  85. output_size = (query_layer.size(0), query_layer.size(2), query_layer.size(1), key_layer.size(1))
  86. # [batch_size, q_length, num_heads, head_dim] -> [q_length, batch_size * num_heads, head_dim]
  87. query_layer = query_layer.transpose(1, 0).reshape(output_size[2], output_size[0] * output_size[1], -1)
  88. # [batch_size, k_length, num_heads, head_dim] -> [k_length, batch_size * num_heads, head_dim]
  89. key_layer = key_layer.transpose(1, 0).reshape(output_size[3], output_size[0] * output_size[1], -1)
  90. # Raw attention scores. [batch_size * num_heads, q_length, k_length]
  91. beta = 1.0 / self.layer_number
  92. matmul_result = torch.baddbmm(
  93. alibi,
  94. query_layer.transpose(1, 0),
  95. key_layer.transpose(1, 0).transpose(1, 2),
  96. beta=beta,
  97. alpha=(1.0 / self.norm_factor),
  98. )
  99. # change view to [batch_size, num_heads, q_length, k_length]
  100. attention_scores = matmul_result.view(*output_size)
  101. # attention scores and attention mask [b, np, sq, sk]
  102. max_positions = max(attention_scores.shape[-1], attention_scores.shape[-2])
  103. attention_probs = self.scale_mask_softmax(attention_scores, attention_mask, max_positions).to(value_layer.dtype)
  104. attention_probs = self.attention_dropout(attention_probs)
  105. if head_mask is not None:
  106. attention_probs = attention_probs * head_mask
  107. # context layer shape: [batch_size, num_heads, q_length, head_dim]
  108. output_size = (value_layer.size(0), value_layer.size(2), query_layer.size(0), value_layer.size(3))
  109. # change view [k_length, batch_size x num_heads, head_dim]
  110. value_layer = value_layer.transpose(1, 0).reshape(value_layer.size(1), output_size[0] * output_size[1], -1)
  111. # change view [batch_size x num_heads, q_length, k_length]
  112. attention_probs_reshaped = attention_probs.view(output_size[0] * output_size[1], output_size[2], -1)
  113. # matmul: [batch_size * num_heads, q_length, head_dim]
  114. context_layer = torch.bmm(attention_probs_reshaped, value_layer.transpose(0, 1))
  115. # change view [batch_size, num_heads, q_length, head_dim]
  116. context_layer = context_layer.view(*output_size)
  117. # [batchs_size, num_heads, q_length, head_dim] --> [q_length, batch_size, num_heads, head_dim]
  118. context_layer = context_layer.permute(2, 0, 1, 3).contiguous()
  119. # [q_length, batch_size, num_heads, head_dim] --> [q_length, batch_size, hidden_size]
  120. new_context_layer_shape = context_layer.size()[:-2] + (self.hidden_size,)
  121. context_layer = context_layer.view(*new_context_layer_shape)
  122. # Output. [q_length, batch_size, hidden_size]
  123. # aggregate results across tp ranks. See here: https://github.com/pytorch/pytorch/issues/76232
  124. output_tensor = self.dense(context_layer)
  125. output = output_tensor.transpose(1, 0)
  126. output = dropout_add(output, residual, self.hidden_dropout, self.training)
  127. outputs = (output, present)
  128. if output_attentions:
  129. outputs += (attention_probs,)
  130. return outputs
  131. class BloomMLP(nn.Module):
  132. def __init__(self, config):
  133. super().__init__()
  134. self.hidden_size = config.hidden_size
  135. self.dense_h_to_4h = nn.Linear(self.hidden_size, 4 * self.hidden_size)
  136. self.dense_4h_to_h = nn.Linear(4 * self.hidden_size, self.hidden_size)
  137. self.hidden_dropout = config.hidden_dropout
  138. self.gelu_impl = BloomGelu()
  139. def forward(self, hidden_states, residual):
  140. hidden_states = self.gelu_impl(self.dense_h_to_4h(hidden_states))
  141. intermediate_output = self.dense_4h_to_h(hidden_states)
  142. output = dropout_add(intermediate_output, residual, self.hidden_dropout, self.training)
  143. return output
  144. class BloomBlock(nn.Module):
  145. def __init__(self, config, layer_number=None):
  146. super().__init__()
  147. self.hidden_size = config.hidden_size
  148. self.input_layernorm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_epsilon)
  149. self.n_head = config.n_head
  150. self.self_attention = BloomAttention(config, layer_number=layer_number)
  151. self.post_attention_layernorm = nn.LayerNorm(self.hidden_size, eps=config.layer_norm_epsilon)
  152. self.mlp = BloomMLP(config)
  153. self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm
  154. self.hidden_dropout = config.hidden_dropout
  155. def forward(
  156. self,
  157. hidden_states,
  158. layer_past=None,
  159. attention_mask=None,
  160. head_mask=None,
  161. use_cache=False,
  162. output_attentions=False,
  163. alibi=None,
  164. ):
  165. # hidden_states: [batch_size, seq_length, hidden_size]
  166. # Layer norm at the beginning of the transformer layer.
  167. layernorm_output = self.input_layernorm(hidden_states)
  168. # Layer norm post the self attention.
  169. if self.apply_residual_connection_post_layernorm:
  170. residual = layernorm_output
  171. else:
  172. residual = hidden_states
  173. # Self attention.
  174. attn_outputs = self.self_attention(
  175. layernorm_output,
  176. residual,
  177. layer_past=layer_past,
  178. attention_mask=attention_mask,
  179. alibi=alibi,
  180. head_mask=head_mask,
  181. use_cache=use_cache,
  182. output_attentions=output_attentions,
  183. )
  184. attention_output = attn_outputs[0]
  185. outputs = attn_outputs[1:]
  186. layernorm_output = self.post_attention_layernorm(attention_output)
  187. # Get residual
  188. if self.apply_residual_connection_post_layernorm:
  189. residual = layernorm_output
  190. else:
  191. residual = attention_output
  192. # MLP.
  193. output = self.mlp(layernorm_output, residual)
  194. if use_cache:
  195. outputs = (output,) + outputs
  196. else:
  197. outputs = (output,) + outputs[1:]
  198. return outputs # hidden_states, present, attentions