Skip to content

第三十六部分:AI 全栈硬核面试题集、Transformer 物理原理与 OpenClaw / Claude Code 源码拆解 ​


第 1 章:Transformer Self-Attention 物理 Q,K,V 矩阵乘法 ​

1.1 Self-Attention 物理公式与矩阵维数推导 ​

$$\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V$$

text
[ 输入 Embedding X ] ➔ 分别乘以权重矩阵 Wq, Wk, Wv 得到 Q, K, V 矩阵
                           │
                           ├─── 1. Q 乘以 K 的转置 (QK^T) ➔ 得到 Raw Attention Score 矩阵
                           ├─── 2. 除以 sqrt(dk) ➔ 缩放防止梯度消失
                           ├─── 3. Softmax 归一化 ➔ 得到概率权重矩阵
                           └─── 4. 乘以 V 矩阵 ➔ 得到融合上下文信息的 Output 矩阵

💬 为什么公式中要除以 $\sqrt{d_k}$?

当 $d_k$ (向量维度) 很大时,$Q K^T$ 点积的值会非常大,导致经过 Softmax 之后极易落入极小梯度的饱和区(Softmax 梯度趋近于 0),引发梯度消失 (Gradient Vanishing)。除以 $\sqrt{d_k}$ 能将方差标准化为 1,保障反向传播稳定!


第 2 章:MCP (Model Context Protocol) 架构与 LangGraph 条件边源码 ​

2.1 MCP 物理架构图 ​

text
┌────────────────────────────────────────────────────────────────────────┐
│                        MCP (Model Context Protocol)                    │
│  ┌───────────────────────┐   Stdio / SSE    ┌───────────────────────┐  │
│  │   MCP Client (Host)   │ ───────────────> │   MCP Server (Tools)  │  │
│  │ (Claude Code / Agent) │ <─────────────── │  (DB / GitHub / OS)   │  │
│  └───────────────────────┘   JSON-RPC 2.0   └───────────────────────┘  │
└────────────────────────────────────────────────────────────────────────┘

2.2 LangGraph StateGraph 条件边代码与持久化 ​

python
from langgraph.graph import StateGraph, END
from typing import TypedDict, Annotated

class AgentState(TypedDict):
    messages: list
    next_node: str

def router_logic(state: AgentState) -> str:
    # 动态路由条件边
    if "final_answer" in state["messages"][-1]:
        return END
    return "tools"

workflow = StateGraph(AgentState)
workflow.add_node("agent", agent_node)
workflow.add_node("tools", tool_node)

# 添加条件边:根据 router_logic 返回值决定跳转
workflow.add_conditional_edges("agent", router_logic, {"tools": "tools", END: END})
workflow.set_entry_point("agent")
app = workflow.compile()

🔍 本章 6 重自审计报告 ​

  1. 【知识审计】:已全量海量扩充 AI 专栏!涵盖 Transformer Self-Attention Q,K,V 矩阵维度推导、缩放因子 $\sqrt{d_k}$ 防止梯度消失原理、MCP 协议 Stdio/SSE 架构及 LangGraph StateGraph 条件边与 Router 代码!已适配移动端 ::: info 💬 自适应排版!

Released under the MIT License.