<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet href="/scripts/pretty-feed-v3.xsl" type="text/xsl"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:h="http://www.w3.org/TR/html4/"><channel><title>Heng&apos;s Blog</title><description>Notes and reflections on learning, research, and practice.</description><link>https://heng-blog.pages.dev</link><item><title>Recurrent Neural Networks: 用隐藏状态处理序列</title><link>https://heng-blog.pages.dev/blog/rnn</link><guid isPermaLink="true">https://heng-blog.pages.dev/blog/rnn</guid><description>从隐藏状态、参数共享和时间展开出发，理解 Vanilla RNN 怎样处理序列，以及它为什么难以学习长期依赖。</description><pubDate>Tue, 18 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;普通前馈神经网络把每个输入独立处理，无法自然地表达“前面发生了什么”。但序列中的当前元素通常依赖之前的信息：理解一个词需要参考前文，判断一帧中的动作也需要观察此前的画面。&lt;/p&gt;
&lt;p&gt;Recurrent Neural Network（RNN）的核心想法，是在处理当前输入的同时保留一个隐藏状态。这个状态随着序列向前传递，成为网络对“截至当前时刻的信息”的压缩表示。&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;本文根据 USC CSCI 566 Lecture 7: Recurrent Neural Networks 整理。下文用单下划线表示 vector，用双下划线表示 matrix；scalar 不加下划线。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Vanilla RNN 怎样更新状态&lt;/h2&gt;
&lt;p&gt;Vanilla RNN 的典型状态更新是 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_t}=\tanh(\underline{\underline{W_x}}\underline{x_t}+\underline{\underline{W_h}}\underline{h_{t-1}}+\underline{b})&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;其中：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{x_t}&lt;/code&gt; 是第 &lt;code class=&quot;language-math math-inline&quot;&gt;t&lt;/code&gt; 个输入；&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_{t-1}}&lt;/code&gt; 是上一个时间步留下的隐藏状态；&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_x}}&lt;/code&gt; 将当前输入投影到隐藏空间；&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_h}}&lt;/code&gt; 决定过去的信息怎样影响当前状态；&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_t}&lt;/code&gt; 是结合当前输入与过去信息后得到的新状态。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;初始状态 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_0}&lt;/code&gt; 通常设为零，也可以作为参数学习。如果任务要求每个时间步都产生输出，还可以计算 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{y_t}=\operatorname{softmax}(\underline{\underline{W_y}}\underline{h_t}+\underline{b_y})&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;这条公式最重要的地方不是 tanh，而是 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_{t-1}}\rightarrow\underline{h_t}&lt;/code&gt; 的递归关系。当前状态会继续参与下一步计算，因此信息可以沿着 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_0}\rightarrow\underline{h_1}\rightarrow\cdots\rightarrow\underline{h_T}&lt;/code&gt; 向后传递。&lt;/p&gt;
&lt;h2&gt;时间展开与参数共享&lt;/h2&gt;
&lt;p&gt;RNN 可以沿时间展开成一条计算链：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;h₀ ──[x₁]──▶ h₁ ──[x₂]──▶ h₂ ──[x₃]──▶ h₃ ── … ──▶ hₜ
       f_W          f_W          f_W                 f_W
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;图中的每个 &lt;code class=&quot;language-math math-inline&quot;&gt;f_W&lt;/code&gt; 都是同一个函数，并且复用同一组 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_x}}&lt;/code&gt;、&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_h}}&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{b}&lt;/code&gt;。因此，序列变长并不会增加模型参数量；网络只是在不同时间步重复执行同一种状态更新。&lt;/p&gt;
&lt;p&gt;参数共享也赋予了 RNN 一个重要假设：同一种局部规律可以出现在序列的不同位置。某个词出现在第 &lt;code class=&quot;language-math math-inline&quot;&gt;3&lt;/code&gt; 个位置还是第 &lt;code class=&quot;language-math math-inline&quot;&gt;30&lt;/code&gt; 个位置，网络都使用同一套规则处理它。&lt;/p&gt;
&lt;h2&gt;一种结构，多种序列任务&lt;/h2&gt;
&lt;p&gt;改变在哪些时间步提供输入和读取输出，同一个 RNN 就可以表达多种任务：&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;形式&lt;/th&gt;
&lt;th&gt;输入与输出&lt;/th&gt;
&lt;th&gt;例子&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;many-to-one&lt;/td&gt;
&lt;td&gt;整个序列产生一个输出&lt;/td&gt;
&lt;td&gt;文本分类、视频动作识别&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;many-to-many&lt;/td&gt;
&lt;td&gt;每个输入位置产生一个输出&lt;/td&gt;
&lt;td&gt;序列标注、逐帧分类&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;one-to-many&lt;/td&gt;
&lt;td&gt;一个输入逐步产生一个序列&lt;/td&gt;
&lt;td&gt;图像描述、序列生成&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;sequence-to-sequence&lt;/td&gt;
&lt;td&gt;先编码输入序列，再生成输出序列&lt;/td&gt;
&lt;td&gt;机器翻译&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;在生成任务中，上一步生成的 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{y_{t-1}}&lt;/code&gt; 还可以作为下一步输入。于是模型不仅传递隐藏状态，也会根据自己此前生成的结果继续向后生成。&lt;/p&gt;
&lt;h2&gt;RNN 怎样训练&lt;/h2&gt;
&lt;p&gt;训练时，先沿整个序列完成前向传播，得到各时间步的损失；再把展开后的 RNN 看成一个很深、但各层共享参数的网络，沿时间反向传播梯度。这个过程叫 Backpropagation Through Time（BPTT，随时间反向传播）。&lt;/p&gt;
&lt;p&gt;如果序列很长，保存完整计算图的成本会很高。Truncated BPTT 会继续把隐藏状态传向未来，但只在一个较短的时间窗口内反向传播。它降低了计算和显存成本，代价是窗口之外的依赖无法直接获得梯度。&lt;/p&gt;
&lt;h2&gt;为什么长期依赖很难学习&lt;/h2&gt;
&lt;p&gt;从较晚的时间步向较早的时间步反向传播时，梯度会反复经过 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_h}}&lt;/code&gt; 和 tanh 的导数：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;如果这些连乘的尺度持续小于 &lt;code class=&quot;language-math math-inline&quot;&gt;1&lt;/code&gt;，梯度会随时间距离迅速缩小，形成梯度消失（vanishing gradient）；&lt;/li&gt;
&lt;li&gt;如果尺度持续大于 &lt;code class=&quot;language-math math-inline&quot;&gt;1&lt;/code&gt;，梯度会快速增大，形成梯度爆炸（exploding gradient）。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;梯度裁剪（gradient clipping）可以在梯度范数过大时将它缩小，因此主要用于控制梯度爆炸；它不能从根本上恢复已经消失的梯度。LSTM 和 GRU 后来通过更明确的信息通道与门控，改善了长期依赖的学习。&lt;/p&gt;
&lt;h2&gt;从 RNN 到 attention&lt;/h2&gt;
&lt;p&gt;RNN 用一个固定大小的 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_t}&lt;/code&gt; 持续压缩历史信息，同时要求时间步按顺序计算。序列很长时，早期信息既可能在状态中逐渐丢失，也很难通过梯度获得训练信号。&lt;/p&gt;
&lt;p&gt;Attention 改变了这个信息路径：模型不必只依赖最后一个隐藏状态，而是可以在需要时直接读取不同时间步的表示。Additive Attention 的评分函数看起来很像 Vanilla RNN，因为两者都使用“两个线性投影相加，再经过 tanh”的计算模板；区别是 attention 的分数不会作为下一个位置的隐藏状态继续递归传递。&lt;/p&gt;
&lt;p&gt;所以，理解 RNN 最重要的是抓住三点：隐藏状态把过去带到现在，同一组参数在所有时间步共享，而这种递归链既让网络能够处理可变长度序列，也带来了顺序计算和长期梯度传播的问题。&lt;/p&gt;</content:encoded><h:img src="https://heng-blog.pages.dev/images/social-card.svg"/><enclosure url="https://heng-blog.pages.dev/images/social-card.svg"/></item><item><title>Transformer - 从 Additive Attention 到 Multi-Head Attention</title><link>https://heng-blog.pages.dev/blog/from-additive-to-multi-head-attention</link><guid isPermaLink="true">https://heng-blog.pages.dev/blog/from-additive-to-multi-head-attention</guid><description>从 Bahdanau Attention 出发，推导缩放点积注意力、多头机制以及 padding 和 causal mask。</description><pubDate>Sat, 19 Apr 2025 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;注意力机制的共同目标是：根据当前查询为一组候选信息分配权重，再将它们聚合为上下文表示。本文从机器翻译中的 Additive Attention 出发，逐步过渡到 Transformer 使用的 Multi-Head Attention。&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;本文整理自 &lt;a href=&quot;https://github.com/hengproject/ML_recall&quot;&gt;&lt;code&gt;hengproject/ML_recall&lt;/code&gt;&lt;/a&gt; 中的 &lt;a href=&quot;https://github.com/hengproject/ML_recall/blob/master/basics/attention.ipynb&quot;&gt;&lt;code&gt;basics/attention.ipynb&lt;/code&gt;&lt;/a&gt;。参考了 &lt;a href=&quot;https://hwcoder.top/Manual-Coding-1&quot;&gt;hwcoder 的手写笔记&lt;/a&gt;及&lt;a href=&quot;https://zhuanlan.zhihu.com/p/555778029&quot;&gt;《Recurrent Models of Visual Attention》精读&lt;/a&gt;。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Additive Attention&lt;/h2&gt;
&lt;p&gt;Bahdanau 等人在 2014 年的论文 &lt;a href=&quot;https://arxiv.org/abs/1409.0473&quot;&gt;&lt;em&gt;Neural Machine Translation by Jointly Learning to Align and Translate&lt;/em&gt;&lt;/a&gt; 中，将注意力机制用于神经机器翻译。生成每个目标 token 时，Decoder 会为 Encoder 的全部隐藏状态分配权重，并计算上下文向量。&lt;/p&gt;
&lt;p&gt;Encoder 读取长度为 &lt;code class=&quot;language-math math-inline&quot;&gt;T_x&lt;/code&gt; 的源序列后，会产生一组隐藏状态 &lt;code class=&quot;language-math math-inline&quot;&gt;\{\underline{h_1},\ldots,\underline{h_{T_x}}\}&lt;/code&gt;；其中 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_j}&lt;/code&gt; 表示源序列第 &lt;code class=&quot;language-math math-inline&quot;&gt;j&lt;/code&gt; 个位置的上下文信息。Decoder 在生成目标 token &lt;code class=&quot;language-math math-inline&quot;&gt;y_i&lt;/code&gt; 之前，已经有上一步的隐藏状态（&lt;code&gt;hidden_state&lt;/code&gt;）&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{s_{i-1}}&lt;/code&gt;，它概括了此前的生成进度 &lt;code class=&quot;language-math math-inline&quot;&gt;y_1,\ldots,y_{i-1}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;此时 attention 要回答的问题是：根据 Decoder 当前已经生成的内容，源序列中的哪些位置对下一个 token &lt;code class=&quot;language-math math-inline&quot;&gt;y_i&lt;/code&gt; 最有用？因此，它分别比较 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{s_{i-1}}&lt;/code&gt; 与每个 Encoder state &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_j}&lt;/code&gt;，得到匹配分数 &lt;code class=&quot;language-math math-inline&quot;&gt;e_{i1},\ldots,e_{iT_x}&lt;/code&gt;。这些分数经过 softmax 后形成注意力权重，再用于汇总当前 Decoder step 所需的源序列信息。&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;记号说明：&lt;/strong&gt; 下文用单下划线表示 vector，用双下划线表示 matrix；scalar 不加下划线。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;1. 计算匹配分数&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;e_{ij}
= \underline{v_a}^T
\tanh\left(
\underline{\underline{W_a}}\underline{s_{i-1}}
+ \underline{\underline{U_a}}\underline{h_j}
\right).&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_a}}&lt;/code&gt;、&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{U_a}}&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{v_a}&lt;/code&gt; 都是可训练参数。若 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{s_{i-1}}\in\mathbb{R}^{d_s}&lt;/code&gt;、&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_j}\in\mathbb{R}^{d_h}&lt;/code&gt;，并将 attention 隐藏空间的维度记为 &lt;code class=&quot;language-math math-inline&quot;&gt;d_a&lt;/code&gt;，那么 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_a}}\in\mathbb{R}^{d_a\times d_s}&lt;/code&gt;、&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{U_a}}\in\mathbb{R}^{d_a\times d_h}&lt;/code&gt;、&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{v_a}\in\mathbb{R}^{d_a}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;这个评分函数可视为一个带 &lt;code&gt;tanh&lt;/code&gt; 的小型前馈网络，用于估计当前 Decoder state 与每个 Encoder state 的匹配程度。&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{v_a}&lt;/code&gt; 的主要作用是将 &lt;code&gt;tanh&lt;/code&gt; 输出的 vector 转换成 scalar，作为最终的匹配分数 &lt;code class=&quot;language-math math-inline&quot;&gt;e_{ij}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;觉得这个匹配函数像 Vanilla RNN，并不是错觉。它们确实使用了几乎相同的计算模板：两个线性变换相加，再经过 &lt;code&gt;tanh&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;Vanilla RNN 的典型状态更新是 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_t}=\tanh(\underline{\underline{W_x}}\underline{x_t}+\underline{\underline{W_h}}\underline{h_{t-1}}+\underline{b})&lt;/code&gt;，Additive Attention 的匹配函数是 &lt;code class=&quot;language-math math-inline&quot;&gt;e_{ij}=\underline{v_a}^T\tanh(\underline{\underline{W_a}}\underline{s_{i-1}}+\underline{\underline{U_a}}\underline{h_j})&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;把两者并排看，对应关系会更明显：&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Vanilla RNN&lt;/th&gt;
&lt;th&gt;Additive Attention&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;当前输入 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{x_t}&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;第 &lt;code class=&quot;language-math math-inline&quot;&gt;j&lt;/code&gt; 个 Encoder state &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_j}&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;上一步状态 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_{t-1}}&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;上一步 Decoder state &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{s_{i-1}}&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_x}}\underline{x_t}+\underline{\underline{W_h}}\underline{h_{t-1}}&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{U_a}}\underline{h_j}+\underline{\underline{W_a}}\underline{s_{i-1}}&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;输出新的隐藏状态 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_t}&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;再乘 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{v_a}^T&lt;/code&gt;，输出匹配分数 &lt;code class=&quot;language-math math-inline&quot;&gt;e_{ij}&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;它们看起来相似，是因为两者都在做同一类计算：把两个向量投影到同一个隐藏空间，相加后再经过非线性变换。&lt;/p&gt;
&lt;p&gt;在 Additive Attention 中，可以先写出 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{z_{ij}}=\tanh(\underline{\underline{W_a}}\underline{s_{i-1}}+\underline{\underline{U_a}}\underline{h_j})&lt;/code&gt;。这里的 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{z_{ij}}&lt;/code&gt; 是一个联合表示，表示 Decoder 当前的生成需求 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{s_{i-1}}&lt;/code&gt; 与第 &lt;code class=&quot;language-math math-inline&quot;&gt;j&lt;/code&gt; 个 Encoder state &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_j}&lt;/code&gt; 组合之后的结果。随后再计算 &lt;code class=&quot;language-math math-inline&quot;&gt;e_{ij}=\underline{v_a}^T\underline{z_{ij}}&lt;/code&gt;，把这个向量压缩成一个标量匹配分数。&lt;/p&gt;
&lt;p&gt;因此，它本质上是一个单隐藏层前馈神经网络：&lt;code class=&quot;language-math math-inline&quot;&gt;[\underline{s_{i-1}},\underline{h_j}]\longrightarrow\underline{z_{ij}}\longrightarrow e_{ij}&lt;/code&gt;。把两个输入拼接起来后，评分函数也可以写成 &lt;code class=&quot;language-math math-inline&quot;&gt;e_{ij}=\underline{v_a}^T\tanh\left(\begin{bmatrix}\underline{\underline{W_a}}&amp;#x26;\underline{\underline{U_a}}\end{bmatrix}\begin{bmatrix}\underline{s_{i-1}}\\\underline{h_j}\end{bmatrix}\right)&lt;/code&gt;。论文只是把两个向量分别投影后相加，没有直接写成拼接形式。&lt;/p&gt;
&lt;p&gt;不过，它本身不是 RNN。关键区别在于是否存在时间递归。&lt;/p&gt;
&lt;p&gt;RNN 计算 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_t}=f(\underline{x_t},\underline{h_{t-1}})&lt;/code&gt; 后，得到的 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_t}&lt;/code&gt; 会继续参与下一时刻的计算，即 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_{t-1}}\rightarrow\underline{h_t}\rightarrow\underline{h_{t+1}}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;Attention 打分计算的是 &lt;code class=&quot;language-math math-inline&quot;&gt;e_{ij}=f(\underline{s_{i-1}},\underline{h_j})&lt;/code&gt;。得到的 &lt;code class=&quot;language-math math-inline&quot;&gt;e_{ij}&lt;/code&gt; 只是当前位置的匹配分数，不会作为 attention 网络的隐藏状态继续传递。对于固定的解码步骤 &lt;code class=&quot;language-math math-inline&quot;&gt;i&lt;/code&gt;，&lt;code class=&quot;language-math math-inline&quot;&gt;e_{i1},e_{i2},\ldots,e_{iT}&lt;/code&gt; 之间不存在 &lt;code class=&quot;language-math math-inline&quot;&gt;e_{i1}\rightarrow e_{i2}\rightarrow e_{i3}&lt;/code&gt; 这样的递归关系，因此这些分数可以并行计算。&lt;/p&gt;
&lt;p&gt;更准确地说，Additive Attention 的评分函数长得像 RNN 的状态更新函数，但它是一个前馈网络，而不是循环网络。&lt;/p&gt;
&lt;p&gt;这种形式也和它的历史背景有关。Bahdanau Attention 本来就是为 RNN Encoder–Decoder 设计的。当时已经有 Encoder state &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_j}&lt;/code&gt; 和 Decoder state &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{s_{i-1}}&lt;/code&gt;，研究者需要一个可训练函数判断二者是否匹配，自然采用了当时常见的 &lt;code class=&quot;language-math math-inline&quot;&gt;\tanh(\underline{\underline{W}}\underline{x}+\underline{\underline{U}}\underline{h})&lt;/code&gt; 结构。可以把它理解为：用一个结构类似 RNN 单元内部计算的小型 MLP，给两个隐藏状态打分。&lt;/p&gt;
&lt;p&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{v_a}^T&lt;/code&gt; 是 RNN 状态更新公式中没有的部分。RNN 中，&lt;code&gt;tanh&lt;/code&gt; 的输出本身就是新的隐藏向量；attention 最终需要的却是一个标量分数。若 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{z_{ij}},\underline{v_a}\in\mathbb{R}^{d_a}&lt;/code&gt;，那么 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{v_a}^T\underline{z_{ij}}\in\mathbb{R}&lt;/code&gt;。这个标量越大，表示第 &lt;code class=&quot;language-math math-inline&quot;&gt;j&lt;/code&gt; 个 Encoder position 与当前 Decoder step 越匹配。之后再对所有 &lt;code class=&quot;language-math math-inline&quot;&gt;e_{ij}&lt;/code&gt; 做 softmax，得到真正用于加权聚合的注意力权重 &lt;code class=&quot;language-math math-inline&quot;&gt;\alpha_{ij}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;所以，直觉可以更准确地表述为：它不是一个 RNN，而是它的隐藏层采用了与经典 RNN 单元相同的“两个线性投影相加，再经过 &lt;code&gt;tanh&lt;/code&gt;”的计算结构。并且 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{s_{i-1}}&lt;/code&gt; 本身通常就来自 RNN Decoder，因此整套公式在视觉上会更像 RNN。&lt;/p&gt;
&lt;h3&gt;2. 归一化注意力权重&lt;/h3&gt;
&lt;p&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;e_{ij}&lt;/code&gt; 是未经归一化的注意力分数，&lt;code class=&quot;language-math math-inline&quot;&gt;\alpha_{ij}&lt;/code&gt; 是经过 softmax 后得到的注意力权重，满足
&lt;code class=&quot;language-math math-inline&quot;&gt;\sum_j\alpha_{ij}=1&lt;/code&gt;，并实际用于 Encoder state 的加权聚合。&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\alpha_{ij}
= \frac{\exp(e_{ij})}{\sum_{k=1}^{T_x}\exp(e_{ik})},
\qquad
\sum_{j=1}^{T_x}\alpha_{ij}=1.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;实现 softmax 时减去最大分数，可以避免指数运算溢出。&lt;/p&gt;
&lt;p&gt;这里的指数函数会把任意实数分数转换成正数，并放大不同分数之间的相对差异；除以所有指数分数之和，则把它们归一化成总和为 &lt;code class=&quot;language-math math-inline&quot;&gt;1&lt;/code&gt; 的权重。&lt;/p&gt;
&lt;h3&gt;3. 聚合上下文&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\underline{c_i}
= \sum_{j=1}^{T_x}\alpha_{ij}\underline{h_j}.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{c_i}&lt;/code&gt; 是 Encoder state 的加权和，表示生成第 &lt;code class=&quot;language-math math-inline&quot;&gt;i&lt;/code&gt; 个目标 token 时需要的源序列信息。&lt;/p&gt;
&lt;h3&gt;NumPy 实现&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import numpy as np

def additive_attention(s_prev, h, W_a, U_a, v_a):
    &quot;&quot;&quot;
    s_prev: (hidden_size,)
    h:      (source_length, hidden_size)
    W_a:    (attention_dim, hidden_size)
    U_a:    (attention_dim, hidden_size)
    v_a:    (attention_dim,)
    &quot;&quot;&quot;
    source_length = h.shape[0]
    s_expanded = np.broadcast_to(s_prev, (source_length, s_prev.size))

    energy = np.tanh(s_expanded @ W_a.T + h @ U_a.T) @ v_a
    weights = np.exp(energy - np.max(energy))
    weights /= np.sum(weights)
    context = weights @ h
    return context, weights
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;支持 batch 的 PyTorch 实现&lt;/h3&gt;
&lt;p&gt;这里用 &lt;code&gt;Linear&lt;/code&gt; 实现 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_a}}&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{U_a}}&lt;/code&gt;。它们只变换最后一个维度，因此 &lt;code class=&quot;language-math math-inline&quot;&gt;s_{\mathrm{expanded}}\in\mathbb{R}^{B\times T_x\times d_s}&lt;/code&gt; 经过 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_a}}&lt;/code&gt; 后，形状变为 &lt;code class=&quot;language-math math-inline&quot;&gt;B\times T_x\times d_a&lt;/code&gt;，batch 和序列长度维度保持不变。&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import torch
import torch.nn as nn
import torch.nn.functional as F

class AdditiveAttention(nn.Module):
    def __init__(self, hidden_size, attention_dim):
        super().__init__()
        self.W_a = nn.Linear(hidden_size, attention_dim, bias=False)
        self.U_a = nn.Linear(hidden_size, attention_dim, bias=False)
        self.v_a = nn.Parameter(torch.randn(attention_dim))

    def forward(self, s_prev, h):
        # s_prev: (batch, hidden_size)
        # h:      (batch, source_length, hidden_size)
        source_length = h.size(1)
        s_expanded = s_prev.unsqueeze(1).expand(-1, source_length, -1)

        energy = torch.tanh(self.W_a(s_expanded) + self.U_a(h))
        scores = torch.matmul(energy, self.v_a)
        weights = F.softmax(scores, dim=-1)
        context = torch.bmm(weights.unsqueeze(1), h).squeeze(1)
        return context, weights
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;从 Additive Attention 到 Scaled Dot-Product Attention&lt;/h2&gt;
&lt;p&gt;Additive Attention 与 Scaled Dot-Product Attention 的整体流程没有改变，仍然是“评分、归一化、聚合”。变化主要发生在两处：参与计算的表示经过了更明确的投影，并且匹配分数换了一种计算方式。&lt;/p&gt;
&lt;p&gt;对单个 Decoder state 和 Encoder state，可以先建立下面的对应关系：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\underline{q}^T
= \underline{s_{i-1}}^T\underline{\underline{W_Q}},
\qquad
\underline{k_j}^T
= \underline{h_j}^T\underline{\underline{W_K}},
\qquad
\underline{v_j}^T
= \underline{h_j}^T\underline{\underline{W_V}}.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Query &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{q}&lt;/code&gt; 表示当前需要寻找什么，Key &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{k_j}&lt;/code&gt; 用来判断第 &lt;code class=&quot;language-math math-inline&quot;&gt;j&lt;/code&gt; 个位置是否匹配，Value &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{v_j}&lt;/code&gt; 则提供匹配后真正要聚合的内容。也就是说，Query 和 Key 负责计算注意力权重，Value 负责形成输出。&lt;/p&gt;
&lt;p&gt;Additive Attention 中，与 Query、Key 角色相近的两个中间 vector 分别是 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{q_{\mathrm{add}}}=\underline{\underline{W_a}}\underline{s_{i-1}}&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{k_{\mathrm{add},j}}=\underline{\underline{U_a}}\underline{h_j}&lt;/code&gt;，因此评分函数可以写成 &lt;code class=&quot;language-math math-inline&quot;&gt;e_{ij}=\underline{v_a}^T\tanh(\underline{q_{\mathrm{add}}}+\underline{k_{\mathrm{add},j}})&lt;/code&gt;。Scaled Dot-Product Attention 则使用上面定义的 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{q}&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{k_j}&lt;/code&gt;，把评分函数改为 &lt;code class=&quot;language-math math-inline&quot;&gt;e_{ij}=\underline{q}^T\underline{k_j}/\sqrt{d_k}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;得到注意力权重后，Additive Attention 聚合原始 Encoder state &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_j}&lt;/code&gt;，而 Transformer 聚合投影后的 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{v_j}&lt;/code&gt;。Value 投影使模型可以分别学习“用什么进行匹配”和“匹配后取出什么内容”。&lt;/p&gt;
&lt;p&gt;把一个序列中所有位置的 Query、Key 和 Value 分别堆叠起来，就得到下面使用的 matrix &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{Q}}&lt;/code&gt;、&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{K}}&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{V}}&lt;/code&gt;。在 Transformer 的 self-attention 中，它们通常都由同一个输入序列 matrix &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{X}}&lt;/code&gt; 投影得到。&lt;/p&gt;
&lt;p&gt;这里把单个 token 的表示写成 row vector，因此使用 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{q}^T=\underline{s_{i-1}}^T\underline{\underline{W_Q}}&lt;/code&gt;。把所有 token 的 row vector 堆叠成 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{X}}&lt;/code&gt; 后，就得到 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{Q}}=\underline{\underline{X}}\underline{\underline{W_Q}}&lt;/code&gt;。如果改用 column vector 约定，同一个投影应写成 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{q}=\underline{\underline{W_Q}}^T\underline{s_{i-1}}&lt;/code&gt;。&lt;/p&gt;
&lt;h2&gt;Scaled Dot-Product Attention&lt;/h2&gt;
&lt;p&gt;Transformer 在 2017 年的 &lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;&lt;em&gt;Attention Is All You Need&lt;/em&gt;&lt;/a&gt; 中使用 Query、Key 和 Value 表示注意力计算。对输入序列矩阵 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{X}}&lt;/code&gt;：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\underline{\underline{Q}}
= \underline{\underline{X}}\underline{\underline{W_Q}},
\qquad
\underline{\underline{K}}
= \underline{\underline{X}}\underline{\underline{W_K}},
\qquad
\underline{\underline{V}}
= \underline{\underline{X}}\underline{\underline{W_V}}.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;对单个注意力头，暂时省略 batch 维度。若序列长度为 &lt;code class=&quot;language-math math-inline&quot;&gt;n&lt;/code&gt;，则各 matrix 的形状为：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\begin{aligned}
\underline{\underline{X}}
&amp;#x26;\in\mathbb{R}^{n\times d_{model}}, \\
\underline{\underline{W_Q}},
\underline{\underline{W_K}}
&amp;#x26;\in\mathbb{R}^{d_{model}\times d_k}, \\
\underline{\underline{W_V}}
&amp;#x26;\in\mathbb{R}^{d_{model}\times d_v}, \\
\underline{\underline{Q}},
\underline{\underline{K}}
&amp;#x26;\in\mathbb{R}^{n\times d_k}, \\
\underline{\underline{V}}
&amp;#x26;\in\mathbb{R}^{n\times d_v}.
\end{aligned}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;其中 &lt;code class=&quot;language-math math-inline&quot;&gt;d_{model}&lt;/code&gt; 是每个 token 表示的维度。它既决定输入 embedding 的宽度，也影响后续投影 matrix 的形状和模型参数量。&lt;code class=&quot;language-math math-inline&quot;&gt;d_k&lt;/code&gt; 是每个 Query、Key 的维度，&lt;code class=&quot;language-math math-inline&quot;&gt;d_v&lt;/code&gt; 是每个 Value 的维度。&lt;/p&gt;
&lt;p&gt;Query 和 Key 决定“关注哪里”，Value 提供被聚合的内容。单个注意力头的计算为：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\operatorname{Attention}\left(
\underline{\underline{Q}},
\underline{\underline{K}},
\underline{\underline{V}}
\right)
= \operatorname{softmax}\left(
\frac{
\underline{\underline{Q}}\,
\underline{\underline{K}}^T
}{\sqrt{d_k}}
\right)
\underline{\underline{V}}.&lt;/code&gt;&lt;/pre&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;维度记号：&lt;/strong&gt; &lt;code class=&quot;language-math math-inline&quot;&gt;d_k&lt;/code&gt; 是每个 Query 和 Key 向量的维度，也就是点积中相加项的数量。从这里开始，后文中的 &lt;code class=&quot;language-math math-inline&quot;&gt;d_x&lt;/code&gt; 均表示向量 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{x}&lt;/code&gt; 的维度。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;为什么要缩放点积&lt;/h3&gt;
&lt;p&gt;假设 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{q},\underline{k}\in\mathbb{R}^{d_k}&lt;/code&gt;，并且各分量相互独立且服从标准正态分布，即 &lt;code class=&quot;language-math math-inline&quot;&gt;q_i,k_i\overset{\mathrm{i.i.d.}}{\sim}\mathcal{N}(0,1)&lt;/code&gt;。先看点积中的单项：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\begin{aligned}
\mathbb{E}[q_i k_i]
&amp;#x26;= \mathbb{E}[q_i]\mathbb{E}[k_i]
= 0, \\
\operatorname{Var}(q_i k_i)
&amp;#x26;= \mathbb{E}\left[(q_i k_i)^2\right]
- \mathbb{E}[q_i k_i]^2 \\
&amp;#x26;= \mathbb{E}[q_i^2]\mathbb{E}[k_i^2]
= 1.
\end{aligned}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;因此，整个点积的期望与方差为：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\begin{aligned}
\mathbb{E}[\underline{q}\cdot\underline{k}]
&amp;#x26;= \sum_{i=1}^{d_k}\mathbb{E}[q_i k_i]
= 0, \\
\operatorname{Var}(\underline{q}\cdot\underline{k})
&amp;#x26;= \sum_{i=1}^{d_k}\operatorname{Var}(q_i k_i)
= d_k.
\end{aligned}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;因此点积的标准差会随维度按 &lt;code class=&quot;language-math math-inline&quot;&gt;\sqrt{d_k}&lt;/code&gt; 增长。除以 &lt;code class=&quot;language-math math-inline&quot;&gt;\sqrt{d_k}&lt;/code&gt; 后，分数的数值范围更加稳定。如果省略缩放，较大的点积容易让 softmax 输出接近 one-hot，使梯度集中在少数高分位置，其他路径难以得到有效更新。&lt;/p&gt;
&lt;h3&gt;使用 Value 聚合&lt;/h3&gt;
&lt;p&gt;对第 &lt;code class=&quot;language-math math-inline&quot;&gt;i&lt;/code&gt; 个 Query，softmax 产生它对所有 Key 的注意力权重 &lt;code class=&quot;language-math math-inline&quot;&gt;\alpha_{ij}&lt;/code&gt;。随后使用这些权重聚合对应的 Value：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\underline{o_i}
= \sum_{j=1}^{n}\alpha_{ij}\underline{v_j}.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;这与 Additive Attention 中的 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{c_i}=\sum_j\alpha_{ij}\underline{h_j}&lt;/code&gt; 直接对应。主要区别是 Transformer 聚合经过投影的 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{v_j}&lt;/code&gt;，而不是直接聚合 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h_j}&lt;/code&gt;。&lt;/p&gt;
&lt;h2&gt;Multi-Head Attention&lt;/h2&gt;
&lt;p&gt;多头注意力将 &lt;code class=&quot;language-math math-inline&quot;&gt;d_{model}&lt;/code&gt; 维表示拆成 &lt;code class=&quot;language-math math-inline&quot;&gt;h&lt;/code&gt; 个头。常见配置是：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;d_k = d_v = \frac{d_{model}}{h}.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;每个头分别计算注意力，再拼接并投影回模型维度：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\begin{aligned}
\underline{\underline{\operatorname{head}_i}}
&amp;#x26;= \operatorname{Attention}\left(
\underline{\underline{Q_i}},
\underline{\underline{K_i}},
\underline{\underline{V_i}}
\right), \\
\operatorname{MultiHead}\left(
\underline{\underline{Q}},
\underline{\underline{K}},
\underline{\underline{V}}
\right)
&amp;#x26;= \operatorname{Concat}\left(
\underline{\underline{\operatorname{head}_1}},
\ldots,
\underline{\underline{\operatorname{head}_h}}
\right)
\underline{\underline{W_O}}.
\end{aligned}&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;从单头到多头的维度变化&lt;/h3&gt;
&lt;p&gt;原 notebook 还逐步检查了 score、注意力权重、单头输出、拼接结果和最终输出的形状。省略 batch 维度时，这条计算链可以写成：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\begin{aligned}
\underline{\underline{S_i}}
&amp;#x26;= \frac{
\underline{\underline{Q_i}}
\underline{\underline{K_i}}^T
}{\sqrt{d_k}}
\in\mathbb{R}^{n\times n}, \\
\underline{\underline{A_i}}
&amp;#x26;= \operatorname{softmax}\left(
\underline{\underline{S_i}}
\right)
\in\mathbb{R}^{n\times n}, \\
\underline{\underline{\operatorname{head}_i}}
&amp;#x26;= \underline{\underline{A_i}}
\underline{\underline{V_i}}
\in\mathbb{R}^{n\times d_v}, \\
\underline{\underline{C}}
&amp;#x26;= \operatorname{Concat}\left(
\underline{\underline{\operatorname{head}_1}},
\ldots,
\underline{\underline{\operatorname{head}_h}}
\right)
\in\mathbb{R}^{n\times(hd_v)}, \\
\underline{\underline{W_O}}
&amp;#x26;\in\mathbb{R}^{(hd_v)\times d_{model}}, \\
\underline{\underline{O}}
&amp;#x26;= \underline{\underline{C}}
\underline{\underline{W_O}}
\in\mathbb{R}^{n\times d_{model}}.
\end{aligned}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;当 &lt;code class=&quot;language-math math-inline&quot;&gt;d_k=d_v=d_{model}/h&lt;/code&gt; 时，&lt;code class=&quot;language-math math-inline&quot;&gt;hd_v=d_{model}&lt;/code&gt;，所以拼接后的宽度回到模型维度。加入 batch 维度并拆分 heads 后，主要张量形状如下：&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;张量&lt;/th&gt;
&lt;th&gt;形状&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;输入 &lt;code class=&quot;language-math math-inline&quot;&gt;X&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;(B,n,d_{model})&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;分头后的 &lt;code class=&quot;language-math math-inline&quot;&gt;Q,K&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;(B,h,n,d_k)&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;分头后的 &lt;code class=&quot;language-math math-inline&quot;&gt;V&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;(B,h,n,d_v)&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;注意力分数与权重&lt;/td&gt;
&lt;td&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;(B,h,n,n)&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;各头的上下文&lt;/td&gt;
&lt;td&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;(B,h,n,d_v)&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;最终输出&lt;/td&gt;
&lt;td&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;(B,n,d_{model})&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2&gt;Mask&lt;/h2&gt;
&lt;p&gt;注意力分数在 softmax 之前加入 mask。被遮蔽位置设为负无穷，softmax 后其权重为零。&lt;/p&gt;
&lt;h3&gt;Padding mask&lt;/h3&gt;
&lt;p&gt;Padding mask 阻止模型关注补齐 token。若 mask 形状为 &lt;code class=&quot;language-math math-inline&quot;&gt;(B,n)&lt;/code&gt;，扩展为 &lt;code class=&quot;language-math math-inline&quot;&gt;(B,1,1,n)&lt;/code&gt; 后即可广播到所有注意力头和查询位置：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;mask = padding_mask[:, None, None, :]
scores = scores.masked_fill(mask.bool(), float(&quot;-inf&quot;))
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Causal mask&lt;/h3&gt;
&lt;p&gt;自回归解码要求第 &lt;code class=&quot;language-math math-inline&quot;&gt;t&lt;/code&gt; 个位置只能看到不晚于自己的 token。上三角位置需要被遮蔽：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;[[0, -inf, -inf],
 [0,    0, -inf],
 [0,    0,    0]]
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;causal = torch.triu(
    torch.ones(seq_len, seq_len, device=scores.device, dtype=torch.bool),
    diagonal=1,
)
scores = scores.masked_fill(causal[None, None, :, :], float(&quot;-inf&quot;))
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;完整 PyTorch 实现&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import math
import torch
import torch.nn as nn
import torch.nn.functional as F

class MultiHeadAttention(nn.Module):
    def __init__(self, d_model, num_heads):
        super().__init__()
        if d_model % num_heads != 0:
            raise ValueError(&quot;d_model must be divisible by num_heads&quot;)

        self.d_model = d_model
        self.num_heads = num_heads
        self.d_k = d_model // num_heads
        self.W_q = nn.Linear(d_model, d_model)
        self.W_k = nn.Linear(d_model, d_model)
        self.W_v = nn.Linear(d_model, d_model)
        self.W_o = nn.Linear(d_model, d_model)

    def forward(
        self,
        query,
        key=None,
        value=None,
        padding_mask=None,
        causal=False,
    ):
        key = query if key is None else key
        value = key if value is None else value

        batch_size, query_len, _ = query.shape
        key_len = key.size(1)
        if value.size(1) != key_len:
            raise ValueError(&quot;key and value must have the same sequence length&quot;)
        if causal and query_len != key_len:
            raise ValueError(&quot;causal attention requires equal query and key lengths&quot;)

        def split_heads(projection, seq_len):
            # Linear 一次生成所有 heads，再 reshape：
            # (B, n, d_model) -&gt; (B, n, h, d_k) -&gt; (B, h, n, d_k)
            return projection.view(
                batch_size, seq_len, self.num_heads, self.d_k
            ).transpose(1, 2)

        Q = split_heads(self.W_q(query), query_len)
        K = split_heads(self.W_k(key), key_len)
        V = split_heads(self.W_v(value), key_len)
        scores = Q @ K.transpose(-2, -1) / math.sqrt(self.d_k)

        if padding_mask is not None:
            scores = scores.masked_fill(
                padding_mask[:, None, None, :].bool(), float(&quot;-inf&quot;)
            )

        if causal:
            causal_mask = torch.triu(
                torch.ones(
                    query_len,
                    key_len,
                    device=query.device,
                    dtype=torch.bool,
                ),
                diagonal=1,
            )
            scores = scores.masked_fill(
                causal_mask[None, None, :, :], float(&quot;-inf&quot;)
            )

        weights = F.softmax(scores, dim=-1)
        context = weights @ V
        # transpose 后内存通常不连续，先调用 contiguous() 再 view
        context = context.transpose(1, 2).contiguous().view(
            batch_size, query_len, self.d_model
        )
        return self.W_o(context), weights
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;下面两张热力图来自原 notebook。第一张展示 causal mask 形成的下三角注意力，第二张还叠加了 padding mask，使后两个 Key 位置不可见。&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://heng-blog.pages.dev/_astro/causal-mask.BSH3m-qu_Z1U6wCJ.webp&quot; alt=&quot;Causal mask 下的注意力权重&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://heng-blog.pages.dev/_astro/causal-and-padding-mask.CEqW7MdA_Z1OUHmL.webp&quot; alt=&quot;Causal mask 与 padding mask 共同作用&quot;&gt;&lt;/p&gt;
&lt;h2&gt;小结&lt;/h2&gt;
&lt;p&gt;Additive Attention 与 Scaled Dot-Product Attention 使用不同的匹配函数，但都遵循“评分、归一化、聚合”三个步骤。Multi-Head Attention 进一步让模型在多个表示子空间中并行学习关系，而 mask 则把序列结构和有效长度约束注入注意力计算。&lt;/p&gt;</content:encoded><h:img src="https://heng-blog.pages.dev/images/social-card.svg"/><enclosure url="https://heng-blog.pages.dev/images/social-card.svg"/></item><item><title>LoRA的学习率 LoRA+: Efficient Low Rank Adaptation</title><link>https://heng-blog.pages.dev/blog/lora-plus</link><guid isPermaLink="true">https://heng-blog.pages.dev/blog/lora-plus</guid><description>从 LoRA 两个 low-rank matrix 的不对称训练出发，理解 LoRA+ 为什么为 A 和 B 设置不同的学习率。</description><pubDate>Tue, 28 Jul 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;LoRA 用 low-rank update 限制下游适配需要训练的参数；AdaLoRA 继续讨论有限的 rank 应该分配给哪些 matrix；QLoRA 则通过量化冻结的基础模型，进一步降低训练时的显存成本。&lt;/p&gt;
&lt;p&gt;LoRA+ 没有再改变 low-rank update 的结构，而是回到一个更基础、也更容易被忽略的问题：&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;LoRA 中的两个 matrix 扮演不同角色，初始化方式也不同，为什么训练时却默认使用相同的学习率？&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;它给出的答案非常简单：&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 不应该被当成完全对称的参数。LoRA+ 保留 LoRA 的参数量、计算图和推理方式，只让 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 使用比 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 更大的学习率。&lt;/p&gt;
&lt;h2&gt;LoRA+ 改了什么&lt;/h2&gt;
&lt;p&gt;LoRA 将一个权重 matrix 的更新写成 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}=\frac{\alpha}{r}\underline{\underline{B}}\underline{\underline{A}}&lt;/code&gt;。其中 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 先把输入投影到 &lt;code class=&quot;language-math math-inline&quot;&gt;r&lt;/code&gt; 维空间，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 再把它映射回输出空间。&lt;/p&gt;
&lt;p&gt;标准 LoRA 通常对两者使用同一个学习率，即 &lt;code class=&quot;language-math math-inline&quot;&gt;\eta_A=\eta_B=\eta&lt;/code&gt;。LoRA+ 将它改成 &lt;code class=&quot;language-math math-inline&quot;&gt;\eta_B=\lambda\eta_A&lt;/code&gt;，其中 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda&gt;1&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;实际使用时，只需要让 optimizer 为两组参数设置不同的学习率。&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 的形状没有改变，可训练参数数量没有改变，forward 也仍然计算 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}\underline{\underline{A}}\underline{x}&lt;/code&gt;。因此 LoRA+ 不是一种新的 low-rank parameterization，而是对 LoRA 优化方式的修正。&lt;/p&gt;
&lt;h2&gt;为什么相同的学习率不一定合理&lt;/h2&gt;
&lt;p&gt;在常见的 LoRA 初始化中，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 被随机初始化，而 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 从零开始。这样可以保证训练开始时 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}\underline{\underline{A}}=\underline{\underline{0}}&lt;/code&gt;，模型的初始输出仍然等于预训练模型的输出。&lt;/p&gt;
&lt;p&gt;但这个初始化也让两者从第一步开始就具有不同的训练行为。因为 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}=\underline{\underline{0}}&lt;/code&gt;，初始时 &lt;code class=&quot;language-math math-inline&quot;&gt;\frac{\partial\mathcal{L}}{\partial\underline{\underline{A}}}=\underline{\underline{0}}&lt;/code&gt;；而 &lt;code class=&quot;language-math math-inline&quot;&gt;\frac{\partial\mathcal{L}}{\partial\underline{\underline{B}}}&lt;/code&gt; 仍然可以通过非零的 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 得到 gradient。也就是说，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 会先开始变化，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 要等 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 离开零点后才真正参与训练。&lt;/p&gt;
&lt;p&gt;这种不对称并不只存在于第一步。两个 matrix 的形状相反，在 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}\underline{\underline{A}}\underline{x}&lt;/code&gt; 中承担的作用也不同：&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 决定保留哪些输入方向，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 决定这些方向怎样作用到输出。给它们相同的学习率，并不代表它们会以相近的速度改变模型输出。&lt;/p&gt;
&lt;h2&gt;理论分析最重要的结论&lt;/h2&gt;
&lt;p&gt;论文从模型宽度 &lt;code class=&quot;language-math math-inline&quot;&gt;n&lt;/code&gt; 不断增大的极限出发，要求由 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 更新产生的输出变化都保持在 &lt;code class=&quot;language-math math-inline&quot;&gt;\Theta(1)&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;这里的 &lt;code class=&quot;language-math math-inline&quot;&gt;\Theta(1)&lt;/code&gt; 不需要理解成某个固定数值。它表达的是：当模型越来越宽时，这一部分变化仍然具有实际作用，既不会趋近于零，也不会不断放大。论文把这种状态称为 efficient feature learning。&lt;/p&gt;
&lt;p&gt;分析得到的关键结论是：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;如果始终令 &lt;code class=&quot;language-math math-inline&quot;&gt;\eta_A=\eta_B&lt;/code&gt;，就无法让两个分支对模型输出的影响同时保持在 &lt;code class=&quot;language-math math-inline&quot;&gt;\Theta(1)&lt;/code&gt;；其中一个分支会在宽模型中变得相对不重要。&lt;/li&gt;
&lt;li&gt;将学习率分开后，这个冲突可以消失。在论文分析的尺度下，合适的关系是 &lt;code class=&quot;language-math math-inline&quot;&gt;\eta_A=\Theta(n^{-1})&lt;/code&gt;、&lt;code class=&quot;language-math math-inline&quot;&gt;\eta_B=\Theta(1)&lt;/code&gt;。&lt;/li&gt;
&lt;li&gt;因此模型宽度越大，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 的学习率相对 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 越大。这也是实际算法使用 &lt;code class=&quot;language-math math-inline&quot;&gt;\eta_B=\lambda\eta_A&lt;/code&gt; 且 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda&gt;1&lt;/code&gt; 的来源。&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;这个理论不是要给每个有限大小的模型算出唯一的 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda&lt;/code&gt;，而是说明一个方向性的结论：两个 matrix 需要不同的更新尺度，而且 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 应该更新得更快。&lt;/p&gt;
&lt;h2&gt;实验告诉我们什么&lt;/h2&gt;
&lt;p&gt;论文在 RoBERTa-base、GPT-2 和 Llama-7B 上进行了实验，任务包括 MNLI、QQP、SST-2、QNLI，以及用 flan-v2 训练后在 MMLU 上评估。&lt;/p&gt;
&lt;p&gt;最值得保留的不是某一组孤立的分数，而是以下几个整体结论：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;最优结果通常出现在 &lt;code class=&quot;language-math math-inline&quot;&gt;\eta_B&gt;\eta_A&lt;/code&gt; 的区域，而不是两者相等的位置。&lt;/li&gt;
&lt;li&gt;论文整体报告了约 &lt;code class=&quot;language-math math-inline&quot;&gt;1\%\text{--}2\%&lt;/code&gt; 的性能提升，以及最高约 &lt;code class=&quot;language-math math-inline&quot;&gt;2\times&lt;/code&gt; 的 fine-tuning speedup。&lt;/li&gt;
&lt;li&gt;这里的 speedup 主要表示模型用更少的训练 step 达到相同或更高的性能。LoRA+ 的单步计算量与 LoRA 基本相同，并不是每一个 step 本身快了两倍。&lt;/li&gt;
&lt;li&gt;任务需要的适配越明显，区分两个学习率通常越有价值；对于已经很容易适配的任务，相同学习率也可能接近最优。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;这说明 LoRA+ 并不会在所有任务上带来同样大小的提升。它修正的是 LoRA 的训练动力学，而一个任务是否真正需要这部分额外的 feature learning，仍然取决于模型与数据。&lt;/p&gt;
&lt;h2&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\lambda&lt;/code&gt; 应该怎样选择&lt;/h2&gt;
&lt;p&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\lambda&lt;/code&gt; 不是一个对所有模型都通用的常数。论文发现，它会受到模型、任务和初始化方式影响。&lt;/p&gt;
&lt;p&gt;在论文的实验中，RoBERTa 使用常见的“&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 随机初始化、&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 初始化为零”时，较好的比例大约落在 &lt;code class=&quot;language-math math-inline&quot;&gt;4\text{--}8&lt;/code&gt;；使用相反初始化时，比例可能增大到约 &lt;code class=&quot;language-math math-inline&quot;&gt;16&lt;/code&gt;。Llama 实验中的较优比例则大约在 &lt;code class=&quot;language-math math-inline&quot;&gt;2\text{--}4&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;因此，更稳妥的理解不是“LoRA+ 必须令 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda=16&lt;/code&gt;”，而是：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;先确定实现中哪一个 matrix 是 down projection、哪一个是 up projection；&lt;/li&gt;
&lt;li&gt;保持 &lt;code class=&quot;language-math math-inline&quot;&gt;\eta_B&gt;\eta_A&lt;/code&gt;，可以从 &lt;code class=&quot;language-math math-inline&quot;&gt;\{2,4,8,16\}&lt;/code&gt; 这样的倍数开始搜索；&lt;/li&gt;
&lt;li&gt;同时观察最终效果和收敛速度，不要只根据训练 loss 判断比例。&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;不同库可能对两个 adapter matrix 使用不同的命名或乘法顺序。本文沿用 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}=\underline{\underline{B}}\underline{\underline{A}}&lt;/code&gt;：&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 是 down projection，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 是 up projection。应用 LoRA+ 时，应该先确认实现中的对应关系，而不是只按变量名机械地放大学习率。&lt;/p&gt;
&lt;h2&gt;LoRA+ 在整个发展路径中的位置&lt;/h2&gt;
&lt;p&gt;LoRA 讨论的是 update 能否具有低 rank；AdaLoRA 讨论的是 rank budget 应该放在哪里；QLoRA 讨论的是冻结的基础模型应该怎样保存；LoRA+ 讨论的则是 low-rank factor 应该怎样被 optimizer 更新。&lt;/p&gt;
&lt;p&gt;所以 LoRA+ 的贡献并不是增加一种更复杂的 adapter，而是指出：即使 parameterization 已经选对了，不合适的优化尺度仍然可能浪费它的训练能力。&lt;/p&gt;
&lt;p&gt;从结构上看，它也可以和 QLoRA、AdaLoRA 等方法组合，因为它只改变 optimizer 对不同参数组使用的学习率。不过组合后最合适的 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda&lt;/code&gt; 仍然需要重新验证，不能直接假设原论文中的比例保持不变。&lt;/p&gt;
&lt;p&gt;LoRA+ 最终留下的 whole picture 很清楚：&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;low-rank update 的两个 factor 并不对称。让 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 比 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 学得更快，可以在不增加参数量和单步计算成本的前提下，更充分地利用 LoRA 已经拥有的训练能力。&lt;/p&gt;
&lt;/blockquote&gt;</content:encoded><h:img src="https://heng-blog.pages.dev/images/social-card.svg"/><enclosure url="https://heng-blog.pages.dev/images/social-card.svg"/></item><item><title>LoRA的秩与容量 AdaLoRA: Adaptive Budget Allocation</title><link>https://heng-blog.pages.dev/blog/adalora</link><guid isPermaLink="true">https://heng-blog.pages.dev/blog/adalora</guid><description>从 LoRA 的固定 rank 出发，理解 AdaLoRA 如何拆分 rank-1 component、估计重要性并动态分配 rank。</description><pubDate>Sat, 25 Jul 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;这一系列论文一直围绕同一个问题展开：下游任务究竟需要多少 degrees of freedom，以及这些有限的训练能力应该放在哪里。&lt;/p&gt;
&lt;p&gt;最开始，random subspace training 用固定随机投影 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\Delta\theta}=\underline{\underline{P}}\underline{z}&lt;/code&gt;，把训练限制在一个低维 subspace 中。SAID 在此基础上加入逐层 scaling，让不同层获得不同大小的更新。LoRA 又进一步把研究对象从整个模型的参数 vector 转向单个权重 matrix，用 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}=\underline{\underline{B}}\underline{\underline{A}}&lt;/code&gt; 直接限制更新的 rank。&lt;/p&gt;
&lt;p&gt;但 LoRA 通常会为所有目标 matrix 设置相同的 rank。这样虽然实现简单，却隐含了一个很强的假设：每个 module、每一层都需要相同的更新能力。&lt;/p&gt;
&lt;p&gt;AdaLoRA 接着追问：&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;在总 rank budget 固定时，能否根据不同 module 的重要性动态分配 rank？&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;从固定 rank 到动态分配&lt;/h2&gt;
&lt;p&gt;LoRA 把一个权重更新写成 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}=\underline{\underline{B}}\underline{\underline{A}}&lt;/code&gt;。如果每个目标 matrix 都使用相同的 rank &lt;code class=&quot;language-math math-inline&quot;&gt;r&lt;/code&gt;，那么 rank budget 就会被平均分配到所有位置。&lt;/p&gt;
&lt;p&gt;AdaLoRA 的实验观察是，不同 weight matrix 对下游任务的重要性并不相同。某些 module 增加训练能力会带来明显提升，另一些 module 即使获得更多参数，收益也很小。统一使用相同的 &lt;code class=&quot;language-math math-inline&quot;&gt;r&lt;/code&gt;，可能让不重要的 matrix 占用过多预算，同时限制真正重要的 matrix。&lt;/p&gt;
&lt;p&gt;因此，AdaLoRA 不再预先固定每个 matrix 最终保留多少 rank，而是在训练过程中估计各个更新方向的重要性，再把有限的总预算留给更重要的方向。&lt;/p&gt;
&lt;p&gt;这个区别也可以写成一个简单的 rank budget constraint。&lt;/p&gt;
&lt;p&gt;假设共有 &lt;code class=&quot;language-math math-inline&quot;&gt;m&lt;/code&gt; 个目标 matrix。在相同的最终总 rank budget 下：&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;LoRA：平均分配 rank&lt;/th&gt;
&lt;th&gt;AdaLoRA：动态分配 rank&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;r_1=r_2=\cdots=r_m=r&lt;/code&gt;，因此 &lt;code class=&quot;language-math math-inline&quot;&gt;\sum_{k=1}^{m}r_k=mr&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\sum_{k=1}^{m}r_k=mr&lt;/code&gt;，但不要求 &lt;code class=&quot;language-math math-inline&quot;&gt;r_1=r_2=\cdots=r_m&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;两边最终可以使用相同数量的 rank；区别在于 LoRA 预先固定每个 matrix 的 rank，而 AdaLoRA
根据训练中估计的重要性决定每个 &lt;code class=&quot;language-math math-inline&quot;&gt;r_k&lt;/code&gt;。&lt;/p&gt;
&lt;h2&gt;把 rank 拆成可以删除的单位&lt;/h2&gt;
&lt;p&gt;LoRA 的 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}\underline{\underline{A}}&lt;/code&gt; 已经限制了 rank，但其中不同方向并没有被显式分离。AdaLoRA 将更新重新参数化为类似 SVD 的形式：&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}=\underline{\underline{P}}\underline{\underline{\Lambda}}\underline{\underline{Q}}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;LoRA 的分解并不唯一。对于任意可逆 matrix &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{R}}&lt;/code&gt;，都有
&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}\underline{\underline{A}}=(\underline{\underline{B}}\underline{\underline{R}})(\underline{\underline{R}}^{-1}\underline{\underline{A}})&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;也就是说，同一个 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}&lt;/code&gt; 可以由许多组彼此混合的方向表示。因此，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt;
的第 &lt;code class=&quot;language-math math-inline&quot;&gt;i&lt;/code&gt; 列和 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 的第 &lt;code class=&quot;language-math math-inline&quot;&gt;i&lt;/code&gt; 行没有天然、稳定的对应关系，不能直接把它们当作一个具有独立身份的
rank 单位。若将这一对向量全部置零，它们也很难在后续训练中恢复。&lt;/p&gt;
&lt;p&gt;为了得到可以独立衡量、删除和重新激活的 rank 单位，AdaLoRA 在 LoRA 的 low-rank update 上引入了更明确的结构。&lt;/p&gt;
&lt;p&gt;其中 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{P}}\in\mathbb{R}^{d_1\times r}&lt;/code&gt;，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{Q}}\in\mathbb{R}^{r\times d_2}&lt;/code&gt;，而 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Lambda}}=\operatorname{diag}(\lambda_1,\ldots,\lambda_r)&lt;/code&gt; 是一个 diagonal matrix。&lt;/p&gt;
&lt;p&gt;把这个乘积展开，可以得到 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}=\sum_{i=1}^{r}\lambda_i\underline{p_i}\underline{q_i}^{T}&lt;/code&gt;。这里 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{p_i}&lt;/code&gt; 是 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{P}}&lt;/code&gt; 的第 &lt;code class=&quot;language-math math-inline&quot;&gt;i&lt;/code&gt; 列，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{q_i}^{T}&lt;/code&gt; 是 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{Q}}&lt;/code&gt; 的第 &lt;code class=&quot;language-math math-inline&quot;&gt;i&lt;/code&gt; 行，而 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda_i\underline{p_i}\underline{q_i}^{T}&lt;/code&gt; 是一个 rank-1 component。&lt;/p&gt;
&lt;p&gt;这样做的关键，是让一个 rank 对应一个可以单独控制的 singular triplet：&lt;code class=&quot;language-math math-inline&quot;&gt;(\underline{p_i},\lambda_i,\underline{q_i})&lt;/code&gt;。&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;当 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda_i&lt;/code&gt; 被保留时，对应的 rank-1 component 继续参与更新；&lt;/li&gt;
&lt;li&gt;当 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda_i&lt;/code&gt; 被置零时，这个 component 不再影响 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}&lt;/code&gt;；&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{p_i}&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{q_i}&lt;/code&gt; 仍然保留并继续更新，因此被错误移除的方向以后还有机会重新激活。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;这里改变的是 effective rank，而不是 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Lambda}}&lt;/code&gt; 的实际尺寸。训练过程中 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Lambda}}&lt;/code&gt; 始终保持同样的形状，AdaLoRA 只是用 mask 将部分 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda_i&lt;/code&gt; 置零；如果某个方向之后重新变得重要，对应的 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda_i&lt;/code&gt; 仍可再次参与更新。&lt;/p&gt;
&lt;p&gt;在理想的正交条件下，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}&lt;/code&gt; 的 rank 就等于非零 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda_i&lt;/code&gt; 的数量。于是，调整 rank 可以转化成一个更容易操作的问题：保留哪些 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda_i&lt;/code&gt;，又将哪些 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda_i&lt;/code&gt; 置零。&lt;/p&gt;
&lt;p&gt;AdaLoRA 并不是在每一步都对完整的 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}&lt;/code&gt; 计算一次精确 SVD。它直接训练 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{P}}&lt;/code&gt;、&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Lambda}}&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{Q}}&lt;/code&gt;，用这种 SVD-like parameterization 避免反复分解大型 matrix 的成本。&lt;/p&gt;
&lt;h2&gt;为什么需要 orthogonal regularization&lt;/h2&gt;
&lt;p&gt;如果不同 rank-1 component 学到了高度重复的方向，那么删除其中一个 component 时，&lt;code class=&quot;language-math math-inline&quot;&gt;\lambda_i&lt;/code&gt; 就不再是一个清楚、独立的 rank 开关。&lt;/p&gt;
&lt;p&gt;因此，AdaLoRA 希望 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{P}}&lt;/code&gt; 的列向量和 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{Q}}&lt;/code&gt; 的行向量分别保持近似 orthogonal，也就是 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{P}}^{T}\underline{\underline{P}}\approx\underline{\underline{I}}&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{Q}}\underline{\underline{Q}}^{T}\approx\underline{\underline{I}}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;对应的 regularization 是 &lt;code class=&quot;language-math math-inline&quot;&gt;R(\underline{\underline{P}},\underline{\underline{Q}})=\lVert\underline{\underline{P}}^{T}\underline{\underline{P}}-\underline{\underline{I}}\rVert_F^2+\lVert\underline{\underline{Q}}\underline{\underline{Q}}^{T}-\underline{\underline{I}}\rVert_F^2&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;训练目标因此变成 task loss 与 orthogonal regularization 的组合。这个约束减少不同方向之间的信息冗余，也让删除某个 singular triplet 时的变化更稳定。&lt;/p&gt;
&lt;h2&gt;怎样判断一个方向是否重要&lt;/h2&gt;
&lt;p&gt;现在的问题变成：AdaLoRA 应该保留哪个 singular triplet &lt;code class=&quot;language-math math-inline&quot;&gt;(\underline{p_i},\lambda_i,\underline{q_i})&lt;/code&gt;？&lt;/p&gt;
&lt;p&gt;论文先从单个可训练 scalar &lt;code class=&quot;language-math math-inline&quot;&gt;w&lt;/code&gt; 的 sensitivity 出发，用一阶 Taylor approximation 估计把它置零会怎样改变 loss。&lt;/p&gt;
&lt;p&gt;假设当前参数为 &lt;code class=&quot;language-math math-inline&quot;&gt;w&lt;/code&gt;。将它移除，就是把它从 &lt;code class=&quot;language-math math-inline&quot;&gt;w&lt;/code&gt; 变成 &lt;code class=&quot;language-math math-inline&quot;&gt;0&lt;/code&gt;，因此参数变化为
&lt;code class=&quot;language-math math-inline&quot;&gt;\Delta w=0-w=-w&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;在当前参数附近对 loss 做一阶 Taylor 展开，可得
&lt;code class=&quot;language-math math-inline&quot;&gt;\mathcal{L}(w+\Delta w)\approx\mathcal{L}(w)+\frac{\partial\mathcal{L}}{\partial w}\Delta
  w&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;因此，置零前后的 loss 变化近似为
&lt;code class=&quot;language-math math-inline&quot;&gt;\Delta\mathcal{L}=\mathcal{L}(w+\Delta w)-\mathcal{L}(w)\approx-w\frac{\partial\mathcal{L}}{\partial
  w}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;这里需要判断的是变化大小，而不是 loss 增减的方向，所以取绝对值：
&lt;code class=&quot;language-math math-inline&quot;&gt;|\Delta\mathcal{L}|\approx\left|w\frac{\partial\mathcal{L}}{\partial w}\right|&lt;/code&gt;。这就得到论文使用的
sensitivity。&lt;/p&gt;
&lt;p&gt;这个结果只是当前位置附近的一阶估计。它忽略了二阶及更高阶项，因此不等于真正将参数置零后重新计算得到的精确 loss
变化。&lt;/p&gt;
&lt;p&gt;因此，在训练步骤 &lt;code class=&quot;language-math math-inline&quot;&gt;t&lt;/code&gt;，可以用 &lt;code class=&quot;language-math math-inline&quot;&gt;S_t(w)=\left|w_t\frac{\partial\mathcal{L}_t}{\partial w_t}\right|&lt;/code&gt; 表示当前 sensitivity。这个值越大，说明把 &lt;code class=&quot;language-math math-inline&quot;&gt;w&lt;/code&gt; 置零预计会给 task loss 带来越大的变化。&lt;/p&gt;
&lt;p&gt;但单个 mini-batch 得到的 sensitivity 很容易受到采样噪声影响。AdaLoRA 使用 exponential moving average（EMA）对它进行平滑：&lt;code class=&quot;language-math math-inline&quot;&gt;\overline{S}_t(w)=\beta_1\overline{S}_{t-1}(w)+(1-\beta_1)S_t(w)&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;它还记录当前 sensitivity 偏离历史趋势的程度：&lt;code class=&quot;language-math math-inline&quot;&gt;U_t(w)=\beta_2U_{t-1}(w)+(1-\beta_2)\left|S_t(w)-\overline{S}_t(w)\right|&lt;/code&gt;。&lt;code class=&quot;language-math math-inline&quot;&gt;U_t(w)&lt;/code&gt; 越大，表示这个参数的重要性仍在明显变化，估计具有更高的 uncertainty。&lt;/p&gt;
&lt;p&gt;论文实验默认使用 &lt;code class=&quot;language-math math-inline&quot;&gt;\beta_1=\beta_2=0.85&lt;/code&gt;。其中 &lt;code class=&quot;language-math math-inline&quot;&gt;\beta_1&lt;/code&gt; 控制 sensitivity 的平滑程度，&lt;code class=&quot;language-math math-inline&quot;&gt;\beta_2&lt;/code&gt; 控制 uncertainty 的平滑程度；数值越接近 &lt;code class=&quot;language-math math-inline&quot;&gt;1&lt;/code&gt;，历史估计所占的比重越大。&lt;/p&gt;
&lt;p&gt;最终的 parameter-level importance score 是 &lt;code class=&quot;language-math math-inline&quot;&gt;I_t(w)=\overline{S}_t(w)U_t(w)&lt;/code&gt;。也就是说，一个参数既要持续表现出较高的 sensitivity，又要考虑它在近期训练中的变化，才会得到更高的 importance。&lt;/p&gt;
&lt;h2&gt;从 parameter importance 到 rank importance&lt;/h2&gt;
&lt;p&gt;一个 rank-1 component 不只包含 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda_i&lt;/code&gt;，还包含 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{p_i}&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{q_i}&lt;/code&gt;。因此，AdaLoRA 不应该只看 &lt;code class=&quot;language-math math-inline&quot;&gt;|\lambda_i|&lt;/code&gt;，而是同时聚合整个 singular triplet 中所有参数的 importance。&lt;/p&gt;
&lt;p&gt;对于第 &lt;code class=&quot;language-math math-inline&quot;&gt;k&lt;/code&gt; 个权重更新中的第 &lt;code class=&quot;language-math math-inline&quot;&gt;i&lt;/code&gt; 个 triplet，论文把 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda_{k,i}&lt;/code&gt; 的 importance、&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{P_k}}&lt;/code&gt; 第 &lt;code class=&quot;language-math math-inline&quot;&gt;i&lt;/code&gt; 列各元素的平均 importance，以及 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{Q_k}}&lt;/code&gt; 第 &lt;code class=&quot;language-math math-inline&quot;&gt;i&lt;/code&gt; 行各元素的平均 importance 相加，得到 triplet-level importance score。&lt;/p&gt;
&lt;p&gt;使用平均值而不是直接求和，是为了避免较大的 vector 仅仅因为包含更多参数就自然获得更高分数。得到所有 triplet 的分数后，AdaLoRA 会跨 module、跨 layer 进行全局排序，把较低分数对应的 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda_{k,i}&lt;/code&gt; 置零。&lt;/p&gt;
&lt;p&gt;这样，重要的 matrix 最后可以保留更多 singular triplet，也就是获得更高的 rank；不重要的 matrix 则逐渐失去 rank。rank allocation 不再由人工为每一层预先指定，而是在训练过程中由 importance estimation 决定。&lt;/p&gt;
&lt;p&gt;论文用 &lt;code class=&quot;language-math math-inline&quot;&gt;s(\cdot)&lt;/code&gt; 表示单个参数的 importance function。采用前文的 sensitivity 与 uncertainty
时，&lt;code class=&quot;language-math math-inline&quot;&gt;s^{(t)}(w)=\overline{S}_t(w)U_t(w)&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;对第 &lt;code class=&quot;language-math math-inline&quot;&gt;k&lt;/code&gt; 个 weight update 的第 &lt;code class=&quot;language-math math-inline&quot;&gt;i&lt;/code&gt; 个 singular triplet，原文的聚合公式为
&lt;code class=&quot;language-math math-inline&quot;&gt;S_{k,i}=s(\lambda_{k,i})+\frac{1}{d_1}\sum_{j=1}^{d_1}s(P_{k,ji})+\frac{1}{d_2}\sum_{j=1}^{d_2}s(Q_{k,ij})&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;第一项来自 singular value &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda_{k,i}&lt;/code&gt;，第二项是 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{P_k}}&lt;/code&gt; 第 &lt;code class=&quot;language-math math-inline&quot;&gt;i&lt;/code&gt;
列的平均 importance，第三项是 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{Q_k}}&lt;/code&gt; 第 &lt;code class=&quot;language-math math-inline&quot;&gt;i&lt;/code&gt; 行的平均 importance。两个
vector 都取平均值，因此 &lt;code class=&quot;language-math math-inline&quot;&gt;S_{k,i}&lt;/code&gt; 不会仅仅因为 vector 较长而变大。&lt;/p&gt;
&lt;h2&gt;预算怎样逐渐收缩&lt;/h2&gt;
&lt;p&gt;AdaLoRA 不会在训练开始时立即把 rank 降到目标值。它先使用一个略高于最终目标的初始预算，让不同方向都有机会参与训练；经过 warm-up 后，再按照 schedule 逐渐减少可保留的 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda_i&lt;/code&gt; 数量，直到达到目标预算；最后固定得到的 rank distribution，继续完成训练。&lt;/p&gt;
&lt;p&gt;这个过程让模型先探索哪些方向有用，再逐渐集中到重要方向上。与一开始就固定低 rank 相比，它减少了过早删除潜在重要方向的风险。&lt;/p&gt;
&lt;p&gt;设总训练步数为 &lt;code class=&quot;language-math math-inline&quot;&gt;T&lt;/code&gt;，initial warm-up 和 final fine-tuning 分别持续 &lt;code class=&quot;language-math math-inline&quot;&gt;t_i&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;t_f&lt;/code&gt; 步；初始与目标
budget 分别为 &lt;code class=&quot;language-math math-inline&quot;&gt;b^{(0)}&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;b^{(T)}&lt;/code&gt;。作者的官方实现使用下面的 cubic schedule：
&lt;code class=&quot;language-math math-inline&quot;&gt;b^{(t)}=\begin{cases}b^{(0)},&amp;#x26;0\leq t&amp;#x3C;t_i,\\b^{(T)}+\left(b^{(0)}-b^{(T)}\right)\left(1-\frac{t-t_i}{T-t_i-t_f}\right)^3,&amp;#x26;t_i\leq t&amp;#x3C;T-t_f,\\b^{(T)},&amp;#x26;T-t_f\leq t\leq T.\end{cases}&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;第一阶段不裁减 budget；第二阶段通过三次函数逐渐从 &lt;code class=&quot;language-math math-inline&quot;&gt;b^{(0)}&lt;/code&gt; 降到 &lt;code class=&quot;language-math math-inline&quot;&gt;b^{(T)}&lt;/code&gt;；最后 &lt;code class=&quot;language-math math-inline&quot;&gt;t_f&lt;/code&gt;
步固定目标 budget 和已经得到的 rank distribution。&lt;/p&gt;
&lt;p&gt;AdaLoRA 论文附录的印刷公式在第二段分子中写成了 &lt;code class=&quot;language-math math-inline&quot;&gt;t-t_i-t_f&lt;/code&gt;，但这样无法在两个阶段的边界处连续接上。作者官方代码实际使用
&lt;code class=&quot;language-math math-inline&quot;&gt;t-t_i&lt;/code&gt;，这里采用与代码和正文描述一致的形式。&lt;/p&gt;
&lt;h2&gt;实验如何验证这个故事&lt;/h2&gt;
&lt;h3&gt;不同位置确实需要不同的 rank&lt;/h3&gt;
&lt;p&gt;论文首先用一个控制实验检验“平均分配 rank 是否合理”。作者在 DeBERTaV3-base 上训练 MNLI-m，在总可训练参数固定为约 &lt;code class=&quot;language-math math-inline&quot;&gt;0.28&lt;/code&gt;M 的条件下，只改变 LoRA 被分配到哪些 weight matrix 或哪些 layer。&lt;/p&gt;
&lt;p&gt;当预算只分配给一种 matrix 时，结果如下：&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;获得 LoRA 的 matrix&lt;/th&gt;
&lt;th align=&quot;right&quot;&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_q}}&lt;/code&gt;&lt;/th&gt;
&lt;th align=&quot;right&quot;&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_k}}&lt;/code&gt;&lt;/th&gt;
&lt;th align=&quot;right&quot;&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_v}}&lt;/code&gt;&lt;/th&gt;
&lt;th align=&quot;right&quot;&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_o}}&lt;/code&gt;&lt;/th&gt;
&lt;th align=&quot;right&quot;&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_{f1}}}&lt;/code&gt;&lt;/th&gt;
&lt;th align=&quot;right&quot;&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_{f2}}}&lt;/code&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;MNLI-m accuracy&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;88.58&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;88.98&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;89.36&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;89.28&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;89.91&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;89.99&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;在这个实验中，把预算给 FFN 的 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_{f1}}}&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_{f2}}}&lt;/code&gt;，效果高于只给 attention projection。把 LoRA 同时用于一组连续 layer 中的所有 matrix 时，位置差异也很明显：&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;获得 LoRA 的 layer&lt;/th&gt;
&lt;th align=&quot;right&quot;&gt;1–3&lt;/th&gt;
&lt;th align=&quot;right&quot;&gt;4–6&lt;/th&gt;
&lt;th align=&quot;right&quot;&gt;7–9&lt;/th&gt;
&lt;th align=&quot;right&quot;&gt;10–12&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;MNLI-m accuracy&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;77.87&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;85.82&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;88.15&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;88.60&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;后几层明显比前几层更需要训练能力。这两个结果并不是说 FFN 或高层在所有任务中都一定最重要，而是说明统一 rank 隐含的“各处同等重要”假设并不可靠，因此应该让 allocation 随任务和训练过程决定。&lt;/p&gt;
&lt;h3&gt;主实验比较了什么&lt;/h3&gt;
&lt;p&gt;论文分别用 DeBERTaV3-base 测试 GLUE 和 SQuAD，用 BART-large 测试 XSum 与 CNN/DailyMail。比较对象包括 full fine-tuning、BitFit、Adapter 和 LoRA。为了避免只给 attention matrix 的实现选择影响结论，实验中的 LoRA 也被扩展到与 AdaLoRA 相同的一组目标 matrix。&lt;/p&gt;
&lt;p&gt;GLUE 实验把最终预算设为约 &lt;code class=&quot;language-math math-inline&quot;&gt;0.3&lt;/code&gt;M、&lt;code class=&quot;language-math math-inline&quot;&gt;0.6&lt;/code&gt;M 和 &lt;code class=&quot;language-math math-inline&quot;&gt;1.2&lt;/code&gt;M 个可训练参数；对应的 AdaLoRA 总 rank budget 分别为 &lt;code class=&quot;language-math math-inline&quot;&gt;144&lt;/code&gt;、&lt;code class=&quot;language-math math-inline&quot;&gt;288&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;576&lt;/code&gt;，初始预算是最终预算的 &lt;code class=&quot;language-math math-inline&quot;&gt;1.5&lt;/code&gt; 倍。也就是说，它先用较宽的搜索空间探索，再逐步收缩到与 baseline 接近的最终参数量。&lt;/p&gt;
&lt;p&gt;下面选取三个不同任务中的结果。每一行只能在本行内比较，因为 accuracy、F1 和 ROUGE-2 是不同指标：&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;任务与预算&lt;/th&gt;
&lt;th&gt;指标&lt;/th&gt;
&lt;th align=&quot;right&quot;&gt;LoRA&lt;/th&gt;
&lt;th align=&quot;right&quot;&gt;AdaLoRA&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;GLUE，约 &lt;code class=&quot;language-math math-inline&quot;&gt;0.3&lt;/code&gt;M 参数&lt;/td&gt;
&lt;td&gt;八个任务平均分&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;88.15&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;88.86&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;SQuAD v2.0，&lt;code class=&quot;language-math math-inline&quot;&gt;0.08\%&lt;/code&gt; 参数&lt;/td&gt;
&lt;td&gt;F1&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;87.5&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;88.7&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;XSum，&lt;code class=&quot;language-math math-inline&quot;&gt;1.10\%&lt;/code&gt; 参数&lt;/td&gt;
&lt;td&gt;ROUGE-2&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;20.20&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;21.13&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;这些结果支持的是一个相对具体的结论：在相近的最终参数预算下，动态决定各处保留多少 rank，通常比统一 rank 更有效。它们并不能单独证明所有 weight update 都天然具有某个唯一的低秩结构，也不能说明 AdaLoRA 在任意数据集上都会优于 LoRA。&lt;/p&gt;
&lt;h3&gt;消融实验验证了哪些设计&lt;/h3&gt;
&lt;p&gt;论文还分别移除了或替换了 AdaLoRA 的关键部分：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;直接对 LoRA 的 rank-1 doublet 做 structured pruning，整体上不如 SVD-like parameterization。例如在 &lt;code class=&quot;language-math math-inline&quot;&gt;0.08\%&lt;/code&gt; 参数预算的 CoLA 实验中，前者得分为 &lt;code class=&quot;language-math math-inline&quot;&gt;66.71&lt;/code&gt;，AdaLoRA 为 &lt;code class=&quot;language-math math-inline&quot;&gt;70.21&lt;/code&gt;；&lt;/li&gt;
&lt;li&gt;只看 sensitivity，或只按 &lt;code class=&quot;language-math math-inline&quot;&gt;|\lambda_i|&lt;/code&gt; 排序，都不如完整的 sensitivity 与 uncertainty 组合稳定，说明一次 mini-batch 上的梯度并不足以可靠决定一个方向是否应该被删除；&lt;/li&gt;
&lt;li&gt;只使用 SVD-like parameterization、但不做 adaptive allocation，虽然能改善 LoRA，却仍然达不到完整 AdaLoRA 的结果；&lt;/li&gt;
&lt;li&gt;去掉 orthogonal regularization 会使表现下降，说明“让每个 singular triplet 成为较独立的 rank 单位”确实是后续排序和删除成立的重要条件。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;最终得到的 rank distribution 也与最开始的控制实验相呼应：更多预算通常流向 FFN 和较高层。不过，这个分布是训练得到的结果，不应该被反过来写成所有模型都必须遵守的手工规则。&lt;/p&gt;
&lt;h3&gt;参数更少不等于训练更便宜&lt;/h3&gt;
&lt;p&gt;AdaLoRA 需要维护 importance 的 moving average、执行全局排序和 mask，还加入了 orthogonal regularization。因此，它的主要贡献是提高固定最终参数预算的使用效率，而不是让训练过程自动变得更快。&lt;/p&gt;
&lt;p&gt;论文报告，在单张 V100 上的比较中，AdaLoRA 的显存占用与 LoRA 接近，但训练时间增加约 &lt;code class=&quot;language-math math-inline&quot;&gt;11\%&lt;/code&gt;–&lt;code class=&quot;language-math math-inline&quot;&gt;16\%&lt;/code&gt;。例如 MNLI 的 &lt;code class=&quot;language-math math-inline&quot;&gt;0.08\%&lt;/code&gt; 参数设置中，LoRA 每个 epoch 约需 &lt;code class=&quot;language-math math-inline&quot;&gt;105&lt;/code&gt; 分钟，AdaLoRA 约需 &lt;code class=&quot;language-math math-inline&quot;&gt;116&lt;/code&gt; 分钟。这个开销换来的是更灵活的 rank allocation，以及同预算下通常更好的任务表现。&lt;/p&gt;
&lt;h2&gt;从 LoRA 到 AdaLoRA&lt;/h2&gt;
&lt;p&gt;LoRA 的问题是如何用 low-rank update 代替完整的 weight update；AdaLoRA 的问题则是，在 low-rank update 已经成立之后，有限的 rank 应该分配给哪些 matrix。&lt;/p&gt;
&lt;p&gt;它的推导路径可以概括为：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;把 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}&lt;/code&gt; 写成 SVD-like parameterization；&lt;/li&gt;
&lt;li&gt;将它拆成多个可以独立控制的 rank-1 component；&lt;/li&gt;
&lt;li&gt;用 sensitivity 和 uncertainty 估计每个 triplet 的 importance；&lt;/li&gt;
&lt;li&gt;在所有 layer 和 module 之间全局排序；&lt;/li&gt;
&lt;li&gt;逐渐将低重要性方向对应的 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda_i&lt;/code&gt; 置零。&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;这里还留下了一个值得继续追问的问题：AdaLoRA 把一个 singular triplet，也就是一个 rank，当作统一的预算单位；但对于不同形状的 matrix，一个 rank 实际对应的参数量是 &lt;code class=&quot;language-math math-inline&quot;&gt;d_1+d_2+1&lt;/code&gt;，成本并不相同。&lt;/p&gt;
&lt;p&gt;因此，“应该给哪个 matrix 更多 rank”之后，还有一个更精确的问题：“在真实参数成本固定时，不同 layer 的 capacity 应该如何分配？”这也是我继续阅读 &lt;em&gt;Layer-Wise Capacity Allocation for Low-Rank Vision-Language-Action Fine-Tuning Under Demonstration Budget Constraints&lt;/em&gt; 的原因。&lt;/p&gt;</content:encoded><h:img src="https://heng-blog.pages.dev/images/social-card.svg"/><enclosure url="https://heng-blog.pages.dev/images/social-card.svg"/></item><item><title>LoRA的显存成本 QLoRA: Efficient Finetuning of Quantized LLMs</title><link>https://heng-blog.pages.dev/blog/qlora</link><guid isPermaLink="true">https://heng-blog.pages.dev/blog/qlora</guid><description>从 LoRA 仍需保存完整基础模型的问题出发，理解 QLoRA 的 NF4、Double Quantization 与 Paged Optimizers。</description><pubDate>Sat, 25 Jul 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;LoRA 冻结预训练权重，只训练 low-rank update，因此显著减少了可训练参数、gradient 和 optimizer state 的数量。但“参数高效”并不等于“显存占用已经足够低”：即使 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_0}}&lt;/code&gt; 不参与更新，完整的基础模型仍然要放进显存，前向和反向计算也仍然需要经过它。&lt;/p&gt;
&lt;p&gt;QLoRA 接着追问：&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;能否把冻结的基础模型压缩到 4-bit，同时仍然通过它反向传播，将 gradient 传给 LoRA adapter？&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;QLoRA 将 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_0}}&lt;/code&gt; 以 4-bit 保存，使用时临时反量化到 BFloat16，再完成 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h}=\operatorname{dequant}(\underline{\underline{W_0^{\mathrm{NF4}}}})\underline{x}+\frac{\alpha}{r}\underline{\underline{B}}\underline{\underline{A}}\underline{x}&lt;/code&gt;。基础权重保持冻结，真正被 optimizer 更新的仍然只有 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;论文将自己的三个主要技术贡献概括为：4-bit NormalFloat（NF4）、Double Quantization 和 Paged Optimizers。&lt;/p&gt;
&lt;h2&gt;贡献一：4-bit NormalFloat（NF4）&lt;/h2&gt;
&lt;p&gt;量化要用有限的 bit pattern 表示连续数值。4-bit 只能提供 &lt;code class=&quot;language-math math-inline&quot;&gt;2^4=16&lt;/code&gt; 个离散值，因此关键问题不是“能否只用 4 bit”，而是这 16 个值应该放在哪里。&lt;/p&gt;
&lt;p&gt;预训练模型的权重通常近似服从以 &lt;code class=&quot;language-math math-inline&quot;&gt;0&lt;/code&gt; 为中心的正态分布：大部分权重集中在零附近，绝对值较大的权重较少。如果仍然均匀放置 16 个量化值，分布稀疏的两端会占用过多编码，零附近却没有足够精细的表示。&lt;/p&gt;
&lt;p&gt;NF4 根据标准正态分布的 quantile 选择 16 个候选值，使每个 quantization bin 在理论上包含相近数量的权重。于是，零附近的候选值更密集，尾部更稀疏，更符合权重本身的分布。&lt;/p&gt;
&lt;p&gt;具体使用时，QLoRA 先把每个 block 中的权重除以该 block 的绝对值最大值，将它们缩放到 &lt;code class=&quot;language-math math-inline&quot;&gt;[-1,1]&lt;/code&gt;，再映射到最近的 NF4 候选值。存储的是每个权重的 4-bit 编号，以及恢复这个 block 所需的 quantization constant。&lt;/p&gt;
&lt;p&gt;NF4 还需要精确表示 &lt;code class=&quot;language-math math-inline&quot;&gt;0&lt;/code&gt;。论文分别为负半轴选择 &lt;code class=&quot;language-math math-inline&quot;&gt;8&lt;/code&gt; 个 quantile 值、为正半轴选择 &lt;code class=&quot;language-math math-inline&quot;&gt;9&lt;/code&gt; 个 quantile 值，再删除两个集合中重复的一个 &lt;code class=&quot;language-math math-inline&quot;&gt;0&lt;/code&gt;，最终得到 &lt;code class=&quot;language-math math-inline&quot;&gt;8+9-1=16&lt;/code&gt; 个候选值。&lt;/p&gt;
&lt;p&gt;这里需要区分已有方法和论文贡献：block-wise quantization 并不是 QLoRA 首次提出的；QLoRA 的新贡献是为近似正态分布的预训练权重设计 NF4，并将它用于高精度的 4-bit fine-tuning。&lt;/p&gt;
&lt;h2&gt;贡献二：Double Quantization&lt;/h2&gt;
&lt;p&gt;4-bit 编号并不足以恢复权重。每个 block 还需要一个 quantization constant，记录这个 block 在量化前被缩放了多少。block 越小，局部量化通常越准确，但需要保存的 constant 也越多。&lt;/p&gt;
&lt;p&gt;QLoRA 的第一层量化每 &lt;code class=&quot;language-math math-inline&quot;&gt;64&lt;/code&gt; 个权重使用一个 FP32 constant，因此 constant 的平均成本是 &lt;code class=&quot;language-math math-inline&quot;&gt;32/64=0.5&lt;/code&gt; bit per parameter。Double Quantization 的做法，是把这些 constant 当作第二组待量化数据，再用 8-bit float 和 block size &lt;code class=&quot;language-math math-inline&quot;&gt;256&lt;/code&gt; 对它们进行量化。&lt;/p&gt;
&lt;p&gt;第二层量化后的平均成本变为 &lt;code class=&quot;language-math math-inline&quot;&gt;8/64+32/(64\times256)=0.127&lt;/code&gt; bit per parameter，因此比直接保存 FP32 constant 少 &lt;code class=&quot;language-math math-inline&quot;&gt;0.373&lt;/code&gt; bit per parameter。&lt;/p&gt;
&lt;p&gt;对于一个 &lt;code class=&quot;language-math math-inline&quot;&gt;30&lt;/code&gt;B 参数模型，理论节省量约为 &lt;code class=&quot;language-math math-inline&quot;&gt;30\times10^9\times0.373/8\approx1.40&lt;/code&gt; GB。它节省的不是 4-bit 权重本身，而是每个 block 附带的 quantization constant。&lt;/p&gt;
&lt;p&gt;由于第一层 constant 都是正数，QLoRA 在第二次量化前先减去它们的平均值，使数据分布移动到零的两侧，从而更充分地使用对称量化的正负编码；反量化时再把平均值加回来。&lt;/p&gt;
&lt;h2&gt;贡献三：Paged Optimizers&lt;/h2&gt;
&lt;p&gt;NF4 和 Double Quantization 减少的是训练期间长期存在的显存占用，但训练显存并不始终保持不变。处理较长序列或进行 gradient checkpointing 的重新计算时，显存可能短暂出现峰值。即使训练大部分时间只使用 &lt;code class=&quot;language-math math-inline&quot;&gt;22&lt;/code&gt; GB，某一步突然需要 &lt;code class=&quot;language-math math-inline&quot;&gt;25&lt;/code&gt; GB，在一张 &lt;code class=&quot;language-math math-inline&quot;&gt;24&lt;/code&gt; GB GPU 上仍然会发生 out-of-memory。&lt;/p&gt;
&lt;p&gt;Paged Optimizers 主要解决这种短时峰值，而不是进一步量化基础模型。它利用 NVIDIA Unified Memory，在 GPU 显存紧张时将部分 optimizer state page 移到 CPU RAM；需要执行参数更新时，再把相关 page 传回 GPU。&lt;/p&gt;
&lt;p&gt;以 Adam 为例，optimizer 通常需要为可训练参数保存 gradient 的一阶 moving average &lt;code class=&quot;language-math math-inline&quot;&gt;m_t&lt;/code&gt; 和平方 gradient 的 moving average &lt;code class=&quot;language-math math-inline&quot;&gt;v_t&lt;/code&gt;。QLoRA 只需要为 LoRA adapter 保存这些状态，不需要为冻结的 4-bit 基础权重保存；但当其他计算临时占用更多显存时，这些状态仍然可以作为可迁移的缓冲空间。&lt;/p&gt;
&lt;p&gt;因此，三项贡献解决的是三个不同位置的显存问题：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;NF4 用更适合权重分布的 4-bit 候选值压缩冻结的基础模型；&lt;/li&gt;
&lt;li&gt;Double Quantization 继续压缩第一层量化产生的 constant；&lt;/li&gt;
&lt;li&gt;Paged Optimizers 在显存峰值出现时，将 optimizer state 暂时迁移到 CPU。&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;QLoRA 没有改变 LoRA 对 weight update 的 low-rank 假设。它改变的是基础模型的保存与计算方式，使 LoRA 不只减少需要训练的参数，也能用于单张 GPU 无法以 16-bit 容纳的更大模型。&lt;/p&gt;</content:encoded><h:img src="https://heng-blog.pages.dev/images/social-card.svg"/><enclosure url="https://heng-blog.pages.dev/images/social-card.svg"/></item><item><title>LoRA: Low-Rank Adaptation</title><link>https://heng-blog.pages.dev/blog/lora</link><guid isPermaLink="true">https://heng-blog.pages.dev/blog/lora</guid><description>从 LoRA 的 low-rank update 出发，理解 rank 约束、训练与推理实现，以及它和 intrinsic dimension 的关系。</description><pubDate>Thu, 23 Jul 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;在第一篇论文中，我们讨论了 intrinsic dimension：模型虽然位于一个很大的参数空间中，但完成特定任务可能只需要很少的 degrees of freedom。random subspace training 使用一个固定的随机投影，把低维可训练参数映射回完整参数空间，从而测量任务真正需要的训练维度。&lt;/p&gt;
&lt;p&gt;第二篇论文继续讨论了如何使用 Sparse projection 和 Fastfood 降低随机投影的计算与存储成本，以及如何把 intrinsic dimension 用到预训练模型上。实验进一步表明：模型规模虽然很大，下游适配所需要的有效训练空间却可能很小。&lt;/p&gt;
&lt;p&gt;这自然带来一个新的问题：如果下游任务只需要少量有效的更新方向，那么这些方向能否直接反映在权重更新 matrix 的结构中？&lt;/p&gt;
&lt;p&gt;random subspace training 只能说明完整参数更新可能位于一个低维 subspace，并没有说明更新本身具有怎样的结构。LoRA 在此基础上提出了一个更具体、也更强的假设：对于某个权重矩阵 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_0}}&lt;/code&gt;，下游适配产生的更新 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}&lt;/code&gt; 可能只需要少量独立的输入—输出方向，因此具有较低的 intrinsic rank。&lt;/p&gt;
&lt;p&gt;如果这个假设成立，就可以让输入先经过一个 &lt;code class=&quot;language-math math-inline&quot;&gt;r&lt;/code&gt; 维瓶颈，再映射回输出空间，也就是令 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}=\underline{\underline{B}}\underline{\underline{A}}&lt;/code&gt;。这样 &lt;code class=&quot;language-math math-inline&quot;&gt;\operatorname{rank}(\underline{\underline{\Delta W}})\leq r&lt;/code&gt;，训练也不再需要直接学习完整的 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;这篇文章讨论论文 &lt;a href=&quot;https://arxiv.org/abs/2106.09685&quot;&gt;&lt;em&gt;LoRA: Low-Rank Adaptation of Large Language Models&lt;/em&gt;&lt;/a&gt;。论文的核心贡献，是把下游任务对权重矩阵的完整更新改写成两个小矩阵的乘积。训练时冻结预训练模型，只学习这个 low-rank update；推理时还可以把它合并回原始权重矩阵。&lt;/p&gt;
&lt;p&gt;本文先简要介绍论文解决的问题和主要贡献，然后重点讨论 LoRA 的具体实现：rank 是怎样被约束的，训练时 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt;、&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 如何参与前向计算和梯度更新，以及推理时如何加载或合并 adapter。&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;记号说明：&lt;/strong&gt; 本文用单下划线表示 vector，用双下划线表示 matrix；scalar 不加下划线。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;论文贡献与内容&lt;/h2&gt;
&lt;p&gt;对每一个下游任务做全量微调，需要训练并保存一套与原模型同样大的参数。Adapter 虽然只增加少量参数，但会在原网络中加入需要顺序执行的新模块；prefix tuning 则会占用一部分序列长度。&lt;/p&gt;
&lt;p&gt;LoRA 希望同时满足下面几个目标：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;冻结预训练参数，只训练少量新增参数；&lt;/li&gt;
&lt;li&gt;不在网络中加入额外的串行层；&lt;/li&gt;
&lt;li&gt;不占用输入 token；&lt;/li&gt;
&lt;li&gt;每个任务只保存很小的 adapter；&lt;/li&gt;
&lt;li&gt;合并 adapter 后不增加推理延迟。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;围绕这个目标，论文给出了 low-rank update 的具体参数化方法，并在 RoBERTa、DeBERTa、GPT-2 和 GPT-3 上与全量微调、Adapter 和 prefix-based 方法进行了比较。实验中，LoRA 使用更少的可训练参数，模型质量仍然可以达到或超过全量微调。论文还进一步分析了 LoRA 应该放在哪些权重矩阵、不同 rank 的效果，以及不同训练得到的主要更新方向是否重合。&lt;/p&gt;
&lt;p&gt;论文受到 intrinsic dimension 研究的启发：一个预训练模型虽然有大量参数，下游任务可能只需要少量有效的更新方向。但 LoRA 没有继续使用覆盖整个模型的 random subspace，而是提出一个新的经验假设：&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;下游适配产生的权重更新，可能具有较低的 intrinsic rank。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;这里需要先保留一个逻辑边界：low intrinsic dimension 并不能直接推出 low-rank weight update。LoRA 从前者获得启发，再通过实验验证后者是一种有效的参数化方法；它不是一个由 intrinsic dimension 推导出来的定理。&lt;/p&gt;
&lt;h2&gt;LoRA 的核心实现&lt;/h2&gt;
&lt;p&gt;考虑一个预训练线性层，其权重矩阵为 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_0}}\in\mathbb{R}^{d\times k}&lt;/code&gt;，输入为 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{x}\in\mathbb{R}^k&lt;/code&gt;，原始前向计算是 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h}=\underline{\underline{W_0}}\underline{x}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;全量微调会直接学习一个完整更新 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}\in\mathbb{R}^{d\times k}&lt;/code&gt;，使新的权重变为 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W}}=\underline{\underline{W_0}}+\underline{\underline{\Delta W}}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;LoRA 不直接训练 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}&lt;/code&gt;，而是令 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}=\underline{\underline{B}}\underline{\underline{A}}&lt;/code&gt;，其中 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}\in\mathbb{R}^{r\times k}&lt;/code&gt;、&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}\in\mathbb{R}^{d\times r}&lt;/code&gt;，并且 &lt;code class=&quot;language-math math-inline&quot;&gt;r\ll\min(d,k)&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;于是前向计算变为 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{h}=\underline{\underline{W_0}}\underline{x}+\frac{\alpha}{r}\underline{\underline{B}}\underline{\underline{A}}\underline{x}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;训练过程中：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_0}}&lt;/code&gt; 保持冻结；&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 是可训练参数；&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 使用高斯分布初始化；&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 初始化为零；&lt;/li&gt;
&lt;li&gt;因此训练开始时 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}\underline{\underline{A}}=0&lt;/code&gt;，模型与原始预训练模型完全相同。&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Rank 是怎样被约束的&lt;/h3&gt;
&lt;p&gt;LoRA 不需要在训练过程中反复计算 &lt;code class=&quot;language-math math-inline&quot;&gt;\operatorname{rank}(\underline{\underline{\Delta W}})&lt;/code&gt;，也没有给损失函数加入“rank 不得超过 &lt;code class=&quot;language-math math-inline&quot;&gt;r&lt;/code&gt;”的惩罚项。它直接通过因子分解限制可表示的更新。&lt;/p&gt;
&lt;p&gt;根据矩阵乘法的性质，&lt;code class=&quot;language-math math-inline&quot;&gt;\operatorname{rank}(\underline{\underline{B}}\underline{\underline{A}})\leq\min(\operatorname{rank}(\underline{\underline{B}}),\operatorname{rank}(\underline{\underline{A}}))\leq r&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;从计算路径看，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{x}\in\mathbb{R}^k&lt;/code&gt; 必须先经过 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt;，变成一个 &lt;code class=&quot;language-math math-inline&quot;&gt;r&lt;/code&gt; 维中间 vector，再经过 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 映射到 &lt;code class=&quot;language-math math-inline&quot;&gt;\mathbb{R}^d&lt;/code&gt;。所有更新都必须通过这个 &lt;code class=&quot;language-math math-inline&quot;&gt;r&lt;/code&gt; 维瓶颈，所以最多只能传递 &lt;code class=&quot;language-math math-inline&quot;&gt;r&lt;/code&gt; 个独立的输入—输出模式。&lt;/p&gt;
&lt;p&gt;还可以把乘积写成 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}\underline{\underline{A}}=\sum_{i=1}^r\underline{b_i}\underline{a_i}^T&lt;/code&gt;。每个 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{b_i}\underline{a_i}^T&lt;/code&gt; 都是 rank-&lt;code class=&quot;language-math math-inline&quot;&gt;1&lt;/code&gt; matrix，因此它们的和最多是 rank &lt;code class=&quot;language-math math-inline&quot;&gt;r&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;所以 &lt;code class=&quot;language-math math-inline&quot;&gt;r&lt;/code&gt; 是 rank 上限，而不是最终 rank 的保证值。即使设置 &lt;code class=&quot;language-math math-inline&quot;&gt;r=8&lt;/code&gt;，训练得到的更新也可能只有更低的 effective rank。&lt;/p&gt;
&lt;p&gt;完整更新需要训练 &lt;code class=&quot;language-math math-inline&quot;&gt;dk&lt;/code&gt; 个参数，LoRA 只需要训练 &lt;code class=&quot;language-math math-inline&quot;&gt;r(d+k)&lt;/code&gt; 个参数。例如当 &lt;code class=&quot;language-math math-inline&quot;&gt;d=k=4096&lt;/code&gt;、&lt;code class=&quot;language-math math-inline&quot;&gt;r=8&lt;/code&gt; 时，完整更新包含 &lt;code class=&quot;language-math math-inline&quot;&gt;16{,}777{,}216&lt;/code&gt; 个参数，而 LoRA 只需要 &lt;code class=&quot;language-math math-inline&quot;&gt;65{,}536&lt;/code&gt; 个参数。&lt;/p&gt;
&lt;p&gt;这里数的是矩阵中&lt;strong&gt;可训练标量参数&lt;/strong&gt;的数量。设原始权重矩阵及其完整更新为&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\underline{\underline{W_0}},\underline{\underline{\Delta W}}
\in\mathbb{R}^{d_{\text{out}}\times d_{\text{in}}}.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;矩阵有 &lt;code class=&quot;language-math math-inline&quot;&gt;d_{\text{out}}&lt;/code&gt; 行、&lt;code class=&quot;language-math math-inline&quot;&gt;d_{\text{in}}&lt;/code&gt; 列，因此直接全参数微调
&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}&lt;/code&gt; 需要训练&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;d_{\text{out}}d_{\text{in}}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;个标量参数。&lt;/p&gt;
&lt;p&gt;LoRA 不直接训练完整的 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}&lt;/code&gt;，而是令&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\underline{\underline{\Delta W}}
=\underline{\underline{B}}\underline{\underline{A}},
\qquad
\underline{\underline{B}}\in\mathbb{R}^{d_{\text{out}}\times r},
\qquad
\underline{\underline{A}}\in\mathbb{R}^{r\times d_{\text{in}}}.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;矩阵乘法会消去中间的 &lt;code class=&quot;language-math math-inline&quot;&gt;r&lt;/code&gt; 维，并恢复完整更新的形状：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\underbrace{(d_{\text{out}}\times r)}_{\underline{\underline{B}}}
\underbrace{(r\times d_{\text{in}})}_{\underline{\underline{A}}}
=
\underbrace{(d_{\text{out}}\times d_{\text{in}})}_{\underline{\underline{\Delta W}}}.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;例如：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\underbrace{
\begin{bmatrix}
2 &amp;#x26; 1 &amp;#x26; 3\\
4 &amp;#x26; 0 &amp;#x26; 2
\end{bmatrix}
}_{\underline{\underline{B}}\in\mathbb{R}^{2\times 3}}
\underbrace{
\begin{bmatrix}
5 &amp;#x26; 2\\
1 &amp;#x26; 4\\
3 &amp;#x26; 7
\end{bmatrix}
}_{\underline{\underline{A}}\in\mathbb{R}^{3\times 2}}
=
\underbrace{
\begin{bmatrix}
20 &amp;#x26; 29\\
26 &amp;#x26; 22
\end{bmatrix}
}_{\underline{\underline{B}}\underline{\underline{A}}\in\mathbb{R}^{2\times 2}}.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;其中左上角元素为&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;(\underline{\underline{B}}\underline{\underline{A}})_{11}
=(2\cdot5)+(1\cdot1)+(3\cdot3)=20.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;分别计数两个 LoRA 矩阵：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 有 &lt;code class=&quot;language-math math-inline&quot;&gt;d_{\text{out}}r&lt;/code&gt; 个参数；&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 有 &lt;code class=&quot;language-math math-inline&quot;&gt;rd_{\text{in}}&lt;/code&gt; 个参数。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;加起来就是&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;d_{\text{out}}r+rd_{\text{in}}
=r(d_{\text{out}}+d_{\text{in}}).&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;当 &lt;code class=&quot;language-math math-inline&quot;&gt;r\ll\min(d_{\text{out}},d_{\text{in}})&lt;/code&gt; 时，这远小于
&lt;code class=&quot;language-math math-inline&quot;&gt;d_{\text{out}}d_{\text{in}}&lt;/code&gt;。LoRA 因而减少的是可训练参数、梯度和 optimizer state；它并不会省略基础权重
&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_0}}&lt;/code&gt; 的前向计算。合并权重后也不会增加推理计算，但通常不会让基础模型本身推理得更快。&lt;/p&gt;
&lt;h3&gt;初始化以后，谁先开始学习&lt;/h3&gt;
&lt;p&gt;训练开始时 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}=0&lt;/code&gt;，所以 LoRA 分支的输出为零。暂时省略常数 scaling &lt;code class=&quot;language-math math-inline&quot;&gt;\alpha/r&lt;/code&gt;，设损失函数对 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}&lt;/code&gt; 的梯度为 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{G}}&lt;/code&gt;，则 &lt;code class=&quot;language-math math-inline&quot;&gt;\frac{\partial L}{\partial\underline{\underline{B}}}=\underline{\underline{G}}\underline{\underline{A}}^T&lt;/code&gt;，通常不为零；而 &lt;code class=&quot;language-math math-inline&quot;&gt;\frac{\partial L}{\partial\underline{\underline{A}}}=\underline{\underline{B}}^T\underline{\underline{G}}=0&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;因此第一步主要是 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 开始变化。等 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 不再为零后，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 也会收到梯度，随后两个 matrix 共同学习。&lt;/p&gt;
&lt;p&gt;可以把计算顺序直观地理解为：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 把输入映射到 &lt;code class=&quot;language-math math-inline&quot;&gt;r&lt;/code&gt; 维坐标；&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 把这 &lt;code class=&quot;language-math math-inline&quot;&gt;r&lt;/code&gt; 个坐标映射成输出修正。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;这是一种有用的计算直觉，但 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}\underline{\underline{A}}&lt;/code&gt; 的因子分解并不唯一，所以不应该把 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt; 的某一行或 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 的某一列解释成唯一确定的语义方向。&lt;/p&gt;
&lt;h3&gt;训练伪代码&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;class LoRALinear(nn.Module):
    def __init__(self, base_linear, rank, alpha):
        super().__init__()
        self.base = base_linear
        for parameter in self.base.parameters():
            parameter.requires_grad = False

        d_out, d_in = self.base.weight.shape
        self.A = nn.Parameter(torch.randn(rank, d_in))
        self.B = nn.Parameter(torch.zeros(d_out, rank))
        self.scale = alpha / rank

    def forward(self, x):
        original = self.base(x)
        update = (x @ self.A.T) @ self.B.T
        return original + self.scale * update
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;训练模型时，optimizer 只接收 LoRA 参数：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;model = load_pretrained_model()
freeze(model)
insert_lora(model, target_modules=[&quot;q_proj&quot;, &quot;v_proj&quot;])

optimizer = Adam(lora_parameters(model))

for batch in dataset:
    logits = model(batch.input)
    loss = cross_entropy(logits, batch.label)

    loss.backward()
    optimizer.step()
    optimizer.zero_grad()
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;原论文在大多数实验中把 LoRA 加到 self-attention 的 Query 和 Value projection 上，并冻结 MLP。LoRA 的参数化方法本身并不局限于这两个 matrix，也可以用于其他 dense layer。&lt;/p&gt;
&lt;h2&gt;推理时如何使用 LoRA&lt;/h2&gt;
&lt;h3&gt;动态加载 adapter&lt;/h3&gt;
&lt;p&gt;如果希望同一个基础模型快速切换不同任务，可以保留 LoRA 分支：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;original = W0(x)
update = B(A(x))
output = original + alpha / rank * update
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;这样只需切换很小的 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{A}}&lt;/code&gt;、&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt;，不必为每个任务重新加载一套完整模型。代价是前向计算中仍然存在一次额外的 low-rank 计算。&lt;/p&gt;
&lt;h3&gt;合并到原始权重&lt;/h3&gt;
&lt;p&gt;因为原分支和 LoRA 分支都是线性的，所以可以提前计算 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_{\mathrm{merged}}}}=\underline{\underline{W_0}}+\frac{\alpha}{r}\underline{\underline{B}}\underline{\underline{A}}&lt;/code&gt;。&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;with torch.no_grad():
    W0.weight += alpha / rank * (B @ A)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;合并后，推理仍然只执行普通 linear layer。LoRA 的优势是相对全量微调不会增加推理延迟，但 matrix 的形状没有变，因此它通常不会让基础模型的推理本身更快。&lt;/p&gt;
&lt;p&gt;合并也有代价：如果同一个 batch 中的样本需要使用不同的 adapter，就很难在一次普通 matrix multiplication 中同时完成。保留未合并的 LoRA 分支可以动态选择 adapter，但会重新引入额外计算和延迟。&lt;/p&gt;
&lt;h2&gt;论文的局限性&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;low-rank update 是由实验支持的经验假设，不是从 intrinsic dimension 严格推导出的结论；合适的 rank 会随模型、任务和目标 matrix 改变。&lt;/li&gt;
&lt;li&gt;原论文主要研究 Transformer 的 attention 权重，MLP、LayerNorm 和 bias 的系统性比较被留作后续工作。&lt;/li&gt;
&lt;li&gt;合并 LoRA 可以消除额外推理延迟，却不适合在同一个 batch 中为不同样本动态选择不同 adapter；不合并则需要接受额外计算。&lt;/li&gt;
&lt;li&gt;论文证明了 LoRA 是一种有效的 parameter-efficient training 方法，但没有证明所有下游任务的最优更新都一定是 low rank。&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;总结&lt;/h2&gt;
&lt;p&gt;LoRA 的实现可以压缩成一句话：冻结 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{W_0}}&lt;/code&gt;，训练满足 &lt;code class=&quot;language-math math-inline&quot;&gt;\operatorname{rank}(\underline{\underline{\Delta W}})\leq r&lt;/code&gt; 的 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Delta W}}=\underline{\underline{B}}\underline{\underline{A}}&lt;/code&gt;，再根据部署需求选择保留分支或合并权重。&lt;/p&gt;
&lt;p&gt;它与 intrinsic dimension 的联系主要是一种研究动机：两者都在追问下游训练究竟需要多少有效的 degrees of freedom。LoRA 的关键推进，是把这个问题落实成对每个权重更新 matrix 的 low-rank 结构约束，并给出了可以直接训练、保存和部署的实现。&lt;/p&gt;</content:encoded><h:img src="https://heng-blog.pages.dev/images/social-card.svg"/><enclosure url="https://heng-blog.pages.dev/images/social-card.svg"/></item><item><title>Before LoRA 2: Sparse Projection, Fastfood, and SAID</title><link>https://heng-blog.pages.dev/blog/before-lora-2</link><guid isPermaLink="true">https://heng-blog.pages.dev/blog/before-lora-2</guid><description>从 dense Gaussian projection 的存储问题出发，理解 Sparse projection、Fastfood 和 SAID。</description><pubDate>Wed, 22 Jul 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;上一篇讨论了 intrinsic dimension：我们把训练限制在一个低维随机子空间中，然后观察模型至少需要多少 degrees of freedom，才能达到 direct training 的 &lt;code class=&quot;language-math math-inline&quot;&gt;90\%&lt;/code&gt; 性能。&lt;/p&gt;
&lt;p&gt;构造这个子空间时，上一篇使用的是 dense Gaussian projection。它会产生一个 &lt;code class=&quot;language-math math-inline&quot;&gt;D\times d&lt;/code&gt; 的矩阵 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{P}}&lt;/code&gt;，其中 &lt;code class=&quot;language-math math-inline&quot;&gt;D&lt;/code&gt; 是完整模型的参数量，&lt;code class=&quot;language-math math-inline&quot;&gt;d&lt;/code&gt; 是低维空间的维度。&lt;/p&gt;
&lt;p&gt;这个矩阵很难存储。例如，当 &lt;code class=&quot;language-math math-inline&quot;&gt;d=100&lt;/code&gt; 时，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{P}}&lt;/code&gt; 中需要保存的标量数量就是原模型参数量的 &lt;code class=&quot;language-math math-inline&quot;&gt;100&lt;/code&gt; 倍。&lt;/p&gt;
&lt;h2&gt;两种高效的随机投影&lt;/h2&gt;
&lt;p&gt;原论文为 dense Gaussian projection 的存储和计算问题提供了两种近似方法：Sparse projection 和 Fastfood。&lt;/p&gt;
&lt;h3&gt;Sparse projection&lt;/h3&gt;
&lt;p&gt;Sparse projection 使用了一个很巧妙的办法来构造近似 orthogonal 的随机投影矩阵。它不再让 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{P}}&lt;/code&gt; 中的每个元素都非零，而是按照下面的分布独立采样：&lt;/p&gt;
&lt;p&gt;每个元素以 &lt;code class=&quot;language-math math-inline&quot;&gt;1/\sqrt D&lt;/code&gt; 的概率被设为非零。一旦被选中，它就以相同概率取正值或负值，并且正负值的绝对值相同；其余元素为 &lt;code class=&quot;language-math math-inline&quot;&gt;0&lt;/code&gt;。完成采样后，再把 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{P}}&lt;/code&gt; 的每一列归一化为单位长度。&lt;/p&gt;
&lt;p&gt;也就是说，每个元素非零的概率只有 &lt;code class=&quot;language-math math-inline&quot;&gt;1/\sqrt D&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;假设非零元素的绝对值为 &lt;code class=&quot;language-math math-inline&quot;&gt;a&lt;/code&gt;。由于正负取值的概率相同，&lt;code class=&quot;language-math math-inline&quot;&gt;\mathbb{E}[p_{ki}]=a\frac{1}{2\sqrt D}-a\frac{1}{2\sqrt D}=0&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;对于 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{P}}&lt;/code&gt; 中不同的两列 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{p_i},\underline{p_j}\in\mathbb{R}^D&lt;/code&gt;，它们的内积是 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{p_i}^T\underline{p_j}=\sum_{k=1}^D p_{ki}p_{kj}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;当 &lt;code class=&quot;language-math math-inline&quot;&gt;i\neq j&lt;/code&gt; 时，由于矩阵元素独立采样，&lt;code class=&quot;language-math math-inline&quot;&gt;\mathbb{E}[p_{ki}p_{kj}]=\mathbb{E}[p_{ki}]\mathbb{E}[p_{kj}]=0&lt;/code&gt;。因此，&lt;code class=&quot;language-math math-inline&quot;&gt;\mathbb{E}[\underline{p_i}^T\underline{p_j}]=\sum_{k=1}^D\mathbb{E}[p_{ki}p_{kj}]=0&lt;/code&gt;。不同列在期望意义下互相 orthogonal。&lt;/p&gt;
&lt;p&gt;完成随机采样后，再把每一列除以自己的长度，所以每个列向量都具有单位范数。不同列的内积则会在高维随机采样下接近 &lt;code class=&quot;language-math math-inline&quot;&gt;0&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;因此，虽然 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{P}}&lt;/code&gt; 高度稀疏，它的列向量仍然可以组成一组近似 orthonormal 的随机方向。这里不同列之间只是近似 orthogonal，并不是每次采样都严格正交。&lt;/p&gt;
&lt;p&gt;因为非零元素的密度是 &lt;code class=&quot;language-math math-inline&quot;&gt;1/\sqrt D&lt;/code&gt;，一个 &lt;code class=&quot;language-math math-inline&quot;&gt;D\times d&lt;/code&gt; 的矩阵平均只有 &lt;code class=&quot;language-math math-inline&quot;&gt;\sqrt D\,d&lt;/code&gt; 个非零元素。理论上，存储和计算 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{P}}\underline{z}&lt;/code&gt; 的复杂度都可以从 &lt;code class=&quot;language-math math-inline&quot;&gt;O(Dd)&lt;/code&gt; 降到 &lt;code class=&quot;language-math math-inline&quot;&gt;O(\sqrt D\,d)&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;但是，这种方法并没有像预期一样在实际实现中降低那么多计算量。原论文使用 TensorFlow &lt;code&gt;SparseTensor&lt;/code&gt; 时，实际加速更接近固定的十倍，而没有达到理论上的 &lt;code class=&quot;language-math math-inline&quot;&gt;\sqrt D&lt;/code&gt; 倍。稀疏矩阵中的索引也会占用额外内存，所以它仍然不容易扩展到更大的模型。&lt;/p&gt;
&lt;h3&gt;Fastfood&lt;/h3&gt;
&lt;p&gt;Fastfood 的想法是不显式构造 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{P}}&lt;/code&gt;，而是用一组结构简单、计算便宜的矩阵，近似一个 dense Gaussian random matrix。&lt;/p&gt;
&lt;p&gt;一个 Fastfood 变换可以写成 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{M}}=\underline{\underline{H}}\underline{\underline{G}}\underline{\underline{\Pi}}\underline{\underline{H}}\underline{\underline{B}}&lt;/code&gt;，其中：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}=\operatorname{diag}(\pm1)&lt;/code&gt;，负责随机改变每个坐标的符号；&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{H}}&lt;/code&gt; 是 Hadamard 矩阵；&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Pi}}&lt;/code&gt; 是随机排列矩阵；&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{G}}=\operatorname{diag}(g_1,\ldots,g_d)&lt;/code&gt;，其中 &lt;code class=&quot;language-math math-inline&quot;&gt;g_i\sim\mathcal{N}(0,1)&lt;/code&gt;，负责加入 Gaussian scaling。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;它的过程可以按从右到左理解。&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt; 先随机改变输入坐标的符号，第一个 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{H}}&lt;/code&gt; 对所有坐标进行混合，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Pi}}&lt;/code&gt; 再打乱坐标的对应关系，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{G}}&lt;/code&gt; 加入随机幅度，最后一个 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{H}}&lt;/code&gt; 再进行一次混合。&lt;/p&gt;
&lt;p&gt;Hadamard 矩阵满足 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{H}}\underline{\underline{H}}^T=d\underline{\underline{I}}&lt;/code&gt;。因此，归一化后的矩阵 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\widehat{H}}}=\frac{1}{\sqrt d}\underline{\underline{H}}&lt;/code&gt; 满足 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\widehat{H}}}\underline{\underline{\widehat{H}}}^T=\underline{\underline{I}}&lt;/code&gt;，同时也满足 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\widehat{H}}}^T\underline{\underline{\widehat{H}}}=\underline{\underline{I}}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;对于任意向量 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{x}\in\mathbb{R}^d&lt;/code&gt;，令 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{y}=\underline{\underline{\widehat{H}}}\underline{x}&lt;/code&gt;，那么 &lt;code class=&quot;language-math math-inline&quot;&gt;\lVert\underline{y}\rVert_2^2=(\underline{\underline{\widehat{H}}}\underline{x})^T(\underline{\underline{\widehat{H}}}\underline{x})=\underline{x}^T\underline{\underline{\widehat{H}}}^T\underline{\underline{\widehat{H}}}\underline{x}=\underline{x}^T\underline{x}=\lVert\underline{x}\rVert_2^2&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;因此，归一化的 Hadamard transform 会保持向量长度。&lt;/p&gt;
&lt;p&gt;它不只是保持长度，还会把所有坐标混合起来。例如在二维情况下，&lt;code class=&quot;language-math math-inline&quot;&gt;\frac{1}{\sqrt2}\begin{bmatrix}1&amp;#x26;1\\1&amp;#x26;-1\end{bmatrix}\begin{bmatrix}x_1\\x_2\end{bmatrix}=\frac{1}{\sqrt2}\begin{bmatrix}x_1+x_2\\x_1-x_2\end{bmatrix}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;每个新坐标都是原始坐标的线性组合，所以 Hadamard transform 可以看作一种保持长度的全局信息混合。&lt;/p&gt;
&lt;p&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{B}}&lt;/code&gt;、归一化后的 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{H}}&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{\Pi}}&lt;/code&gt; 都保持 orthogonal 结构，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{G}}&lt;/code&gt; 则提供 Gaussian 随机性。把它们组合起来，就可以近似 dense Gaussian projection 的统计行为。&lt;/p&gt;
&lt;p&gt;更直观地说，Fastfood 就是用几个计算比较便宜的矩阵，完成随机符号变化、全局混合、随机排列和 Gaussian scaling，从而避免显式保存一个巨大的 dense matrix。&lt;/p&gt;
&lt;p&gt;Hadamard transform 可以通过 Fast Walsh–Hadamard Transform 计算。对于一个 &lt;code class=&quot;language-math math-inline&quot;&gt;d&lt;/code&gt; 维向量，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{H}}\underline{x}&lt;/code&gt; 的计算复杂度可以从 &lt;code class=&quot;language-math math-inline&quot;&gt;O(d^2)&lt;/code&gt; 降到 &lt;code class=&quot;language-math math-inline&quot;&gt;O(d\log d)&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;一个 Fastfood block 的输入和输出都是 &lt;code class=&quot;language-math math-inline&quot;&gt;d&lt;/code&gt; 维。如果完整模型有 &lt;code class=&quot;language-math math-inline&quot;&gt;D&gt;d&lt;/code&gt; 个参数，就堆叠大约 &lt;code class=&quot;language-math math-inline&quot;&gt;D/d&lt;/code&gt; 个独立的 block，把输出扩展到 &lt;code class=&quot;language-math math-inline&quot;&gt;D&lt;/code&gt; 维。这样，完整的 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{P}}\underline{z}&lt;/code&gt; 不需要保存 &lt;code class=&quot;language-math math-inline&quot;&gt;D\times d&lt;/code&gt; 个标量，只需要 &lt;code class=&quot;language-math math-inline&quot;&gt;O(D)&lt;/code&gt; 的存储，计算复杂度是 &lt;code class=&quot;language-math math-inline&quot;&gt;O(D\log d)&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;需要注意，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{H}}\underline{\underline{G}}\underline{\underline{\Pi}}\underline{\underline{H}}\underline{\underline{B}}&lt;/code&gt; 近似的是 Gaussian random matrix，而不是严格的 orthogonal matrix。因为 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{G}}&lt;/code&gt; 会随机缩放各个方向，所以整个变换本身不保持长度。&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;方法&lt;/th&gt;
&lt;th&gt;投影矩阵&lt;/th&gt;
&lt;th align=&quot;right&quot;&gt;存储复杂度&lt;/th&gt;
&lt;th align=&quot;right&quot;&gt;计算 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{P}}\underline{z}&lt;/code&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Dense Gaussian&lt;/td&gt;
&lt;td&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{P}}\in\mathbb{R}^{D\times d}&lt;/code&gt;&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;O(Dd)&lt;/code&gt;&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;O(Dd)&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Sparse projection&lt;/td&gt;
&lt;td&gt;非零密度为 &lt;code class=&quot;language-math math-inline&quot;&gt;1/\sqrt D&lt;/code&gt;&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;O(\sqrt D\,d)&lt;/code&gt;&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;O(\sqrt D\,d)&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Fastfood&lt;/td&gt;
&lt;td&gt;堆叠多个 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\underline{H}}\underline{\underline{G}}\underline{\underline{\Pi}}\underline{\underline{H}}\underline{\underline{B}}&lt;/code&gt;&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;O(D)&lt;/code&gt;&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;O(D\log d)&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2&gt;把 intrinsic dimension 用到预训练模型&lt;/h2&gt;
&lt;p&gt;有了 Fastfood 以后，就可以把 intrinsic dimension 的测量方法应用到参数量很大的预训练语言模型上。&lt;/p&gt;
&lt;p&gt;这篇论文提出了 Structure-Aware Intrinsic Dimension（SAID）。它想把 intrinsic dimension 的概念用到具有多层结构的网络上。&lt;/p&gt;
&lt;p&gt;论文把之前不考虑网络层结构的方法称为 Direct Intrinsic Dimension（DID）。DID 在整个模型中共享同一个低维随机投影向量，没有区分不同层可能承担的不同功能。&lt;/p&gt;
&lt;p&gt;SAID 在这个共享的低维向量上，为每一层增加一个可学习的缩放系数。记投影后属于第 &lt;code class=&quot;language-math math-inline&quot;&gt;i&lt;/code&gt; 层的参数更新为 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\delta_i}=[\underline{\underline{P}}(\underline{\theta^{d-m}})]_i&lt;/code&gt;，则这一层的参数可以写成 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\theta_i^D}=\underline{\theta_{0,i}^D}+\lambda_i\underline{\delta_i}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;其中，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\theta_{0,i}^D}&lt;/code&gt; 是 pretrained checkpoint 中第 &lt;code class=&quot;language-math math-inline&quot;&gt;i&lt;/code&gt; 层的初始参数，&lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\theta^{d-m}}&lt;/code&gt; 是共享的低维可训练参数，&lt;code class=&quot;language-math math-inline&quot;&gt;\lambda_i&lt;/code&gt; 是这一层自己的可学习缩放系数。&lt;/p&gt;
&lt;p&gt;这里的上标 &lt;code&gt;d-m&lt;/code&gt; 表示这个 vector 包含 &lt;code&gt;d-m&lt;/code&gt; 个参数，不是乘方。如果模型共有 &lt;code&gt;m&lt;/code&gt; 层，SAID 就需要额外训练 &lt;code&gt;m&lt;/code&gt; 个逐层 scaling，也就是每层一个 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda_i&lt;/code&gt;。为了让可训练参数总数仍然是 &lt;code&gt;d&lt;/code&gt;，论文从原来的 &lt;code&gt;d&lt;/code&gt; 个参数预算中拿出 &lt;code&gt;m&lt;/code&gt; 个位置保存这些 scaling，剩下的 &lt;code&gt;d-m&lt;/code&gt; 个位置才用于共享的低维参数。&lt;/p&gt;
&lt;p&gt;因此，SAID 实际训练的是 &lt;code&gt;d-m&lt;/code&gt; 个共享参数和 &lt;code&gt;m&lt;/code&gt; 个 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda_i&lt;/code&gt;，总数仍然是 &lt;code&gt;d&lt;/code&gt;。如果不减去这 &lt;code&gt;m&lt;/code&gt; 个位置，可训练参数总数就会变成 &lt;code&gt;d+m&lt;/code&gt;，无法再与 DID 在相同参数预算下直接比较。&lt;/p&gt;
&lt;p&gt;这样，不同层就可以获得不同大小的参数更新。某一层如果对当前任务更重要，可以学习更大的 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda_i&lt;/code&gt;；如果某一层不需要太多变化，也可以学习较小的 &lt;code class=&quot;language-math math-inline&quot;&gt;\lambda_i&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;论文使用 SAID 和 DID 做了一系列实验。在给出的数据集和模型上，SAID 的结果都不差于 DID，并且多数情况下可以在达到相同性能时使用更小的 intrinsic dimension。&lt;/p&gt;
&lt;h2&gt;这里测量的 &lt;code class=&quot;language-math math-inline&quot;&gt;d_{90}&lt;/code&gt; 是什么&lt;/h2&gt;
&lt;p&gt;这里的 intrinsic dimension 指的是预训练模型在某个下游任务上的微调维度。&lt;/p&gt;
&lt;p&gt;实验首先选择一个已经完成预训练的 checkpoint 作为参数起点 &lt;code class=&quot;language-math math-inline&quot;&gt;\underline{\theta_0}&lt;/code&gt;，并把它固定。随后指定一个候选维度 &lt;code class=&quot;language-math math-inline&quot;&gt;d&lt;/code&gt;，只训练低维参数；在 SAID 中，还会同时训练每一层对应的缩放系数。固定的 Fastfood projection 再把这些低维参数映射成完整模型的参数更新。&lt;/p&gt;
&lt;p&gt;对于每个候选 &lt;code class=&quot;language-math math-inline&quot;&gt;d&lt;/code&gt;，模型都会在具体的下游任务上重新进行一次低维微调，并把结果和标准 full fine-tuning 的性能进行比较。研究者不断改变 &lt;code class=&quot;language-math math-inline&quot;&gt;d&lt;/code&gt;，寻找能够达到 full fine-tuning 性能 &lt;code class=&quot;language-math math-inline&quot;&gt;90\%&lt;/code&gt; 的最小维度，并把它记为 &lt;code class=&quot;language-math math-inline&quot;&gt;d_{90}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;因此，&lt;code class=&quot;language-math math-inline&quot;&gt;d_{90}&lt;/code&gt; 表示的不是“训练出整个模型需要多少维”，而是“从当前 pretrained checkpoint 出发，为了适配某个下游任务，至少需要多少个有效的 trainable degrees of freedom”。&lt;/p&gt;
&lt;p&gt;它依赖 pretrained checkpoint、下游任务、随机投影、优化器和性能阈值，是一个实验得到的估计值，而不是模型本身固定不变的属性。&lt;/p&gt;</content:encoded><h:img src="https://heng-blog.pages.dev/images/social-card.svg"/><enclosure url="https://heng-blog.pages.dev/images/social-card.svg"/></item><item><title>Before LoRA: Measuring the Intrinsic Dimension</title><link>https://heng-blog.pages.dev/blog/before-lora-1</link><guid isPermaLink="true">https://heng-blog.pages.dev/blog/before-lora-1</guid><description>通过 random subspace training，理解完成一个任务所需的 degrees of freedom 为什么可能远低于模型参数量。</description><pubDate>Wed, 22 Jul 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;这篇文章讨论论文 &lt;a href=&quot;https://arxiv.org/abs/1804.08838&quot;&gt;&lt;em&gt;Measuring the Intrinsic Dimension of Objective Landscapes&lt;/em&gt;&lt;/a&gt;。这篇论文的主要目标不是提出现代意义上的 parameter-efficient training 方法，而是测量 objective landscape 的 intrinsic dimension。它通过实验说明：神经网络虽然拥有大量参数，完成一个任务所需的有效 degrees of freedom 却可能远低于参数总数。&lt;/p&gt;
&lt;h2&gt;论文想说明什么&lt;/h2&gt;
&lt;p&gt;论文主要论证的是：完成一个任务所需的有效 degrees of freedom，可能远低于模型的参数总数。&lt;/p&gt;
&lt;p&gt;在一个 &lt;code class=&quot;language-math math-inline&quot;&gt;D&lt;/code&gt; 维参数空间中，即使把优化限制在一个小得多的 &lt;code class=&quot;language-math math-inline&quot;&gt;d&lt;/code&gt; 维随机子空间中，模型仍然可能达到 direct training 基准性能的 &lt;code class=&quot;language-math math-inline&quot;&gt;90\%&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;一种几何直觉是：随着 &lt;code class=&quot;language-math math-inline&quot;&gt;d&lt;/code&gt; 增大，穿过初始化点的 random affine subspace 更有可能与完整参数空间中的 good-solution region 相交。虽然优化器只能在这个 random affine subspace 中移动，它仍然可能找到一个性能足够好的 parameter configuration。这是理解实验的直觉，而不是对一般非线性 objective landscape 的严格证明。&lt;/p&gt;
&lt;h2&gt;参数空间&lt;/h2&gt;
&lt;p&gt;假设一个模型有 &lt;code class=&quot;language-math math-inline&quot;&gt;D&lt;/code&gt; 个参数。把所有参数展开后，可以将它们看成一个 &lt;code class=&quot;language-math math-inline&quot;&gt;D&lt;/code&gt; 维向量：&lt;code class=&quot;language-math math-inline&quot;&gt;\theta \in \mathbb{R}^{D}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;所有可能的参数向量一起构成一个 &lt;code class=&quot;language-math math-inline&quot;&gt;D&lt;/code&gt; 维参数空间。训练的目标，就是在这个空间中找到一个最优点 &lt;code class=&quot;language-math math-inline&quot;&gt;\theta_{\mathrm{best}}&lt;/code&gt;，使损失函数 &lt;code class=&quot;language-math math-inline&quot;&gt;L(\theta_{\mathrm{best}})&lt;/code&gt; 尽可能小。&lt;/p&gt;
&lt;p&gt;Direct training 可以在完整的 &lt;code class=&quot;language-math math-inline&quot;&gt;D&lt;/code&gt; 维参数空间中移动，因此最多拥有 &lt;code class=&quot;language-math math-inline&quot;&gt;D&lt;/code&gt; 个可训练的 degrees of freedom。&lt;/p&gt;
&lt;h2&gt;Random subspace training&lt;/h2&gt;
&lt;p&gt;为了验证上面的猜想，论文不再直接训练全部 &lt;code class=&quot;language-math math-inline&quot;&gt;D&lt;/code&gt; 个参数，而是在 &lt;code class=&quot;language-math math-inline&quot;&gt;D&lt;/code&gt; 维空间中随机取出 &lt;code class=&quot;language-math math-inline&quot;&gt;d&lt;/code&gt; 个 &lt;code class=&quot;language-math math-inline&quot;&gt;D&lt;/code&gt; 维向量。&lt;/p&gt;
&lt;p&gt;这些向量通过 Gaussian distribution sampling 得到。只要 &lt;code class=&quot;language-math math-inline&quot;&gt;d\leq D&lt;/code&gt;，独立采样得到的 Gaussian 随机向量就以概率 1 linearly independent，因此它们张成一个 &lt;code class=&quot;language-math math-inline&quot;&gt;d&lt;/code&gt; 维子空间。在高维空间中，它们通常还近似 orthogonal。&lt;/p&gt;
&lt;p&gt;把这 &lt;code class=&quot;language-math math-inline&quot;&gt;d&lt;/code&gt; 个向量作为列排列起来，得到一个 &lt;code class=&quot;language-math math-inline&quot;&gt;D \times d&lt;/code&gt; 矩阵：&lt;code class=&quot;language-math math-inline&quot;&gt;P \in \mathbb{R}^{D \times d}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;设两个独立的 Gaussian 随机向量为 &lt;code class=&quot;language-math math-inline&quot;&gt;p_i,p_j \in \mathbb{R}^{D}&lt;/code&gt;。由于两个向量独立，并且每个坐标的均值都是 &lt;code class=&quot;language-math math-inline&quot;&gt;0&lt;/code&gt;，它们内积的期望也是 &lt;code class=&quot;language-math math-inline&quot;&gt;0&lt;/code&gt;：&lt;code class=&quot;language-math math-inline&quot;&gt;\mathbb{E}[p_i^T p_j]=0&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;归一化后，两个向量之间的余弦相似度为 &lt;code class=&quot;language-math math-inline&quot;&gt;\frac{p_i^T p_j}{\lVert p_i\rVert\lVert p_j\rVert}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;当 &lt;code class=&quot;language-math math-inline&quot;&gt;D&lt;/code&gt; 很大时，这个值会集中在 &lt;code class=&quot;language-math math-inline&quot;&gt;0&lt;/code&gt; 附近，其典型量级大约是 &lt;code class=&quot;language-math math-inline&quot;&gt;O(D^{-1/2})&lt;/code&gt;。因此，两个独立的高维 Gaussian 随机向量通常接近 orthogonal。&lt;/p&gt;
&lt;p&gt;这里说的是 approximately orthogonal，而不是 strictly orthogonal。独立性来自采样过程，不是高维空间的结果；在几何上更重要的是，当 &lt;code class=&quot;language-math math-inline&quot;&gt;d\leq D&lt;/code&gt; 时这些向量以概率 1 linearly independent。&lt;/p&gt;
&lt;h2&gt;训练方法&lt;/h2&gt;
&lt;p&gt;基准模型按照原来的方式进行 direct training，并记录它的基准性能。&lt;/p&gt;
&lt;p&gt;在 random subspace training 中，模型参数写成 &lt;code class=&quot;language-math math-inline&quot;&gt;\theta=\theta_0+Pz&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;其中：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\theta_0&lt;/code&gt; 是初始参数，并且在训练中保持固定；&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;P&lt;/code&gt; 是上面得到的随机投影矩阵，也保持固定；&lt;/li&gt;
&lt;li&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;z \in \mathbb{R}^{d}&lt;/code&gt; 是可训练参数，并被初始化为零，因此训练开始时 &lt;code class=&quot;language-math math-inline&quot;&gt;\theta=\theta_0&lt;/code&gt;。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;因此，优化器实际上只更新 &lt;code class=&quot;language-math math-inline&quot;&gt;z&lt;/code&gt;。当前参数相对于初始化点的位移为 &lt;code class=&quot;language-math math-inline&quot;&gt;\theta-\theta_0=Pz&lt;/code&gt;；如果表示第 &lt;code class=&quot;language-math math-inline&quot;&gt;t&lt;/code&gt; 次优化步骤，则有 &lt;code class=&quot;language-math math-inline&quot;&gt;\theta_t-\theta_{t-1}=P(z_t-z_{t-1})&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;虽然 &lt;code class=&quot;language-math math-inline&quot;&gt;\theta&lt;/code&gt; 仍然是一个 &lt;code class=&quot;language-math math-inline&quot;&gt;D&lt;/code&gt; 维向量，但只要 &lt;code class=&quot;language-math math-inline&quot;&gt;P&lt;/code&gt; full column rank，训练过程中真正可以独立控制的就只有 &lt;code class=&quot;language-math math-inline&quot;&gt;d&lt;/code&gt; 个坐标。也就是说，可训练的 degrees of freedom 从 &lt;code class=&quot;language-math math-inline&quot;&gt;D&lt;/code&gt; 降到了 &lt;code class=&quot;language-math math-inline&quot;&gt;d&lt;/code&gt;。&lt;/p&gt;
&lt;h2&gt;Measuring intrinsic dimension&lt;/h2&gt;
&lt;p&gt;接下来通过逐渐增大 &lt;code class=&quot;language-math math-inline&quot;&gt;d&lt;/code&gt;，观察性能曲线在哪里越过指定阈值。&lt;/p&gt;
&lt;p&gt;从较小的 &lt;code class=&quot;language-math math-inline&quot;&gt;d&lt;/code&gt; 开始，在对应的随机子空间中多次训练；然后逐渐增加 &lt;code class=&quot;language-math math-inline&quot;&gt;d&lt;/code&gt;，直到模型性能达到 direct training 基准的 &lt;code class=&quot;language-math math-inline&quot;&gt;90\%&lt;/code&gt;。论文把最早跨过这个阈值的子空间维度估计值记为 &lt;code class=&quot;language-math math-inline&quot;&gt;d_{\mathrm{int}90}&lt;/code&gt;。&lt;/p&gt;
&lt;p&gt;如果用 &lt;code class=&quot;language-math math-inline&quot;&gt;A_{\mathrm{base}}&lt;/code&gt; 表示 direct training 的基准性能，用 &lt;code class=&quot;language-math math-inline&quot;&gt;A(d)&lt;/code&gt; 表示在 &lt;code class=&quot;language-math math-inline&quot;&gt;d&lt;/code&gt; 维随机子空间中训练后的性能，那么它的理想化定义是 &lt;code class=&quot;language-math math-inline&quot;&gt;d_{\mathrm{int}90}=\min\left\{d\in\mathbb{N}:A(d)\geq0.9A_{\mathrm{base}}\right\}&lt;/code&gt;。实际实验中的 &lt;code class=&quot;language-math math-inline&quot;&gt;A(d)&lt;/code&gt; 会受到初始化、随机投影和训练噪声影响，因此 &lt;code class=&quot;language-math math-inline&quot;&gt;d_{\mathrm{int}90}&lt;/code&gt; 是从性能曲线中得到的经验估计。&lt;/p&gt;
&lt;p&gt;论文选择 &lt;code class=&quot;language-math math-inline&quot;&gt;90\%&lt;/code&gt;，是为了在解的质量和对测量噪声的鲁棒性之间取得平衡。&lt;/p&gt;
&lt;p&gt;在当前训练设置和 &lt;code class=&quot;language-math math-inline&quot;&gt;90\%&lt;/code&gt; 性能标准下，&lt;code class=&quot;language-math math-inline&quot;&gt;d_{\mathrm{int}90}&lt;/code&gt; 可以看作构造一个 satisfactory solution 所需可训练 degrees of freedom 的经验上界。之所以是上界，是因为实验使用的是随机选取的子空间，它不一定是最适合这个任务的子空间。如果一个随机 &lt;code class=&quot;language-math math-inline&quot;&gt;d&lt;/code&gt; 维子空间已经能够找到 good solution，那么专门为任务选择的子空间所需维度可能更低。&lt;/p&gt;
&lt;h2&gt;论文的局限性&lt;/h2&gt;
&lt;p&gt;在最直接的 dense implementation 中，固定矩阵 &lt;code class=&quot;language-math math-inline&quot;&gt;P\in\mathbb{R}^{D\times d}&lt;/code&gt; 本身包含 &lt;code class=&quot;language-math math-inline&quot;&gt;Dd&lt;/code&gt; 个标量。当 &lt;code class=&quot;language-math math-inline&quot;&gt;d&gt;1&lt;/code&gt; 时，这已经多于 direct training 只需保存的 &lt;code class=&quot;language-math math-inline&quot;&gt;D&lt;/code&gt; 个模型参数。虽然 &lt;code class=&quot;language-math math-inline&quot;&gt;P&lt;/code&gt; 不参与训练，不能算作 trainable parameters，但生成、存储以及使用它完成矩阵乘法仍然会带来额外的 memory 和 computation cost。&lt;/p&gt;
&lt;p&gt;论文也讨论了 sparse projection 和 Fastfood transform 等更节省空间的实现，因此 &lt;code class=&quot;language-math math-inline&quot;&gt;Dd&lt;/code&gt; 的存储开销并不是这套方法无法避免的要求。不过，这项工作的主要价值仍然是研究 objective landscape 和 search-space dimension：它通过限制可训练的 degrees of freedom，测量解决一个任务实际需要多大的搜索空间，而不是提供一种比 direct training 更低成本的训练方式。&lt;/p&gt;
&lt;h2&gt;这篇论文的价值&lt;/h2&gt;
&lt;p&gt;这篇论文最有价值的地方，是它的实验表明：在许多被测试的模型和任务中，参数化包含大量冗余的 degrees of freedom。&lt;/p&gt;
&lt;p&gt;模型的参数总数是 &lt;code class=&quot;language-math math-inline&quot;&gt;D&lt;/code&gt;，不代表完成任务就真的需要 &lt;code class=&quot;language-math math-inline&quot;&gt;D&lt;/code&gt; 个相互独立的优化方向。在实验中，一个小得多的 &lt;code class=&quot;language-math math-inline&quot;&gt;d&lt;/code&gt; 维随机子空间仍然可以达到接近 direct training 的性能。&lt;/p&gt;
&lt;p&gt;这项工作本身不是 LoRA。它只是提供了一个后来理解 parameter-efficient training 很有用的直觉：模型很大，不代表有效参数更新也必须具有同样高的维度。这一结果也可以帮助理解包括 LoRA 在内的后续方法，不过 LoRA 使用的是可学习的 low-rank update，而不是固定的随机子空间。&lt;/p&gt;</content:encoded><h:img src="https://heng-blog.pages.dev/images/social-card.svg"/><enclosure url="https://heng-blog.pages.dev/images/social-card.svg"/></item><item><title>Transformer - Transformer Decoder</title><link>https://heng-blog.pages.dev/blog/transformer-decoder</link><guid isPermaLink="true">https://heng-blog.pages.dev/blog/transformer-decoder</guid><description>实现 masked self-attention、cross-attention、前馈网络，并组合完整 Encoder-Decoder 模型。</description><pubDate>Wed, 30 Apr 2025 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Transformer Decoder 在自回归生成中接收已经右移的目标序列，并结合 Encoder 输出预测下一个 token。与 Encoder Block 相比，它多了一层 cross-attention，同时 self-attention 必须使用 causal mask。&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;本文整理自 &lt;a href=&quot;https://github.com/hengproject/ML_recall&quot;&gt;&lt;code&gt;hengproject/ML_recall&lt;/code&gt;&lt;/a&gt; 中的 &lt;a href=&quot;https://github.com/hengproject/ML_recall/blob/master/transformers/deocder.ipynb&quot;&gt;&lt;code&gt;transformers/deocder.ipynb&lt;/code&gt;&lt;/a&gt;、&lt;a href=&quot;https://github.com/hengproject/ML_recall/blob/master/transformers/Decoder.py&quot;&gt;&lt;code&gt;Decoder.py&lt;/code&gt;&lt;/a&gt; 和 &lt;a href=&quot;https://github.com/hengproject/ML_recall/blob/master/transformers/Model.py&quot;&gt;&lt;code&gt;Model.py&lt;/code&gt;&lt;/a&gt;。Encoder 实现见&lt;a href=&quot;/blog/transformer-encoder&quot;&gt;上一篇&lt;/a&gt;。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Decoder Block 的三层结构&lt;/h2&gt;
&lt;p&gt;本文继续采用 Pre-LN。一个 Decoder Block 包含：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Masked self-attention&lt;/strong&gt;：目标序列内部建模，只允许关注当前位置及其之前的位置。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cross-attention&lt;/strong&gt;：以 Decoder 状态作为 Query，以 Encoder 输出作为 Key 和 Value。&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Feed-forward network&lt;/strong&gt;：对每个目标位置独立执行两层 MLP。&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;每个子层前都做 LayerNorm，子层输出经过 Dropout 后与输入形成残差连接：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;target input
    │
    ├─ LN ─ masked self-attention ─ dropout ─ (+)
    │                                             │
    ├─ LN ─ cross-attention ─────── dropout ─ (+)
    │              ▲                              │
    │              └── encoder memory             │
    │                                             │
    └─ LN ─ feed-forward ────────── dropout ─ (+) ─ output
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Masked Self-Attention&lt;/h2&gt;
&lt;p&gt;Self-attention 的 &lt;code class=&quot;language-math math-inline&quot;&gt;Q&lt;/code&gt;、&lt;code class=&quot;language-math math-inline&quot;&gt;K&lt;/code&gt;、&lt;code class=&quot;language-math math-inline&quot;&gt;V&lt;/code&gt; 都来自 Decoder 当前状态。它同时使用两种 mask：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;tgt_padding_mask&lt;/code&gt; 遮蔽目标序列中的 padding Key；&lt;/li&gt;
&lt;li&gt;causal mask 遮蔽当前 Query 右侧的未来 Key。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;若不使用 causal mask，训练时每个位置都能直接看到未来的目标 token，模型会发生信息泄漏。推理时没有未来 token 可看，训练和推理行为将不一致。&lt;/p&gt;
&lt;h2&gt;Cross-Attention&lt;/h2&gt;
&lt;p&gt;Cross-attention 连接 Encoder 与 Decoder：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;Q = X_{decoder},
\qquad
K = V = H_{encoder}.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;因此 Query 长度为 &lt;code class=&quot;language-math math-inline&quot;&gt;n_{tgt}&lt;/code&gt;，Key/Value 长度为 &lt;code class=&quot;language-math math-inline&quot;&gt;n_{src}&lt;/code&gt;，注意力权重形状为：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;(B,h,n_{tgt},n_{src}).&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;这里使用源序列的 &lt;code&gt;memory_padding_mask&lt;/code&gt;，而不是目标序列的 mask。Cross-attention 不需要 causal mask，因为完整源序列在编码阶段已经可用。&lt;/p&gt;
&lt;h2&gt;Decoder Block 实现&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import torch
import torch.nn as nn

class TransformerDecoderBlock(nn.Module):
    def __init__(self, d_model, num_heads, dim_ff, dropout=0.1):
        super().__init__()
        self.self_attention = MultiHeadAttention(d_model, num_heads)
        self.cross_attention = MultiHeadAttention(d_model, num_heads)
        self.ffn = nn.Sequential(
            nn.Linear(d_model, dim_ff),
            nn.ReLU(),
            nn.Linear(dim_ff, d_model),
        )
        self.norm1 = nn.LayerNorm(d_model)
        self.norm2 = nn.LayerNorm(d_model)
        self.norm3 = nn.LayerNorm(d_model)
        self.dropout1 = nn.Dropout(dropout)
        self.dropout2 = nn.Dropout(dropout)
        self.dropout3 = nn.Dropout(dropout)

    def forward(
        self,
        x,
        encoder_output,
        tgt_padding_mask=None,
        memory_padding_mask=None,
    ):
        normalized = self.norm1(x)
        self_attention_output, _ = self.self_attention(
            query=normalized,
            padding_mask=tgt_padding_mask,
            causal=True,
        )
        x = x + self.dropout1(self_attention_output)

        normalized = self.norm2(x)
        cross_attention_output, _ = self.cross_attention(
            query=normalized,
            key=encoder_output,
            value=encoder_output,
            padding_mask=memory_padding_mask,
            causal=False,
        )
        x = x + self.dropout2(cross_attention_output)

        normalized = self.norm3(x)
        ffn_output = self.ffn(normalized)
        return x + self.dropout3(ffn_output)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;这里要求 &lt;code&gt;MultiHeadAttention&lt;/code&gt; 支持不同长度的 Query 与 Key/Value。Self-attention 中三者长度相同，而 cross-attention 中 &lt;code class=&quot;language-math math-inline&quot;&gt;n_{tgt}&lt;/code&gt; 与 &lt;code class=&quot;language-math math-inline&quot;&gt;n_{src}&lt;/code&gt; 可以不同。&lt;/p&gt;
&lt;h2&gt;堆叠 Decoder Block&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;class TransformerDecoder(nn.Module):
    def __init__(
        self,
        d_model,
        num_heads,
        dim_ff,
        num_layers,
        dropout=0.1,
    ):
        super().__init__()
        self.layers = nn.ModuleList(
            [
                TransformerDecoderBlock(
                    d_model, num_heads, dim_ff, dropout
                )
                for _ in range(num_layers)
            ]
        )
        self.final_norm = nn.LayerNorm(d_model)

    def forward(
        self,
        x,
        encoder_output,
        tgt_padding_mask=None,
        memory_padding_mask=None,
    ):
        for layer in self.layers:
            x = layer(
                x,
                encoder_output,
                tgt_padding_mask=tgt_padding_mask,
                memory_padding_mask=memory_padding_mask,
            )
        return self.final_norm(x)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;无论堆叠多少层，Decoder 的外部形状都保持 &lt;code class=&quot;language-math math-inline&quot;&gt;(B,n_{tgt},d_{model})&lt;/code&gt;。&lt;/p&gt;
&lt;h2&gt;组合完整 Encoder-Decoder&lt;/h2&gt;
&lt;p&gt;源序列与目标序列分别经过输入嵌入。Encoder 输出称为 &lt;code&gt;memory&lt;/code&gt;，Decoder 输出再投影到词表维度，得到每个目标位置的 logits：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;class TransformerModel(nn.Module):
    def __init__(
        self,
        vocab_size,
        d_model,
        num_heads,
        dim_ff,
        num_layers,
        max_len=5000,
        dropout=0.1,
    ):
        super().__init__()
        self.source_embedding = InputEmbedding(
            vocab_size, d_model, max_len
        )
        self.target_embedding = InputEmbedding(
            vocab_size, d_model, max_len
        )
        self.encoder = TransformerEncoder(
            d_model, num_heads, dim_ff, num_layers, dropout
        )
        self.decoder = TransformerDecoder(
            d_model, num_heads, dim_ff, num_layers, dropout
        )
        self.output_projection = nn.Linear(d_model, vocab_size)

    def forward(
        self,
        source_ids,
        target_ids,
        source_padding_mask=None,
        target_padding_mask=None,
    ):
        source = self.source_embedding(source_ids)
        target = self.target_embedding(target_ids)

        memory = self.encoder(source, source_padding_mask)
        output = self.decoder(
            target,
            memory,
            tgt_padding_mask=target_padding_mask,
            memory_padding_mask=source_padding_mask,
        )
        return self.output_projection(output)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;输入输出形状为：&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;张量&lt;/th&gt;
&lt;th&gt;形状&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;source_ids&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;(B,n_{src})&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;target_ids&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;(B,n_{tgt})&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Encoder memory&lt;/td&gt;
&lt;td&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;(B,n_{src},d_{model})&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Decoder output&lt;/td&gt;
&lt;td&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;(B,n_{tgt},d_{model})&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;logits&lt;/td&gt;
&lt;td&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;(B,n_{tgt},V)&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2&gt;形状测试&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;batch_size = 2
source_length = 7
target_length = 5
vocab_size = 1000

source_ids = torch.randint(
    0, vocab_size, (batch_size, source_length)
)
target_ids = torch.randint(
    0, vocab_size, (batch_size, target_length)
)

source_padding_mask = torch.tensor(
    [
        [0, 0, 0, 0, 0, 1, 1],
        [0, 0, 0, 0, 0, 0, 1],
    ]
)
target_padding_mask = torch.tensor(
    [
        [0, 0, 0, 1, 1],
        [0, 0, 0, 0, 1],
    ]
)

model = TransformerModel(
    vocab_size=vocab_size,
    d_model=512,
    num_heads=8,
    dim_ff=2048,
    num_layers=4,
)
logits = model(
    source_ids,
    target_ids,
    source_padding_mask,
    target_padding_mask,
)

print(logits.shape)  # torch.Size([2, 5, 1000])
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;训练与生成时还缺什么&lt;/h2&gt;
&lt;p&gt;上面的模块完成了核心前向传播，但一个可训练、可生成的序列模型还需要：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;将目标序列右移，以起始 token 作为 Decoder 的第一个输入；&lt;/li&gt;
&lt;li&gt;用未右移的目标序列计算交叉熵，并忽略 padding 位置；&lt;/li&gt;
&lt;li&gt;决定输入嵌入与输出投影是否共享权重；&lt;/li&gt;
&lt;li&gt;在生成时实现 greedy decoding、beam search 或 sampling，并维护停止条件；&lt;/li&gt;
&lt;li&gt;对全部被 mask 的行做保护，避免 softmax 产生 &lt;code&gt;NaN&lt;/code&gt;；&lt;/li&gt;
&lt;li&gt;根据任务分别管理源词表、目标词表与特殊 token。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Decoder 的核心逻辑可以概括为：先在已生成的目标前缀中建模，再从 Encoder memory 中检索源信息，最后通过 FFN 更新每个目标位置的表示。&lt;/p&gt;</content:encoded><h:img src="https://heng-blog.pages.dev/images/social-card.svg"/><enclosure url="https://heng-blog.pages.dev/images/social-card.svg"/></item><item><title>深度学习中的权重初始化</title><link>https://heng-blog.pages.dev/blog/ml-weight-initialization</link><guid isPermaLink="true">https://heng-blog.pages.dev/blog/ml-weight-initialization</guid><description>从零初始化和小随机数出发，通过激活分布理解 Xavier 与 Kaiming 初始化。</description><pubDate>Thu, 17 Apr 2025 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;神经网络的权重初始化会直接影响前向传播中的激活分布，以及反向传播时梯度能否稳定流动。本文从一个线性层出发，逐步比较零初始化、小随机数、Xavier 初始化和 Kaiming 初始化。&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;本文整理自 &lt;a href=&quot;https://github.com/hengproject/ML_recall&quot;&gt;&lt;code&gt;hengproject/ML_recall&lt;/code&gt;&lt;/a&gt; 中的 &lt;a href=&quot;https://github.com/hengproject/ML_recall/blob/main/basics/weight_initialization.ipynb&quot;&gt;&lt;code&gt;basics/weight_initialization.ipynb&lt;/code&gt;&lt;/a&gt;。课程内容参考 USC CSCI 566: Deep Learning and Its Applications。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;从零初始化开始&lt;/h2&gt;
&lt;p&gt;以一个线性层为例。使用增广记号，将偏置合并到输入向量中：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\underline{x} = [x_0, x_1, \ldots, x_n, b],
\qquad
Y = \underline{w}^{T}\underline{x}.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;如果所有权重都初始化为零，那么无论输入如何变化，线性层的输出都会是零：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import numpy as np
import matplotlib.pyplot as plt

x = np.ones(100)
w = np.zeros(100)
y = w.T @ x
print(y)  # 0.0
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;更重要的是，对具有多个同构神经元的网络而言，相同的初始权重会产生相同的输出和梯度，神经元无法学习出不同特征。因此，需要用非零随机值打破对称性。&lt;/p&gt;
&lt;h2&gt;小随机数初始化&lt;/h2&gt;
&lt;p&gt;一种直观方法是从方差很小的高斯分布中采样权重：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\underline{w} \sim \mathcal{N}(\mu, \sigma^2).&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;np.random.seed(2025)
w = 0.01 * np.random.randn(100)
y = w.T @ x
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;单层网络中，这似乎没有问题；但在深层网络中，每一层都会继续缩小信号。下面构造一个六层、使用 &lt;code&gt;tanh&lt;/code&gt; 激活函数的网络：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;h_0 = x,
\qquad
h_i = \tanh(h_{i-1}W_i^T).&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;dims = [4096] * 7
activations = []
x = np.random.randn(16, dims[0])

for fan_in, fan_out in zip(dims[:-1], dims[1:]):
    w = 0.01 * np.random.randn(fan_out, fan_in)
    x = np.tanh(x @ w.T)
    activations.append(x)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://heng-blog.pages.dev/_astro/small-random.mTNvhrui_2s4u0y.webp&quot; alt=&quot;小随机数初始化下各层的激活分布&quot;&gt;&lt;/p&gt;
&lt;p&gt;越靠后的层，激活值越集中在零附近。信号和梯度逐层衰减，网络会变得难以训练。&lt;/p&gt;
&lt;h2&gt;Xavier 初始化&lt;/h2&gt;
&lt;p&gt;Xavier 初始化的目标是让输入与输出的方差尽可能保持一致。对 &lt;code&gt;fan_in&lt;/code&gt; 个输入，常用的正态分布形式为：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;W \sim \mathcal{N}\left(0, \frac{1}{n_{in}}\right).&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;假设 &lt;code class=&quot;language-math math-inline&quot;&gt;W_{ji}&lt;/code&gt; 与 &lt;code class=&quot;language-math math-inline&quot;&gt;x_i&lt;/code&gt; 相互独立、均值为零，且&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;W_{ji} \sim \mathcal{N}\left(0, \frac{1}{n_{in}}\right),
\qquad
\operatorname{Var}(x_i) = \sigma^2.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;对线性变换 &lt;code class=&quot;language-math math-inline&quot;&gt;z_j = \sum_i W_{ji}x_i + b_j&lt;/code&gt;，有：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\begin{aligned}
\operatorname{Var}(z_j)
&amp;#x26;= \sum_{i=1}^{n_{in}} \operatorname{Var}(W_{ji}x_i) \\
&amp;#x26;= \sum_{i=1}^{n_{in}} \operatorname{Var}(W_{ji})\operatorname{Var}(x_i) \\
&amp;#x26;= n_{in} \cdot \frac{1}{n_{in}} \cdot \sigma^2 \\
&amp;#x26;= \sigma^2.
\end{aligned}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;tanh&lt;/code&gt; 在零附近近似线性，因此这种初始化能够在一定程度上让各层激活保持相近的方差：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;dims = [4096] * 7
activations = []
x = np.random.randn(16, dims[0])

for fan_in, fan_out in zip(dims[:-1], dims[1:]):
    w = np.random.randn(fan_out, fan_in) / np.sqrt(fan_in)
    x = np.tanh(x @ w.T)
    activations.append(x)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://heng-blog.pages.dev/_astro/xavier-tanh.61hgZ7ZC_1dMnVx.webp&quot; alt=&quot;Xavier 初始化下各层的 tanh 激活分布&quot;&gt;&lt;/p&gt;
&lt;h2&gt;Xavier 与 ReLU&lt;/h2&gt;
&lt;p&gt;将相同的 Xavier 初始化直接用于 ReLU，激活分布仍然会随网络加深而收缩：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;for fan_in, fan_out in zip(dims[:-1], dims[1:]):
    w = np.random.randn(fan_out, fan_in) / np.sqrt(fan_in)
    x = np.maximum(0, x @ w.T)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://heng-blog.pages.dev/_astro/xavier-relu.CxyPUYYQ_2nFp10.webp&quot; alt=&quot;Xavier 初始化下各层的 ReLU 激活分布&quot;&gt;&lt;/p&gt;
&lt;p&gt;ReLU 会把负值截断为零。在输入关于零对称的近似条件下，可将其视为使 &lt;code class=&quot;language-math math-inline&quot;&gt;E[z^2]&lt;/code&gt; 大约减半。为保持尺度，需要令：&lt;/p&gt;
&lt;p&gt;当 &lt;code class=&quot;language-math math-inline&quot;&gt;z&lt;/code&gt; 关于零对称时，正负两侧对 &lt;code class=&quot;language-math math-inline&quot;&gt;E[z^2]&lt;/code&gt; 的贡献相同。ReLU 将负数一侧截断为零，因此保留下来的 &lt;code class=&quot;language-math math-inline&quot;&gt;E[z^2]&lt;/code&gt; 约为原来的一半：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;E[\operatorname{ReLU}(z)^2] \approx \frac{1}{2}E[z^2].&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;取一组关于零对称的数值：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\begin{aligned}
z &amp;#x26;= [-2,-1,1,2], \\
z^2 &amp;#x26;= [4,1,1,4], \\
E[z^2] &amp;#x26;= \frac{10}{4}=2.5.
\end{aligned}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;经过 ReLU 后，负数被置为零：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\begin{aligned}
\operatorname{ReLU}(z) &amp;#x26;= [0,0,1,2], \\
\operatorname{ReLU}(z)^2 &amp;#x26;= [0,0,1,4], \\
E[\operatorname{ReLU}(z)^2] &amp;#x26;= \frac{5}{4}=1.25
= \frac{1}{2}\times 2.5.
\end{aligned}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;对于具有 &lt;code class=&quot;language-math math-inline&quot;&gt;n_{in}&lt;/code&gt; 个输入的线性层，其输出满足：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;E[z^2] \approx n_{in}\operatorname{Var}(w)E[x^2].&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;经过 ReLU 后：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;E[\operatorname{ReLU}(z)^2]
\approx \frac{1}{2}n_{in}\operatorname{Var}(w)E[x^2].&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;为了让每一层前后的信号尺度基本不变，需要满足：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\frac{1}{2}n_{in}\operatorname{Var}(w) \approx 1,&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;由此得到 He 初始化采用的关系 &lt;code class=&quot;language-math math-inline&quot;&gt;\operatorname{Var}(w) \approx 2/n_{in}&lt;/code&gt;。&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\begin{aligned}
\operatorname{Var}(z_j)
&amp;#x26;= n_{in}\sigma_w^2\sigma_x^2, \\
\operatorname{Var}(\operatorname{ReLU}(z_j))
&amp;#x26;\approx \frac{1}{2}n_{in}\sigma_w^2\sigma_x^2.
\end{aligned}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;要求输出尺度与输入一致，可得：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\frac{1}{2}n_{in}\sigma_w^2\sigma_x^2 = \sigma_x^2
\quad\Longrightarrow\quad
\sigma_w^2 = \frac{2}{n_{in}}.&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Kaiming 初始化&lt;/h2&gt;
&lt;p&gt;因此，对 ReLU 网络可按下面的标准差初始化权重：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\sigma_w = \sqrt{\frac{2}{n_{in}}}.&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;dims = [4096] * 7
activations = []
x = np.random.randn(16, dims[0])

for fan_in, fan_out in zip(dims[:-1], dims[1:]):
    w = np.random.randn(fan_out, fan_in) * np.sqrt(2 / fan_in)
    x = np.maximum(0, x @ w.T)
    activations.append(x)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://heng-blog.pages.dev/_astro/kaiming-relu.Dxw1UNLM_ZARirH.webp&quot; alt=&quot;Kaiming 初始化下各层的 ReLU 激活分布&quot;&gt;&lt;/p&gt;
&lt;h2&gt;小结&lt;/h2&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;初始化方法&lt;/th&gt;
&lt;th&gt;典型尺度&lt;/th&gt;
&lt;th&gt;更适合的激活函数&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;小随机数&lt;/td&gt;
&lt;td&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;0.01 \cdot \mathcal{N}(0, 1)&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;浅层网络或实验基线&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Xavier&lt;/td&gt;
&lt;td&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\operatorname{Var}(W) \approx 1 / n_{in}&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;tanh&lt;/code&gt;、&lt;code&gt;sigmoid&lt;/code&gt; 等近似对称激活&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Kaiming&lt;/td&gt;
&lt;td&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\operatorname{Var}(W) \approx 2 / n_{in}&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;ReLU 及其变体&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;初始化方法的核心不是记住常数，而是控制信号在网络深度方向上的尺度。实际使用时，还应结合激活函数、残差连接、归一化层和框架提供的初始化 API 共同考虑。&lt;/p&gt;</content:encoded><h:img src="https://heng-blog.pages.dev/images/social-card.svg"/><enclosure url="https://heng-blog.pages.dev/images/social-card.svg"/></item><item><title>Transformer - Transformer Encoder</title><link>https://heng-blog.pages.dev/blog/transformer-encoder</link><guid isPermaLink="true">https://heng-blog.pages.dev/blog/transformer-encoder</guid><description>拆解 Pre-LN Encoder Block、自注意力、前馈网络、残差连接与多层堆叠。</description><pubDate>Mon, 21 Apr 2025 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Transformer Encoder 将输入序列编码为上下文化表示。每个 block 包含两个子层：Multi-Head Self-Attention 和逐位置 Feed-Forward Network（FFN），并用残差连接、LayerNorm 与 Dropout 稳定训练。&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;本文整理自 &lt;a href=&quot;https://github.com/hengproject/ML_recall&quot;&gt;&lt;code&gt;hengproject/ML_recall&lt;/code&gt;&lt;/a&gt; 中的 &lt;a href=&quot;https://github.com/hengproject/ML_recall/blob/master/transformers/encoder.ipynb&quot;&gt;&lt;code&gt;transformers/encoder.ipynb&lt;/code&gt;&lt;/a&gt;。注意力与输入表示分别见&lt;a href=&quot;/blog/from-additive-to-multi-head-attention&quot;&gt;注意力机制&lt;/a&gt;和&lt;a href=&quot;/blog/transformer-input-embedding&quot;&gt;输入嵌入&lt;/a&gt;。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Encoder Block 的数据流&lt;/h2&gt;
&lt;p&gt;原始 Transformer 使用 Post-LN，即先执行子层和残差相加，再归一化。本文实现 Pre-LN，将 LayerNorm 放在每个子层之前：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;x ── LayerNorm ── Self-Attention ── Dropout ── (+) ── x&apos;
│                                                   ▲
└───────────────────────────────────────────────────┘

x&apos; ─ LayerNorm ── Feed-Forward ───── Dropout ── (+) ── output
│                                                   ▲
└───────────────────────────────────────────────────┘
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;对应公式为：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\begin{aligned}
x&apos; &amp;#x26;= x + \operatorname{Dropout}(\operatorname{MHA}(\operatorname{LN}(x))), \\
y &amp;#x26;= x&apos; + \operatorname{Dropout}(\operatorname{FFN}(\operatorname{LN}(x&apos;))).
\end{aligned}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Pre-LN 为残差分支提供更直接的梯度路径，通常比深层 Post-LN 模型更容易优化。不过两种结构都仍在使用，具体选择应与模型架构和训练方案保持一致。&lt;/p&gt;
&lt;h2&gt;Multi-Head Self-Attention&lt;/h2&gt;
&lt;p&gt;在 Encoder 的 self-attention 中，Query、Key、Value 都来自同一个归一化后的输入：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;Q = K = V = \operatorname{LN}(x).&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Encoder 不使用 causal mask，因为每个非 padding 位置都允许关注完整输入序列。Padding mask 的形状通常为 &lt;code class=&quot;language-math math-inline&quot;&gt;(B,n)&lt;/code&gt;，它只遮蔽 Key 侧的 padding 位置。&lt;/p&gt;
&lt;h2&gt;Feed-Forward Network&lt;/h2&gt;
&lt;p&gt;FFN 独立作用于每个序列位置，参数在所有位置之间共享：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\operatorname{FFN}(x)
= W_2\,\phi(W_1x+b_1)+b_2.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;第一层把最后一维从 &lt;code class=&quot;language-math math-inline&quot;&gt;d_{model}&lt;/code&gt; 扩展到 &lt;code class=&quot;language-math math-inline&quot;&gt;d_{ff}&lt;/code&gt;，非线性激活后再投影回 &lt;code class=&quot;language-math math-inline&quot;&gt;d_{model}&lt;/code&gt;，从而能够与残差分支相加。&lt;/p&gt;
&lt;h2&gt;Encoder Block 实现&lt;/h2&gt;
&lt;p&gt;下面的 &lt;code&gt;MultiHeadAttention&lt;/code&gt; 沿用前一篇的接口，输入与输出形状均为 &lt;code class=&quot;language-math math-inline&quot;&gt;(B,n,d_{model})&lt;/code&gt;。&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import torch
import torch.nn as nn

class TransformerEncoderBlock(nn.Module):
    def __init__(self, d_model, num_heads, dim_ff, dropout=0.1):
        super().__init__()
        self.attention = MultiHeadAttention(d_model, num_heads)
        self.ffn = nn.Sequential(
            nn.Linear(d_model, dim_ff),
            nn.ReLU(),
            nn.Linear(dim_ff, d_model),
        )
        self.norm1 = nn.LayerNorm(d_model)
        self.norm2 = nn.LayerNorm(d_model)
        self.dropout1 = nn.Dropout(dropout)
        self.dropout2 = nn.Dropout(dropout)

    def forward(self, x, padding_mask=None):
        normalized = self.norm1(x)
        attention_output, _ = self.attention(
            normalized,
            padding_mask=padding_mask,
            causal=False,
        )
        x = x + self.dropout1(attention_output)

        normalized = self.norm2(x)
        ffn_output = self.ffn(normalized)
        return x + self.dropout2(ffn_output)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;残差连接要求每个子层输出都保持 &lt;code class=&quot;language-math math-inline&quot;&gt;(B,n,d_{model})&lt;/code&gt;。&lt;code&gt;dim_ff&lt;/code&gt; 只在 FFN 内部使用，不会改变 block 的外部接口。&lt;/p&gt;
&lt;h2&gt;堆叠多个 Block&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;nn.ModuleList&lt;/code&gt; 可以注册多个独立 block。每层拥有自己的参数，但接收相同的 padding mask：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;class TransformerEncoder(nn.Module):
    def __init__(
        self,
        d_model,
        num_heads,
        dim_ff,
        num_layers,
        dropout=0.1,
    ):
        super().__init__()
        self.layers = nn.ModuleList(
            [
                TransformerEncoderBlock(
                    d_model, num_heads, dim_ff, dropout
                )
                for _ in range(num_layers)
            ]
        )
        self.final_norm = nn.LayerNorm(d_model)

    def forward(self, x, padding_mask=None):
        for layer in self.layers:
            x = layer(x, padding_mask=padding_mask)
        return self.final_norm(x)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;对 Pre-LN 架构，在整个 stack 末尾增加一次 LayerNorm 是常见做法。它不是单个 block 的第三个子层，而是对堆叠后的最终表示做归一化。&lt;/p&gt;
&lt;h2&gt;接入输入嵌入&lt;/h2&gt;
&lt;p&gt;完整 Encoder 先把 token ID 转换为带位置信息的向量，再送入 block stack：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;class TransformerEncoderModel(nn.Module):
    def __init__(
        self,
        vocab_size,
        d_model,
        num_heads,
        dim_ff,
        num_layers,
        max_len=5000,
        dropout=0.1,
    ):
        super().__init__()
        self.input_embedding = InputEmbedding(
            vocab_size, d_model, max_len
        )
        self.encoder = TransformerEncoder(
            d_model, num_heads, dim_ff, num_layers, dropout
        )

    def forward(self, input_ids, padding_mask=None):
        x = self.input_embedding(input_ids)
        return self.encoder(x, padding_mask=padding_mask)
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;形状测试&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;batch_size = 2
seq_len = 10
vocab_size = 1000
d_model = 512

input_ids = torch.randint(0, vocab_size, (batch_size, seq_len))
padding_mask = torch.tensor(
    [
        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 1, 1, 1, 1, 1, 1],
    ]
)

model = TransformerEncoderModel(
    vocab_size=vocab_size,
    d_model=d_model,
    num_heads=8,
    dim_ff=2048,
    num_layers=6,
)
output = model(input_ids, padding_mask)

print(input_ids.shape)  # torch.Size([2, 10])
print(output.shape)     # torch.Size([2, 10, 512])
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;实现注意点&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Mask 遮蔽 Key 位置后，padding 对应的 Query 位置仍可能产生非零输出；下游若要求这些位置严格为零，需要在 block 外再次清零或在损失中忽略。&lt;/li&gt;
&lt;li&gt;原论文 FFN 使用 ReLU，现代模型也常用 GELU、SwiGLU 等激活与门控结构。&lt;/li&gt;
&lt;li&gt;&lt;code&gt;d_model&lt;/code&gt; 必须能被 &lt;code&gt;num_heads&lt;/code&gt; 整除；&lt;code&gt;dim_ff&lt;/code&gt; 则是独立的容量超参数。&lt;/li&gt;
&lt;li&gt;位置编码、Dropout 和注意力内部的投影偏置都会影响完整复现，不能只比较 block 的主干公式。&lt;/li&gt;
&lt;/ul&gt;</content:encoded><h:img src="https://heng-blog.pages.dev/images/social-card.svg"/><enclosure url="https://heng-blog.pages.dev/images/social-card.svg"/></item><item><title>Transformer - Transformer 的输入嵌入与位置编码</title><link>https://heng-blog.pages.dev/blog/transformer-input-embedding</link><guid isPermaLink="true">https://heng-blog.pages.dev/blog/transformer-input-embedding</guid><description>解释 Token Embedding、正弦余弦位置编码及其 PyTorch 实现与张量形状。</description><pubDate>Mon, 21 Apr 2025 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Transformer 的输入表示通常由 Token Embedding 与 Positional Encoding 相加得到。前者表示 token 的语义，后者为不具备循环结构的注意力网络提供顺序信息。&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;本文整理自 &lt;a href=&quot;https://github.com/hengproject/ML_recall&quot;&gt;&lt;code&gt;hengproject/ML_recall&lt;/code&gt;&lt;/a&gt; 中的 &lt;a href=&quot;https://github.com/hengproject/ML_recall/blob/master/transformers/input_embedding.ipynb&quot;&gt;&lt;code&gt;transformers/input_embedding.ipynb&lt;/code&gt;&lt;/a&gt;，公式来自 &lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;&lt;em&gt;Attention Is All You Need&lt;/em&gt;&lt;/a&gt;。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Token Embedding&lt;/h2&gt;
&lt;p&gt;输入 token ID 的形状为 &lt;code class=&quot;language-math math-inline&quot;&gt;(B,n)&lt;/code&gt;，嵌入层维护一个形状为 &lt;code class=&quot;language-math math-inline&quot;&gt;(V,d_{model})&lt;/code&gt; 的可学习矩阵，其中 &lt;code class=&quot;language-math math-inline&quot;&gt;V&lt;/code&gt; 是词表大小。查表后，每个 token 都被映射为一个 &lt;code class=&quot;language-math math-inline&quot;&gt;d_{model}&lt;/code&gt; 维向量：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;(B,n) \longrightarrow (B,n,d_{model}).&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import torch
import torch.nn as nn

class TokenEmbedding(nn.Module):
    def __init__(self, vocab_size, d_model):
        super().__init__()
        self.embedding = nn.Embedding(vocab_size, d_model)

    def forward(self, token_ids):
        return self.embedding(token_ids)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;如果只使用 Token Embedding，模型无法区分相同 token 出现在不同位置的情况。Self-attention 本身对输入排列是等变的，因此还需要显式注入位置信息。&lt;/p&gt;
&lt;h2&gt;Sinusoidal Positional Encoding&lt;/h2&gt;
&lt;p&gt;原始 Transformer 使用固定的正弦余弦位置编码。对位置 &lt;code class=&quot;language-math math-inline&quot;&gt;pos&lt;/code&gt; 和通道索引 &lt;code class=&quot;language-math math-inline&quot;&gt;i&lt;/code&gt;：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\begin{aligned}
\operatorname{PE}_{pos,2i}
&amp;#x26;= \sin\left(\frac{pos}{10000^{2i/d_{model}}}\right), \\
\operatorname{PE}_{pos,2i+1}
&amp;#x26;= \cos\left(\frac{pos}{10000^{2i/d_{model}}}\right).
\end{aligned}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;相邻的偶数、奇数通道使用相同频率的一对正弦和余弦函数，不同通道对覆盖不同尺度。低索引通道变化较快，高索引通道变化较慢，因此每个位置都获得一个多尺度表示。&lt;/p&gt;
&lt;p&gt;最终输入为 token 向量与位置向量之和：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;z_{pos} = x_{pos} + p_{pos}.&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;二者维度相同，所以相加不会改变张量形状。&lt;/p&gt;
&lt;h2&gt;为什么同时使用正弦与余弦&lt;/h2&gt;
&lt;p&gt;对同一频率，在完整周期上的正弦和余弦正交。例如：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\begin{aligned}
\langle \sin x, \cos x \rangle
&amp;#x26;= \int_0^{2\pi}\sin x\cos x\,dx \\
&amp;#x26;= \frac{1}{2}\int_0^{2\pi}\sin(2x)\,dx \\
&amp;#x26;= 0.
\end{aligned}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;更关键的是，正弦与余弦的相位关系使位置偏移可表示为线性变换。对固定偏移 &lt;code class=&quot;language-math math-inline&quot;&gt;k&lt;/code&gt;，&lt;code class=&quot;language-math math-inline&quot;&gt;\sin(pos+k)&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;\cos(pos+k)&lt;/code&gt; 都能由位置 &lt;code class=&quot;language-math math-inline&quot;&gt;pos&lt;/code&gt; 上同频率的正弦、余弦线性组合得到，这为模型学习相对位置关系提供了便利。&lt;/p&gt;
&lt;h2&gt;PyTorch 实现&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import math
import torch
import torch.nn as nn

class PositionalEncoding(nn.Module):
    def __init__(self, d_model, max_len=5000):
        super().__init__()
        pe = torch.zeros(max_len, d_model)
        position = torch.arange(max_len).unsqueeze(1).float()
        frequencies = torch.exp(
            torch.arange(0, d_model, 2).float()
            * (-math.log(10000.0) / d_model)
        )

        pe[:, 0::2] = torch.sin(position * frequencies)  # 偶数索引
        pe[:, 1::2] = torch.cos(position * frequencies)  # 奇数索引
        pe = pe.unsqueeze(0)  # (1, max_len, d_model)

        self.register_buffer(&quot;pe&quot;, pe)

    def forward(self, x):
        # x: (batch, seq_len, d_model)
        return x + self.pe[:, : x.size(1)]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;register_buffer&lt;/code&gt; 表示 &lt;code&gt;pe&lt;/code&gt; 是模块状态的一部分，但不是需要优化器更新的参数。它会随模型保存、加载和迁移设备。&lt;/p&gt;
&lt;p&gt;位置编码预先生成到 &lt;code&gt;max_len&lt;/code&gt;。前向传播时通过 &lt;code&gt;self.pe[:, :x.size(1)]&lt;/code&gt; 取得当前序列长度对应的部分，并沿 batch 维广播。&lt;/p&gt;
&lt;h2&gt;组合输入层&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;class InputEmbedding(nn.Module):
    def __init__(self, vocab_size, d_model, max_len=5000):
        super().__init__()
        self.token_embedding = TokenEmbedding(vocab_size, d_model)
        self.positional_encoding = PositionalEncoding(d_model, max_len)

    def forward(self, token_ids):
        x = self.token_embedding(token_ids)
        return self.positional_encoding(x)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;可以用一个简单测试确认形状：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;batch_size = 2
seq_len = 10
d_model = 512
vocab_size = 1000

token_ids = torch.randint(0, vocab_size, (batch_size, seq_len))
embedding = InputEmbedding(vocab_size, d_model, max_len=seq_len)
output = embedding(token_ids)

print(token_ids.shape)  # torch.Size([2, 10])
print(output.shape)     # torch.Size([2, 10, 512])
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;实现注意点&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;原论文会将 Token Embedding 乘以 &lt;code class=&quot;language-math math-inline&quot;&gt;\sqrt{d_{model}}&lt;/code&gt; 后再与位置编码相加；是否保留这一缩放应与整体实现保持一致。&lt;/li&gt;
&lt;li&gt;上面的切片赋值默认 &lt;code&gt;d_model&lt;/code&gt; 为偶数。若允许奇数维度，需要单独处理最后一个偶数索引通道。&lt;/li&gt;
&lt;li&gt;固定位置编码没有可学习参数，但 &lt;code&gt;max_len&lt;/code&gt; 是硬上限；超长序列需要扩展 buffer 或动态生成。&lt;/li&gt;
&lt;li&gt;现代 Transformer 也常使用可学习位置嵌入、RoPE 或相对位置偏置。它们改变位置建模方式，但不会改变 Token Embedding 的基本职责。&lt;/li&gt;
&lt;/ul&gt;</content:encoded><h:img src="https://heng-blog.pages.dev/images/social-card.svg"/><enclosure url="https://heng-blog.pages.dev/images/social-card.svg"/></item><item><title>Batch Normalization 与 Layer Normalization</title><link>https://heng-blog.pages.dev/blog/batch-norm-vs-layer-norm</link><guid isPermaLink="true">https://heng-blog.pages.dev/blog/batch-norm-vs-layer-norm</guid><description>从统计维度、训练推理行为和应用场景理解 BatchNorm 与 LayerNorm 的区别。</description><pubDate>Thu, 17 Apr 2025 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Batch Normalization（BN）和 Layer Normalization（LN）都通过标准化激活值来改善神经网络的优化过程，但二者计算统计量的维度不同，因此适用场景也不同。&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;本文整理自 &lt;a href=&quot;https://github.com/hengproject/ML_recall&quot;&gt;&lt;code&gt;hengproject/ML_recall&lt;/code&gt;&lt;/a&gt; 中的 &lt;a href=&quot;https://github.com/hengproject/ML_recall/blob/main/basics/Normalizations.ipynb&quot;&gt;&lt;code&gt;basics/Normalizations.ipynb&lt;/code&gt;&lt;/a&gt;。延伸讲解可参考 &lt;a href=&quot;https://www.youtube.com/watch?v=BZh1ltr5Rkg&quot;&gt;Deep Learning Basics: Batch Normalization&lt;/a&gt;。&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Batch Normalization&lt;/h2&gt;
&lt;p&gt;设一个 mini-batch 为 &lt;code class=&quot;language-math math-inline&quot;&gt;\mathcal{B} = \{x_1, \ldots, x_m\}&lt;/code&gt;，BN 首先按 batch 维度计算每个特征的均值与方差：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\begin{aligned}
\mu_{\mathcal{B}} &amp;#x26;= \frac{1}{m}\sum_{i=1}^{m}x_i, \\
\sigma_{\mathcal{B}}^2 &amp;#x26;= \frac{1}{m}\sum_{i=1}^{m}(x_i - \mu_{\mathcal{B}})^2, \\
\hat{x}_i &amp;#x26;= \frac{x_i - \mu_{\mathcal{B}}}{\sqrt{\sigma_{\mathcal{B}}^2 + \epsilon}}, \\
y_i &amp;#x26;= \gamma\hat{x}_i + \beta.
\end{aligned}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\gamma&lt;/code&gt; 和 &lt;code class=&quot;language-math math-inline&quot;&gt;\beta&lt;/code&gt; 是可学习参数，使网络能够恢复或重新调整每个特征的尺度和偏移。&lt;/p&gt;
&lt;p&gt;下面是一个二维输入的 NumPy 实现，其中形状为 &lt;code&gt;(batch_size, features)&lt;/code&gt;：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import numpy as np

np.random.seed(2025)
batch_size = 100
features = 20
x = np.random.randn(batch_size, features)

def batch_normalization(x, gamma, beta, eps=1e-9):
    batch_mean = np.mean(x, axis=0, keepdims=True)
    batch_var = np.var(x, axis=0, keepdims=True)
    x_hat = (x - batch_mean) / np.sqrt(batch_var + eps)
    return gamma * x_hat + beta

y = batch_normalization(x, gamma=1, beta=0)
print(y.shape, np.mean(y), np.var(y))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;这里的 &lt;code&gt;axis=0&lt;/code&gt; 表示：对 batch 中所有样本的同一个特征计算统计量。&lt;/p&gt;
&lt;h3&gt;训练与推理&lt;/h3&gt;
&lt;p&gt;训练时，BN 使用当前 mini-batch 的统计量，并维护均值和方差的移动估计。&lt;/p&gt;
&lt;p&gt;推理时通常使用训练期间累计的移动统计量，而不是依赖当前输入 batch。&lt;/p&gt;
&lt;p&gt;BN 往往能够：&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;改善优化过程中的梯度传播；&lt;/li&gt;
&lt;li&gt;允许使用更高的学习率；&lt;/li&gt;
&lt;li&gt;降低网络对参数初始化的敏感度；&lt;/li&gt;
&lt;li&gt;引入依赖 mini-batch 的随机性，产生一定正则化效果。&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;“减少 internal covariate shift”是 BN 原论文提出的解释，但后续研究表明，这并不足以完整解释 BN 的效果。实践中，更稳妥的理解是 BN 改变并平滑了优化问题的几何性质。&lt;/p&gt;
&lt;h2&gt;Layer Normalization&lt;/h2&gt;
&lt;p&gt;LN 不在不同样本之间聚合统计量，而是对单个样本的特征维度进行归一化。对一个包含 &lt;code class=&quot;language-math math-inline&quot;&gt;H&lt;/code&gt; 个特征的样本 &lt;code class=&quot;language-math math-inline&quot;&gt;\mathcal{H} = \{x_1, \ldots, x_H\}&lt;/code&gt;：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\begin{aligned}
\mu_{\mathcal{H}} &amp;#x26;= \frac{1}{H}\sum_{i=1}^{H}x_i, \\
\sigma_{\mathcal{H}}^2 &amp;#x26;= \frac{1}{H}\sum_{i=1}^{H}(x_i - \mu_{\mathcal{H}})^2, \\
\hat{x}_i &amp;#x26;= \frac{x_i - \mu_{\mathcal{H}}}{\sqrt{\sigma_{\mathcal{H}}^2 + \epsilon}}, \\
y_i &amp;#x26;= \gamma\hat{x}_i + \beta.
\end{aligned}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;对应的 NumPy 实现只需改变统计维度：&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def layer_normalization(x, gamma, beta, eps=1e-9):
    layer_mean = np.mean(x, axis=1, keepdims=True)
    layer_var = np.var(x, axis=1, keepdims=True)
    x_hat = (x - layer_mean) / np.sqrt(layer_var + eps)
    return gamma * x_hat + beta

gamma = np.ones((1, features))
beta = np.zeros((1, features))
y = layer_normalization(x, gamma, beta)
print(y.shape, np.mean(y), np.var(y))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;这里的 &lt;code&gt;axis=1&lt;/code&gt; 表示：分别对每个样本内部的所有特征计算统计量。LN 不依赖同一 batch 中的其他样本，因此训练与推理时的计算方式一致。&lt;/p&gt;
&lt;h2&gt;BN 与 LN 的选择&lt;/h2&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;对比项&lt;/th&gt;
&lt;th&gt;Batch Normalization&lt;/th&gt;
&lt;th&gt;Layer Normalization&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;统计范围&lt;/td&gt;
&lt;td&gt;同一特征跨 batch 中的样本&lt;/td&gt;
&lt;td&gt;单个样本内部的特征&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;对 batch 大小的依赖&lt;/td&gt;
&lt;td&gt;有，小 batch 下统计量可能不稳定&lt;/td&gt;
&lt;td&gt;无&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;训练与推理行为&lt;/td&gt;
&lt;td&gt;使用不同来源的统计量&lt;/td&gt;
&lt;td&gt;一致&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;常见场景&lt;/td&gt;
&lt;td&gt;CNN、较大且稳定的 batch&lt;/td&gt;
&lt;td&gt;Transformer、RNN、变长序列、小 batch&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;需要注意，真实张量往往不止两个维度。例如卷积网络中的 &lt;code&gt;BatchNorm2d&lt;/code&gt; 会按通道统计 batch 与空间位置，而 Transformer 的 &lt;code&gt;LayerNorm&lt;/code&gt; 通常只作用于最后的隐藏维度。判断归一化行为时，应先明确张量形状和被归约的轴。&lt;/p&gt;</content:encoded><h:img src="https://heng-blog.pages.dev/images/social-card.svg"/><enclosure url="https://heng-blog.pages.dev/images/social-card.svg"/></item><item><title>TrainingSkills</title><link>https://heng-blog.pages.dev/blog/archived-trainingskill</link><guid isPermaLink="true">https://heng-blog.pages.dev/blog/archived-trainingskill</guid><pubDate>Sat, 16 Nov 2024 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;This blog is an intro about several practical approach for training models.&lt;/p&gt;
&lt;h2&gt;Data preprocessing&lt;/h2&gt;
&lt;h3&gt;Why do we need preprocess&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Activation functions (ReLU) works around &lt;strong&gt;zero&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If input data is biased toward positive or negative, randomly initialized layers produce biased output.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A feature with small scale has a negligible effect on backprop.&lt;/li&gt;
&lt;li&gt;Remove correlation between input features (PCA Whitening)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;And a lot more …&lt;/p&gt;
&lt;h3&gt;Normalizations&lt;/h3&gt;
&lt;p&gt;Normalization : Normalize the distribution of activations to have zero mean and unit variance&lt;/p&gt;
&lt;p&gt;Why we shall do normalization:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Internal Covariate Shift&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;provides the theoretical basis for why normalization is necessary—it stabilizes the input distribution to layers and speeds up learning.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;To Train Deeper Networks on Larger Data&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For deeper networks and larger datasets, normalization improves training stability, enhances convergence speed, and ensures better performance.&lt;/p&gt;
&lt;h4&gt;Batch Normalization&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\begin{aligned}\textbf{Input:}&amp;#x26;\quad \text{Values of }x\text{ over a mini-batch: }\mathcal{B}=\{x_{1\ldots m}\};\\&amp;#x26;\quad \text{Parameters to be learned: }\gamma,\beta\\\textbf{Output:}&amp;#x26;\quad \{y_i=\mathrm{BN}_{\gamma,\beta}(x_i)\}\\\mu_{\mathcal{B}}&amp;#x26;\leftarrow\frac{1}{m}\sum_{i=1}^{m}x_i &amp;#x26;&amp;#x26;\text{// mini-batch mean}\\\sigma_{\mathcal{B}}^2&amp;#x26;\leftarrow\frac{1}{m}\sum_{i=1}^{m}(x_i-\mu_{\mathcal{B}})^2 &amp;#x26;&amp;#x26;\text{// mini-batch variance}\\\hat{x}_i&amp;#x26;\leftarrow\frac{x_i-\mu_{\mathcal{B}}}{\sqrt{\sigma_{\mathcal{B}}^2+\epsilon}} &amp;#x26;&amp;#x26;\text{// normalize}\\y_i&amp;#x26;\leftarrow\gamma\hat{x}_i+\beta\equiv\mathrm{BN}_{\gamma,\beta}(x_i) &amp;#x26;&amp;#x26;\text{// scale and shift}\end{aligned}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;[Ioffe and Szegedy, 2015]&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Why it is good?&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Improves gradient flow&lt;/li&gt;
&lt;li&gt;Allows higher learning rates&lt;/li&gt;
&lt;li&gt;Reduces strong dependence on initialization&lt;/li&gt;
&lt;li&gt;Regularization&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Usually added after convolutional layers or fully connected layers &amp;#x26;&amp;#x26; before non-linearities&lt;/p&gt;
&lt;h3&gt;Missing Datapoint&lt;/h3&gt;
&lt;p&gt;Missing data can be handled in several ways:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Imputation: Replace missing values with a statistic like mean, median, or&lt;br&gt;
mode, or use a model to predict missing values.&lt;/li&gt;
&lt;li&gt;Removal: If the missing values are not random or comprise a large portion&lt;br&gt;
of the data, it might be better to remove those points.&lt;/li&gt;
&lt;li&gt;Indicator Variable: For some algorithms, it can be useful to create a new&lt;br&gt;
variable indicating the presence of missing data along with imputation.&lt;/li&gt;
&lt;/ol&gt;
&lt;hr&gt;
&lt;h2&gt;Activation Functions&lt;/h2&gt;
&lt;p&gt;Conclusion First:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Use ReLU. Be careful with your learning rates&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Try out Leaky ReLU / Maxout / ELU&lt;/p&gt;
&lt;p&gt;To squeeze out some marginal gains&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Don’t use sigmoid or tanh&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Don’t use sigmoid or tanh&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Sigmoid&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Formula: &lt;code class=&quot;language-math math-inline&quot;&gt;\sigma(x)=\frac{1}{1+e^{-x}}&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Outputs values between 0 and 1.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Problems&lt;/strong&gt;:
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Vanishing gradients&lt;/strong&gt;: For large positive or negative inputs, the gradient becomes very small, slowing down learning.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Outputs are not zero-centered&lt;/strong&gt;: This can cause inefficient gradient updates.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Tanh&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Formula: &lt;code class=&quot;language-math math-inline&quot;&gt;\tanh(x)=\frac{\sinh(x)}{\cosh(x)}=\frac{e^x-e^{-x}}{e^x+e^{-x}}&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Outputs values between -1 and 1.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Problems&lt;/strong&gt;:
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Vanishing gradients&lt;/strong&gt;: Like sigmoid, tanh saturates for large positive or negative inputs.&lt;/li&gt;
&lt;li&gt;Slightly better than sigmoid because it’s zero-centered, but still inferior to ReLU and its variants.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Why avoid them&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Modern networks prefer ReLU or its variants because they avoid these issues, train faster, and perform better for deep architectures.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Use ReLU. Be careful with your learning rates&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;ReLU (Rectified Linear Unit)&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;ReLU is one of the most commonly used activation functions in deep learning because it introduces &lt;strong&gt;non-linearity&lt;/strong&gt; while being computationally efficient.&lt;/li&gt;
&lt;li&gt;Defined as: &lt;code class=&quot;language-math math-inline&quot;&gt;\mathrm{ReLU}(x)=\max(0,x)&lt;/code&gt;, it outputs the input directly if positive and zero otherwise.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Why ReLU is recommended&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Sparse activation&lt;/strong&gt;: Only a subset of neurons are activated at any given time, making the network more efficient.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Avoids vanishing gradients&lt;/strong&gt;: Unlike sigmoid or tanh, ReLU doesn’t squash gradients, which helps deeper networks learn effectively.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Caution about learning rates&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Problem&lt;/strong&gt;: ReLU can cause the “dead neuron” problem, where some neurons output zero for all inputs and stop learning. This happens when the input to the ReLU is consistently negative due to high learning rates.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Solution&lt;/strong&gt;: Use a &lt;strong&gt;moderate learning rate&lt;/strong&gt; and techniques like proper weight initialization or adaptive optimizers (e.g., Adam).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Experiment with Leaky ReLU, Maxout, or ELU for improved performance or to avoid specific issues with ReLU.&lt;/h3&gt;
&lt;p&gt;Focus on incremental improvements when the model is already performing well.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Leaky ReLU&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A variant of ReLU that allows a small, non-zero gradient for negative inputs, preventing the “dead neuron” problem.&lt;/li&gt;
&lt;li&gt;Formula: &lt;code class=&quot;language-math math-inline&quot;&gt;\text{Leaky ReLU}(x)=\left\{\begin{array}{lll}x &amp;#x26; x&gt;0\;\alpha x &amp;#x26; x\le 0\end{array}\right.&lt;/code&gt;, where &lt;code class=&quot;language-math math-inline&quot;&gt;\alpha&lt;/code&gt; is a small positive constant (e.g., 0.01).&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Maxout&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Generalizes ReLU and allows learning the activation function directly.&lt;/li&gt;
&lt;li&gt;Formula: &lt;code class=&quot;language-math math-inline&quot;&gt;\mathrm{Maxout}(x)=\max(w_T^1x+b_1,\,w_T^2x+b_2)&lt;/code&gt;, where &lt;code class=&quot;language-math math-inline&quot;&gt;w_1,\,w_2&lt;/code&gt; are learnable parameters.&lt;/li&gt;
&lt;li&gt;Benefits: Provides greater flexibility in modeling but increases the number of parameters.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;ELU (Exponential Linear Unit)&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Smooths out the ReLU function for negative values, providing better gradient flow.&lt;/li&gt;
&lt;li&gt;Formula: &lt;code class=&quot;language-math math-inline&quot;&gt;\mathrm{ELU}(x)=\left\{\begin{array}{lll}x &amp;#x26; x&gt;0\;\alpha(\exp(x)-1) &amp;#x26; x\le 0\end{array}\right.&lt;/code&gt;, where &lt;code class=&quot;language-math math-inline&quot;&gt;\alpha&gt;0&lt;/code&gt; controls the curve for negative values.&lt;/li&gt;
&lt;li&gt;Negative saturation regime compared with Leaky ReLU adds some robustness to noise&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Weight Initialization&lt;/h2&gt;
&lt;p&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;Y=W*x&lt;/code&gt;&lt;br&gt;
If all weights in &lt;code&gt;W&lt;/code&gt; are 0 , Output &lt;code&gt;Y&lt;/code&gt;will be always 0 and then gradients will go to 0, causing gradient vanishing problem.&lt;/p&gt;
&lt;p&gt;There are several existing approach to deal with initialization:&lt;/p&gt;
&lt;h3&gt;Small Random Numbers(Doesn’t work for deeper networks)&lt;/h3&gt;
&lt;p&gt;Sample from a gaussian distribution with 0 mean and given standard deviation (such as 0.01)&lt;/p&gt;
&lt;p&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;W\sim N(\mu,\sigma^2)&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;W = 0.01*np.random.randn(Din,Dout)&lt;/code&gt;(for conv layers, Din is &lt;code class=&quot;language-math math-inline&quot;&gt;{fiter_s ize}^{2}*input_c hannels&lt;/code&gt;)&lt;/p&gt;
&lt;p&gt;Why not working for deeper networks?&lt;/p&gt;
&lt;p&gt;After several forward pass, the X will be 0 mean and negligible std.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;W = 0.01*np.random.randn(Din,Dout)
x = tanh(x@W)

==&gt; after 6 forward pass
x = x@W@W@W@W@W@W
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Xavier Initialization&lt;/h3&gt;
&lt;p&gt;Approach: Set the variance according to # of input neurons&lt;/p&gt;
&lt;p&gt;Intuition: input and output with the same variance to prevent vanishing or exploding problem&lt;/p&gt;
&lt;p&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;W\sim N(\mu,\sigma^2)&lt;/code&gt; and &lt;code class=&quot;language-math math-inline&quot;&gt;Var(W)=\frac{1}{D_{in}}&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;&lt;code&gt;W = np.random.randn(Din,Dout)/np.sqrt(Din)&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Let: &lt;code class=&quot;language-math math-inline&quot;&gt;y=x_1w_1+x_2w_2+\cdots+x_{D_{in}}w_{D_{in}}&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Assume:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\text{Var}(x_1)=\text{Var}(x_2)=\cdots=\text{Var}(x_{D_{in}})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We want:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\text{Var}(y)=\text{Var}(x_i)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\text{Var}(y)=\text{Var}(x_1w_1+x_2w_2+\cdots+x_{D_{in}}w_{D_{in}})&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;=D_{in},\;\text{Var}(x_iw_i)\quad\text{[Assume all }x_i,w_i\text{ are i.i.d.]}&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;=D_{in},\;\text{Var}(x_i)Var(w_i)\quad\text{[Assume all }x_i,w_i\text{ are zero mean]}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So,&lt;code class=&quot;language-math math-inline&quot;&gt;Var(y)=Var(x_i)&lt;/code&gt; only when &lt;code class=&quot;language-math math-inline&quot;&gt;Var(W)=\frac{1}{D_{in}}&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;While for ReLU, activations collapse to zero again, no learning.&lt;/p&gt;
&lt;h3&gt;Kaiming Initialization&lt;/h3&gt;
&lt;p&gt;For a layer with input dimension &lt;code class=&quot;language-math math-inline&quot;&gt;D_{in}&lt;/code&gt; (number of input neurons), the weights are initialized as:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;W\sim N(0,\frac{2}{D_{in}})&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This means:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The weights are drawn from a normal distribution with a mean of 0 and a variance of &lt;code class=&quot;language-math math-inline&quot;&gt;\frac{2}{D_{in}}&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The scaling factor &lt;code class=&quot;language-math math-inline&quot;&gt;\frac{2}{D_{in}}&lt;/code&gt; accounts for the ReLU activation function, ensuring that the variance of the outputs remains stable as it propagates through the network.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Kaiming initialization is particularly effective when using ReLU, Leaky ReLU, or similar activation functions that introduce sparsity. For networks with sigmoid or tanh activations, Xavier initialization is typically preferred.&lt;/p&gt;
&lt;h2&gt;Optimization&lt;/h2&gt;
&lt;h3&gt;Momentum + SGD&lt;/h3&gt;
&lt;p&gt;SGD:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;x_{t+1}=x_t-\alpha\nabla f(x_t)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;loop:
    dx = compute_gradient(x)
    x -= learning_rate * dx
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;SGD + Momentum:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;v_{t+1}=\rho v_t+\nabla f(x_t)&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;x_{t+1}=x_t-\alpha v_{t+1}&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;vx = 0
loop:
    dx = compute_gradient(x)
    vx = rho*vx + dx
    x -= learning_rate * dx
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;/archived-blog/figs/TrainingSkill/SGDMomentum.png&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;Reduce the oscillations in the rapid change directions. (Avoid zig-zag)&lt;/p&gt;
&lt;h3&gt;AdaGrad&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;grad_squared = 0
loop:
    dx = compute_gradient(x)
    grad_squared += dx * dx
    x -= learning_rate * dx / (np.sqrt(grad_squared) + 1e-7)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Such that:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Progress along “steep” directions is damped&lt;br&gt;
progress along “flat” directions is accelerated&lt;/li&gt;
&lt;li&gt;After long time, &lt;code class=&quot;language-math math-inline&quot;&gt;\Delta(x)\to 0&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;RMSProp:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;grad_squared = 0
loop:
    dx = compute_gradient(x)
    grad_squared = decay_rate * grad_squared + (1 - decay_rate) * dx * dx
    x -= learning_rate * dx / (np.sqrt(grad_squared) + 1e-7)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;can make momentum smoother&lt;/p&gt;
&lt;h3&gt;Adams&lt;/h3&gt;
&lt;p&gt;from RMSProp:&lt;/p&gt;
&lt;p&gt;(Almost)&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;first_moment = 0
second_moment = 0
loop:
    dx = compute_gradient(x)
    first_moment = beta1 * first_moment + (1 - beta1) * dx [momentum]
    second_moment = beta2 * second_moment + (1 - beta2) * dx * dx [adagrad/RMSProp]
    x -= learning_rate * first_moment / (np.sqrt(second_moment) + 1e-7)

&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;(Full form)&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;first_moment = 0
second_moment = 0
for t in range(1, num_iterations):
    dx = compute_gradient(x)

    first_moment = beta1 * first_moment + (1 - beta1) * dx
    second_moment = beta2 * second_moment + (1 - beta2) * dx * dx

    first_unbias = first_moment / (1 - beta1 ** t)
    second_unbias = second_moment / (1 - beta2 ** t)

    x -= learning_rate * first_unbias / (np.sqrt(second_unbias) + 1e-7)
&lt;/code&gt;&lt;/pre&gt;</content:encoded><h:img src="https://heng-blog.pages.dev/images/social-card.svg"/><enclosure url="https://heng-blog.pages.dev/images/social-card.svg"/></item><item><title>Autoencoder</title><link>https://heng-blog.pages.dev/blog/archived-autoencoder</link><guid isPermaLink="true">https://heng-blog.pages.dev/blog/archived-autoencoder</guid><pubDate>Wed, 13 Nov 2024 00:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;What is Autoencoder&lt;/h2&gt;
&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;An autoencoder is a type of algorithm with the primary&lt;br&gt;
purpose of learning an “informative” representation of the data that&lt;br&gt;
can be used for different applications by learning to reconstruct a set&lt;br&gt;
of input observations well enough.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2003.05991&quot;&gt;https://arxiv.org/abs/2003.05991&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;There are three main components in the autoencoders: encoder. latent feature representation and a decoder.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;The encoder and decoder are simply functions, while with the name latent feature representation, one typically intends a tensor of real numbers&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;a href=&quot;https://arxiv.org/pdf/2201.03898&quot;&gt;https://arxiv.org/pdf/2201.03898&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;If Decoder and Encoder are linear model, the autoencoder will achieve same latent presentation of PCA.&lt;/p&gt;
&lt;p&gt;to prove:&lt;a href=&quot;http://toe.lt/1a&quot;&gt;http://toe.lt/1a&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/1804.10253&quot;&gt;https://arxiv.org/abs/1804.10253&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;img src=&quot;/archived-blog/figs/Autoencoder/EncoderDecoder.png&quot; alt=&quot;encoder-decoder architecture&quot;&gt;&lt;/p&gt;
&lt;p&gt;The mission of autoencoder is to learn the functions &lt;code class=&quot;language-math math-inline&quot;&gt;\mathit{A}:\mathbb{R}^{\mathit{n}}\to\mathbb{R}^{\mathit{p}}&lt;/code&gt; (encoder) and &lt;code class=&quot;language-math math-inline&quot;&gt;\mathit{B}:\mathbb{R}^{\mathit{p}}\to\mathbb{R}^{\mathit{n}}&lt;/code&gt; (decoder) that satisfy&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-math math-display&quot;&gt;\arg\min_{\mathit{A},\mathit{B}}\,\mathit{E}[\Delta(\mathbf{x},\mathit{B}\circ\mathit{A}(\mathbf{x})],&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code class=&quot;language-math math-inline&quot;&gt;\mathit{M}&lt;/code&gt;&lt;br&gt;
where &lt;code class=&quot;language-math math-inline&quot;&gt;\mathit{E}&lt;/code&gt; is the expectation over the distribution of &lt;code class=&quot;language-math math-inline&quot;&gt;\mathit{x}&lt;/code&gt; , and &lt;code class=&quot;language-math math-inline&quot;&gt;\Delta&lt;/code&gt; is the reconstruction loss function, which measures the distance between the output of the decoder and the intput. The latter is usually set to be the &lt;code class=&quot;language-math math-inline&quot;&gt;\ell_{2}&lt;/code&gt; -norm.&lt;/p&gt;
&lt;h2&gt;Easiest way to realize a autoencoder&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;class Encoder(nn.Module):
    def __init__(self, input_dim, feature_dim):
        super(Encoder, self).__init__()
        self.fc = nn.Linear(input_dim, feature_dim)

    def forward(self, x):
        x = torch.relu(self.fc(x))
        return x

class Decoder(nn.Module):
    def __init__(self, feature_dim, output_dim):
        super(Decoder, self).__init__()
        self.fc = nn.Linear(feature_dim, output_dim)

    def forward(self, x):
        x = torch.sigmoid(self.fc(x))
        return x

class Autoencoder(nn.Module):
    def __init__(self, input_dim, feature_dim):
        super(Autoencoder, self).__init__()
        self.encoder = Encoder(input_dim, feature_dim)
        self.decoder = Decoder(feature_dim, input_dim)

    def forward(self, x):
        encoded = self.encoder(x)
        decoded = self.decoder(encoded)
        return decoded
&lt;/code&gt;&lt;/pre&gt;</content:encoded><h:img src="https://heng-blog.pages.dev/images/social-card.svg"/><enclosure url="https://heng-blog.pages.dev/images/social-card.svg"/></item><item><title>DenoisingAutoencoder</title><link>https://heng-blog.pages.dev/blog/archived-denoisingautoencoder</link><guid isPermaLink="true">https://heng-blog.pages.dev/blog/archived-denoisingautoencoder</guid><pubDate>Thu, 14 Nov 2024 00:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;Hypothesis of Denoising Autoencoder&lt;/h2&gt;
&lt;blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;robustness to partial destruction
of the input, i.e., partially destroyed inputs should
yield almost the same representation.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;such hypothesis is motivated by&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;a good representation is expected to capture stable structures in the
form of dependencies and regularities characteristic of
the (unknown) distribution of its observed input. For
high dimensional redundant input (such as images) at
least, such structures are likely to depend on evidence
gathered from a combination of many input dimen
sions. They should thus be recoverable from partial
observation only.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;a href=&quot;https://www.cs.toronto.edu/~larocheh/publications/icml-2008-denoising-autoencoders.pdf&quot;&gt;https://www.cs.toronto.edu/~larocheh/publications/icml-2008-denoising-autoencoders.pdf&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;</content:encoded><h:img src="https://heng-blog.pages.dev/images/social-card.svg"/><enclosure url="https://heng-blog.pages.dev/images/social-card.svg"/></item><item><title>Lagrangian Optimization</title><link>https://heng-blog.pages.dev/blog/archived-optimization</link><guid isPermaLink="true">https://heng-blog.pages.dev/blog/archived-optimization</guid><pubDate>Sat, 06 Apr 2024 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;This post introduces the concept of &lt;code&gt;Lagrangian Optimization&lt;/code&gt;. This is a method for finding the local extrema of a multivariable function when the variables are subject to one or more constraint conditions. This method can transform an optimization problem with n variables and k constraint conditions into a problem of solving a system of equations with n + k variables.这篇帖子介绍了&lt;code&gt;Lagrangian Optimization&lt;/code&gt;。这是一种是一种寻找多元函数在其变量受到一个或多个条件的约束时的局部极值的方法。这种方法可以将一个有n个变量与k个约束条件的最优化问题转换为一个解有n + k个变量的方程组的解的问题。&lt;/p&gt;
&lt;p&gt;The discussion starts with the case of a single-variable equality constraint, and then gradually generalizes to the cases of multiple-variable equalities and single-variable inequalities.首先从单变量等式约束条件开始讨论 ,随后逐渐推广到多变量等式，单变量不等式的情况&lt;/p&gt;
&lt;p&gt;Finally, the post presents the &lt;code&gt;Lagrangian Optimization&lt;/code&gt; equations for the cases of multiple-variable equalities and multiple-variable inequalities.最后给出多变量等式、多变量不等式对应的&lt;code&gt;Lagrangian Optimization&lt;/code&gt;方程&lt;/p&gt;
&lt;p&gt;Lagrangian Optimization.pdf&lt;/p&gt;</content:encoded><h:img src="https://heng-blog.pages.dev/images/social-card.svg"/><enclosure url="https://heng-blog.pages.dev/images/social-card.svg"/></item><item><title>SVM</title><link>https://heng-blog.pages.dev/blog/archived-svm</link><guid isPermaLink="true">https://heng-blog.pages.dev/blog/archived-svm</guid><pubDate>Tue, 26 Mar 2024 00:00:00 GMT</pubDate><content:encoded>&lt;h2&gt;SVM&lt;/h2&gt;
&lt;p&gt;not finished (await rest SVR)&lt;/p&gt;
&lt;p&gt;SVM.pdf&lt;/p&gt;</content:encoded><h:img src="https://heng-blog.pages.dev/images/social-card.svg"/><enclosure url="https://heng-blog.pages.dev/images/social-card.svg"/></item></channel></rss>