TechPulse
首页博客项目关于联系
搜索
Wild Intelligence

高级前端开发工程师 | AI 全栈工程师 | 正在深入学习人工智能

GitHubTwitterRSS

内容

博客文章项目展示搜索

关于

关于我联系方式RSS 订阅

© 2026 Leon Yang. All rights reserved.

Built with Next.js & shadcn/ui

返回博客
深度学习精选

Transformer 架构详解:从 Attention 到 GPT

2026-04-2820 分钟4,560 次阅读

Transformer 架构详解:从 Attention 到 GPT

Transformer 是现代 AI 的基石,理解它对于学习 LLM 至关重要。

Self-Attention 机制

import torch
import torch.nn.functional as F

def self_attention(Q, K, V):
    # 计算注意力分数
    d_k = Q.size(-1)
    scores = torch.matmul(Q, K.transpose(-2, -1)) / torch.sqrt(torch.tensor(d_k, dtype=torch.float32))

    # Softmax 归一化
    attention_weights = F.softmax(scores, dim=-1)

    # 加权求和
    output = torch.matmul(attention_weights, V)
    return output, attention_weights

Multi-Head Attention

class MultiHeadAttention(torch.nn.Module):
    def __init__(self, d_model, num_heads):
        super().__init__()
        self.num_heads = num_heads
        self.d_k = d_model // num_heads

        self.W_q = torch.nn.Linear(d_model, d_model)
        self.W_k = torch.nn.Linear(d_model, d_model)
        self.W_v = torch.nn.Linear(d_model, d_model)
        self.W_o = torch.nn.Linear(d_model, d_model)

    def forward(self, Q, K, V):
        batch_size = Q.size(0)

        # 线性变换并分头
        Q = self.W_q(Q).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
        K = self.W_k(K).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
        V = self.W_v(V).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)

        # 计算注意力
        attn_output, _ = self_attention(Q, K, V)

        # 拼接并输出
        attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, -1, self.num_heads * self.d_k)
        return self.W_o(attn_output)

关键创新

  1. 并行计算:相比 RNN,Transformer 可以并行处理序列
  2. 长距离依赖:Attention 机制直接建立任意位置间的连接
  3. 位置编码:通过位置编码保留序列顺序信息

Transformer 的出现,开启了大语言模型的新时代。

TransformerAttention深度学习NLP

评论

加载评论中...

目录

Transformer 架构详解:从 Attention 到 GPTSelf-Attention 机制Multi-Head Attention关键创新

分类

AI 学习1AI 应用2AI 基础2深度学习1

标签

PythonAILangChainLLM职业转型RAGNumPy数据处理TransformerAttention

热门文章

Agentic RAG:下一代智能检索系统

3,890 次阅读

LangChain 实战:构建你的第一个 RAG 应用

3,200 次阅读

从零开始学 Python:前端工程师的 AI 转型之路

2,850 次阅读

关于作者

Leon Yang

兰亭古墨

@leonyangdev

Front-End Expert | Full-Stack Developer | Currently Learning AI | Husband & Father

了解更多 →