MCPcopy Create free account
hub / github.com/pytorch/examples / forward

Method forward

distributed/tensor_parallelism/llama2_model.py:190–228  ·  view source on GitHub ↗

Forward pass of the attention module. Args: x (torch.Tensor): Input tensor. freqs_cis (torch.Tensor): Precomputed frequency tensor. Returns: torch.Tensor: Output tensor after attention.

(
        self,
        x: torch.Tensor,
        freqs_cis: torch.Tensor,
    )

Source from the content-addressed store, hash-verified

188 nn.init.trunc_normal_(self.wo.weight, mean=0.0, std=init_std)
189
190 def forward(
191 self,
192 x: torch.Tensor,
193 freqs_cis: torch.Tensor,
194 ):
195 """
196 Forward pass of the attention module.
197
198 Args:
199 x (torch.Tensor): Input tensor.
200 freqs_cis (torch.Tensor): Precomputed frequency tensor.
201
202 Returns:
203 torch.Tensor: Output tensor after attention.
204
205 """
206 bsz, seqlen, _ = x.shape
207 xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)
208
209 xq = xq.view(bsz, seqlen, self.n_heads, self.head_dim)
210 xk = xk.view(bsz, seqlen, self.n_kv_heads, self.head_dim)
211 xv = xv.view(bsz, seqlen, self.n_kv_heads, self.head_dim)
212
213 xq, xk = apply_rotary_emb(xq, xk, freqs_cis=freqs_cis)
214
215 keys = repeat_kv(xk, self.n_rep) # (bs, seqlen, n_local_heads, head_dim)
216 values = repeat_kv(xv, self.n_rep) # (bs, seqlen, n_local_heads, head_dim)
217
218 xq = xq.transpose(1, 2) # (bs, n_local_heads, seqlen, head_dim)
219 xk = keys.transpose(1, 2) # (bs, n_local_heads, seqlen, head_dim)
220 xv = values.transpose(1, 2) # (bs, n_local_heads, seqlen, head_dim)
221
222 # we use casual mask for training
223 output = F.scaled_dot_product_attention(xq, xk, xv, is_causal=True)
224 output = output.transpose(
225 1, 2
226 ).contiguous() # (bs, seqlen, n_local_heads, head_dim)
227 output = output.view(bsz, seqlen, -1)
228 return self.wo(output)
229
230
231class FeedForward(nn.Module):

Callers

nothing calls this directly

Calls 2

apply_rotary_embFunction · 0.85
repeat_kvFunction · 0.85

Tested by

no test coverage detected