bert_sparse_self_attention.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. """
  2. Copyright 2020 The Microsoft DeepSpeed Team
  3. """
  4. from torch import nn
  5. from deepspeed.ops.sparse_attention import SparseSelfAttention, FixedSparsityConfig
  6. class BertSparseSelfAttention(nn.Module):
  7. """Implements Sparse Self Attention layer of Bert model based on https://github.com/microsoft/DeepSpeedExamples/blob/master/bing_bert/nvidia/modelingpreln.py#L373
  8. For more information please see, TODO DeepSpeed Sparse Transformer.
  9. For usage example please see, TODO DeepSpeed Sparse Transformer Tutorial.
  10. """
  11. def __init__(
  12. self,
  13. config,
  14. # SparsityConfig parameters needs to be set accordingly
  15. sparsity_config=FixedSparsityConfig(num_heads=4)):
  16. """Initialize the bert sparse self attention layer.
  17. Note) you can use any of the provided sparsity configs or simply add yours!
  18. Arguments:
  19. config: required: Bert model config
  20. sparsity_config: optional: this parameter determines sparsity pattern configuration; it is based on FixedSparsityConfig class.
  21. """
  22. super(BertSparseSelfAttention, self).__init__()
  23. if config.hidden_size % config.num_attention_heads != 0:
  24. raise ValueError(
  25. "The hidden size (%d) is not a multiple of the number of attention "
  26. "heads (%d)" % (config.hidden_size,
  27. config.num_attention_heads))
  28. self.num_attention_heads = config.num_attention_heads
  29. self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
  30. self.all_head_size = self.num_attention_heads * self.attention_head_size
  31. self.query = nn.Linear(config.hidden_size, self.all_head_size)
  32. self.key = nn.Linear(config.hidden_size, self.all_head_size)
  33. self.value = nn.Linear(config.hidden_size, self.all_head_size)
  34. self.sparse_self_attention = SparseSelfAttention(sparsity_config)
  35. def transpose_for_scores(self, x):
  36. new_x_shape = x.size()[:-1] + (self.num_attention_heads,
  37. self.attention_head_size)
  38. x = x.view(*new_x_shape)
  39. return x.permute(0, 2, 1, 3)
  40. def forward(self, hidden_states, attention_mask):
  41. """Applies forward phase of bert sparse self attention
  42. Arguments:
  43. hidden_states: required: hidden_states tensor of the bert model
  44. attn_mask: required: a mask tensor of size (SequenceLength X SequenceLength); currently only 2D is supported
  45. Return:
  46. context_layer: a dense tensor containing attention context
  47. """
  48. mixed_query_layer = self.query(hidden_states)
  49. mixed_key_layer = self.key(hidden_states)
  50. mixed_value_layer = self.value(hidden_states)
  51. query_layer = self.transpose_for_scores(mixed_query_layer)
  52. key_layer = self.transpose_for_scores(mixed_key_layer)
  53. value_layer = self.transpose_for_scores(mixed_value_layer)
  54. context_layer = self.sparse_self_attention(query_layer,
  55. key_layer,
  56. value_layer,
  57. key_padding_mask=attention_mask)
  58. context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
  59. new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size, )
  60. context_layer = context_layer.view(*new_context_layer_shape)
  61. return context_layer