Editing
Transformer Architecture
(section)
Jump to navigation
Jump to search
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== <span style="color: #FFFFFF;">Applying</span> == '''Computing self-attention from scratch in PyTorch:''' <syntaxhighlight lang="python"> import torch import torch.nn.functional as F def scaled_dot_product_attention(Q, K, V, mask=None): """ Q, K, V: shape (batch, heads, seq_len, d_k) """ d_k = Q.size(-1) # Compute attention scores scores = torch.matmul(Q, K.transpose(-2, -1)) / (d_k ** 0.5) # Apply causal mask (for decoder) if mask is not None: scores = scores.masked_fill(mask == 0, float('-inf')) # Softmax to get attention weights attn_weights = F.softmax(scores, dim=-1) # Weighted sum of values return torch.matmul(attn_weights, V), attn_weights # Example dimensions batch, heads, seq_len, d_k = 2, 8, 512, 64 Q = torch.randn(batch, heads, seq_len, d_k) K = torch.randn(batch, heads, seq_len, d_k) V = torch.randn(batch, heads, seq_len, d_k) output, weights = scaled_dot_product_attention(Q, K, V) print(output.shape) # torch.Size([2, 8, 512, 64]) </syntaxhighlight> ; Key transformer variants and their use cases : '''BERT''' β Sentence classification, NER, question answering (fine-tuning on labeled data) : '''GPT-2/3/4''' β Text generation, few-shot learning, instruction following : '''T5''' β Any-to-any text tasks framed as "text to text" : '''LLaMA / Mistral''' β Open-weight generation models for local deployment : '''ViT (Vision Transformer)''' β Image classification by treating patches as tokens : '''Whisper''' β Speech-to-text using encoder transformer on mel spectrograms </div> <div style="background-color: #8B4500; color: #FFFFFF; padding: 20px; border-radius: 8px; margin-bottom: 15px;">
Summary:
Please note that all contributions to BloomWiki may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
BloomWiki:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Navigation menu
Personal tools
Not logged in
Talk
Contributions
Create account
Log in
Namespaces
Page
Discussion
English
Views
Read
Edit
View history
More
Search
Navigation
Main page
Recent changes
Random page
Help about MediaWiki
Tools
What links here
Related changes
Special pages
Page information