MCPcopy Create free account
hub / github.com/zai-org/CodeGeeX / SelfAttention

Class SelfAttention

codegeex/torch/codegeex_model.py:51–224  ·  view source on GitHub ↗

self-attention layer abstract class. Self-attention layer takes input with size [b, s, h] and returns output of the same size.

Source from the content-addressed store, hash-verified

49
50
51class SelfAttention(torch.nn.Module):
52 """self-attention layer abstract class.
53
54 Self-attention layer takes input with size [b, s, h]
55 and returns output of the same size.
56 """
57
58 def __init__(
59 self,
60 hidden_size,
61 num_attention_heads,
62 layer_number,
63 fp16=True,
64 attention_softmax_in_fp32=True,
65 ):
66 super(SelfAttention, self).__init__()
67 self.hidden_size = hidden_size
68 self.num_attention_heads = num_attention_heads
69 self.fp16 = fp16
70 self.attention_softmax_in_fp32 = attention_softmax_in_fp32
71 self.layer_number = max(1, layer_number)
72
73 assert self.hidden_size % self.num_attention_heads == 0
74 self.hidden_size_per_attention_head = int(self.hidden_size // self.num_attention_heads)
75
76 self.query = torch.nn.Linear(self.hidden_size, self.hidden_size)
77 self.key = torch.nn.Linear(self.hidden_size, self.hidden_size)
78 self.value = torch.nn.Linear(self.hidden_size, self.hidden_size)
79
80 self.norm_factor = math.sqrt(self.hidden_size_per_attention_head)
81 self.softmax = torch.nn.Softmax(dim=-1)
82
83 self.dense = torch.nn.Linear(self.hidden_size, self.hidden_size)
84
85 def forward(
86 self,
87 hidden_states,
88 attention_mask,
89 layer_past=None,
90 get_key_value=False,
91 prompt_length=None,
92 context_length=None,
93 ):
94 # hidden_states: [sq, b, h]
95
96 # =====================
97 # Query, Key, and Value
98 # =====================
99
100 query_layer = self.query(hidden_states)
101 key_layer = self.key(hidden_states)
102 value_layer = self.value(hidden_states)
103
104 new_query_layer_shape = query_layer.size()[:-1] + \
105 (self.num_attention_heads,
106 self.hidden_size_per_attention_head)
107 query_layer = query_layer.view(*new_query_layer_shape)
108

Callers 1

__init__Method · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected