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

Class SelfAttention

codegeex/oneflow/codegeex_model.py:52–276  ·  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

50
51
52class SelfAttention(torch.nn.Module):
53 """self-attention layer abstract class.
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 layer_id=0,
94 ):
95 # hidden_states: [sq, b, h]
96
97 # =====================
98 # Query, Key, and Value
99 # =====================
100
101 if hasattr(torch._C, 'grouped_matmul_bias') and not isinstance(self.query, QuantizedLinear):
102 query_layer, key_layer, value_layer = torch._C.grouped_matmul_bias([hidden_states, hidden_states, hidden_states],
103 [self.query.weight, self.key.weight, self.value.weight],
104 [self.query.bias, self.key.bias, self.value.bias])
105 else:
106 query_layer = self.query(hidden_states)
107 key_layer = self.key(hidden_states)
108 value_layer = self.value(hidden_states)
109

Callers 1

__init__Method · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected