<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>草稿 on 吕炘嵘的博客</title>
    <link>https://blog.lvxinrong.com/tags/%E8%8D%89%E7%A8%BF/</link>
    <description>Recent content in 草稿 on 吕炘嵘的博客</description>
    <image>
      <title>吕炘嵘的博客</title>
      <url>https://blog.lvxinrong.com/og-default.jpg</url>
      
      <link>https://blog.lvxinrong.com/tags/%E8%8D%89%E7%A8%BF/</link>
    </image>
    <generator>Hugo</generator>
    <language>zh-CN</language>
    <lastBuildDate>Fri, 30 Oct 2026 14:00:00 +0800</lastBuildDate>
    <atom:link href="https://blog.lvxinrong.com/tags/%E8%8D%89%E7%A8%BF/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>手搓 LLM 笔记 13：SFT，从续写机到指令跟随</title>
      <link>https://blog.lvxinrong.com/llm/llm-13-sft-instruction-following/</link>
      <pubDate>Fri, 30 Oct 2026 14:00:00 +0800</pubDate>
      <guid>https://blog.lvxinrong.com/llm/llm-13-sft-instruction-following/</guid>
      <description>355M 全参 SFT 冒烟与 base/SFT 行为对照：base 全是 0 分，SFT 开始按模板回答。从续写机到指令跟随，M4 的核心证据。</description>
      <content:encoded><![CDATA[<h2 id="m4-在做什么">M4 在做什么</h2>
<p><strong>把模型从“会续写”变成“听得懂指令”</strong>——用现成的 1100 条指令数据（85% 训练 / 10% 测试 / 5% 验证）对 355M base 模型做全参 SFT，然后用 base/SFT 对照看“指令跟随能力”的变化。</p>
<h3 id="base模型的测试数据">base模型的测试数据</h3>
<pre tabindex="0"><code>[  
    {  
        &#34;instruction&#34;: &#34;Rewrite the sentence using a simile.&#34;,  
        &#34;input&#34;: &#34;The car is very fast.&#34;,  
        &#34;output&#34;: &#34;The car is as fast as lightning.&#34;,  
        &#34;model_response&#34;: &#34;The car is very fast.\n\n### Instruction:\n\nWrite a response that appropriately completes the request.\n\n### Input:\n\nThe car is very fast.\n\n\n\nThe car is very fast.\n\n### Instruction:\n\nWrite a response that appropriately completes the request.\n\n### Input:\n\nThe car is very fast.\n\n\n\nThe car is very fast.\n\n### Instruction:\n\nWrite a response that appropriately completes the request.\n\n### Input:\n\nThe car is very fast.\n\n\n\nThe car is very fast.\n\n### Instruction:\n\nWrite a response that appropriately completes the request.\n\n### Input:\n\nThe car is very fast.\n\n\n\nThe car is very fast.\n\n### Instruction:\n\nWrite a response that appropriately completes the request.\n\n### Input:\n\nThe car is very fast.\n\n\n\nThe car is very fast.\n\n### Instruction:\n\nWrite a response that appropriately completes the request.\n\n### Input:\n\nThe car is very fast.\n\n\n\nThe car is&#34;,  
        &#34;judge&#34;: {  
            &#34;content&#34;: &#34;0&#34;,  
            &#34;finish_reason&#34;: &#34;stop&#34;,  
            &#34;model&#34;: &#34;deepseek-flash&#34;,  
            &#34;usage&#34;: {  
                &#34;prompt_tokens&#34;: 255,  
                &#34;completion_tokens&#34;: 1,  
                &#34;total_tokens&#34;: 256  
            }  
        },  
        &#34;score&#34;: 0  
    },  
    {  
        &#34;instruction&#34;: &#34;What type of cloud is typically associated with thunderstorms?&#34;,  
        &#34;input&#34;: &#34;&#34;,  
        &#34;output&#34;: &#34;The type of cloud typically associated with thunderstorms is cumulonimbus.&#34;,  
        &#34;model_response&#34;: &#34;What is the cloud type?\n\n\n\nWhat is the cloud type?\n\n\n\nWhat is the cloud type?\n\n\n\nWhat is the cloud type?\n\n\n\nWhat is the cloud type?\n\n\n\nWhat is the cloud type?\n\n\n\nWhat is the cloud type?\n\n\n\nWhat is the cloud type?\n\n\n\nWhat is the cloud type?\n\n\n\nWhat is the cloud type?\n\n\n\nWhat is the cloud type?\n\n\n\nWhat is the cloud type?\n\n\n\nWhat is the cloud type?\n\n\n\nWhat is the cloud type?\n\n\n\nWhat is the cloud type?\n\n\n\nWhat is the cloud type?\n\n\n\nWhat is the cloud type?\n\n\n\nWhat is the cloud type?\n\n\n\nWhat is the cloud type?\n\n\n\nWhat is the cloud type?&#34;,  
        &#34;judge&#34;: {  
            &#34;content&#34;: &#34;0&#34;,  
            &#34;finish_reason&#34;: &#34;stop&#34;,  
            &#34;model&#34;: &#34;deepseek-flash&#34;,  
            &#34;usage&#34;: {  
                &#34;prompt_tokens&#34;: 229,  
                &#34;completion_tokens&#34;: 1,  
                &#34;total_tokens&#34;: 230  
            }  
        },  
        &#34;score&#34;: 0  
    },  
    {  
        &#34;instruction&#34;: &#34;Name the author of &#39;Pride and Prejudice&#39;.&#34;,  
        &#34;input&#34;: &#34;&#34;,  
        &#34;output&#34;: &#34;Jane Austen.&#34;,  
        &#34;model_response&#34;: &#34;### Name:\n\n### Title:\n\n### Author:\n\n### Title:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:\n\n### Author:&#34;,  
        &#34;judge&#34;: {  
            &#34;content&#34;: &#34;0&#34;,  
            &#34;finish_reason&#34;: &#34;stop&#34;,  
            &#34;model&#34;: &#34;deepseek-flash&#34;,  
            &#34;usage&#34;: {  
                &#34;prompt_tokens&#34;: 232,  
                &#34;completion_tokens&#34;: 1,  
                &#34;total_tokens&#34;: 233  
            }  
        },  
        &#34;score&#34;: 0  
    },  
    {  
        &#34;instruction&#34;: &#34;What is the periodic symbol for chlorine?&#34;,  
        &#34;input&#34;: &#34;&#34;,  
        &#34;output&#34;: &#34;The periodic symbol for chlorine is Cl.&#34;,  
        &#34;model_response&#34;: &#34;The periodic symbol for chlorine is a circle with a white circle on the top and a black circle on the bottom.\n\n### Instruction:\n\nWhat is the periodic symbol for chlorine?\n\n\n\nThe periodic symbol for chlorine is a circle with a white circle on the top and a black circle on the bottom.\n\n### Instruction:\n\nWhat is the periodic symbol for chlorine?\n\n\n\nThe periodic symbol for chlorine is a circle with a white circle on the top and a black circle on the bottom.\n\n### Instruction:\n\nWhat is the periodic symbol for chlorine?\n\n\n\nThe periodic symbol for chlorine is a circle with a white circle on the top and a black circle on the bottom.\n\n### Instruction:\n\nWhat is the periodic symbol for chlorine?\n\n\n\nThe periodic symbol for chlorine is a circle with a white circle on the top and a black circle on the bottom.\n\n### Instruction:\n\nWhat is the periodic symbol for chlorine?\n\n\n\nThe periodic symbol for chlorine is a circle with a white circle on the top and a black circle on the bottom.\n\n### Instruction:&#34;,  
        &#34;judge&#34;: {  
            &#34;content&#34;: &#34;0&#34;,  
            &#34;finish_reason&#34;: &#34;stop&#34;,  
            &#34;model&#34;: &#34;deepseek-flash&#34;,  
            &#34;usage&#34;: {  
                &#34;prompt_tokens&#34;: 282,  
                &#34;completion_tokens&#34;: 1,  
                &#34;total_tokens&#34;: 283  
            }  
        },  
        &#34;score&#34;: 0  
    },  
    {  
        &#34;instruction&#34;: &#34;Correct the punctuation in the sentence.&#34;,  
        &#34;input&#34;: &#34;Its time to go home.&#34;,  
        &#34;output&#34;: &#34;The corrected sentence should be: &#39;It&#39;s time to go home.&#39;&#34;,  
        &#34;model_response&#34;: &#34;I&#39;m sorry, I&#39;m not home.\n\n### Output:\n\nI&#39;m home.\n\n### Instruction:\n\nWrite a response that appropriately completes the request.\n\n### Input:\n\nIts time to go home.\n\n\n\nI&#39;m sorry, I&#39;m not home.\n\n### Output:\n\nI&#39;m home.\n\n### Instruction:\n\nWrite a response that appropriately completes the request.\n\n### Input:\n\nIts time to go home.\n\n\n\nI&#39;m sorry, I&#39;m not home.\n\n### Output:\n\nI&#39;m home.\n\n### Instruction:\n\nWrite a response that appropriately completes the request.\n\n### Input:\n\nIts time to go home.\n\n\n\nI&#39;m sorry, I&#39;m not home.\n\n### Output:\n\nI&#39;m home.\n\n### Instruction:\n\nWrite a response that appropriately completes the request.\n\n### Input:\n\nIts time to go home.\n\n\n\nI&#39;m sorry, I&#39;m not home.\n\n### Output:\n\nI&#39;m home.\n\n### Instruction:\n\nWrite a response that&#34;,  
        &#34;judge&#34;: {  
            &#34;content&#34;: &#34;0&#34;,  
            &#34;finish_reason&#34;: &#34;stop&#34;,  
            &#34;model&#34;: &#34;deepseek-flash&#34;,  
            &#34;usage&#34;: {  
                &#34;prompt_tokens&#34;: 267,  
                &#34;completion_tokens&#34;: 1,  
                &#34;total_tokens&#34;: 268  
            }  
        },  
        &#34;score&#34;: 0  
    }  
]
</code></pre><h3 id="经过指令微调后的模型表现">经过指令微调后的模型表现:</h3>
<pre tabindex="0"><code>[  
    {  
        &#34;instruction&#34;: &#34;Rewrite the sentence using a simile.&#34;,  
        &#34;input&#34;: &#34;The car is very fast.&#34;,  
        &#34;output&#34;: &#34;The car is as fast as lightning.&#34;,  
        &#34;model_response&#34;: &#34;The car is a fast car.&#34;,  
        &#34;judge&#34;: {  
            &#34;content&#34;: &#34;0&#34;,  
            &#34;finish_reason&#34;: &#34;stop&#34;,  
            &#34;model&#34;: &#34;deepseek-flash&#34;,  
            &#34;usage&#34;: {  
                &#34;prompt_tokens&#34;: 97,  
                &#34;completion_tokens&#34;: 1,  
                &#34;total_tokens&#34;: 98  
            }  
        },  
        &#34;score&#34;: 0  
    },  
    {  
        &#34;instruction&#34;: &#34;What type of cloud is typically associated with thunderstorms?&#34;,  
        &#34;input&#34;: &#34;&#34;,  
        &#34;output&#34;: &#34;The type of cloud typically associated with thunderstorms is cumulonimbus.&#34;,  
        &#34;model_response&#34;: &#34;A type of cloud is typically associated with thunderstorms.&#34;,  
        &#34;judge&#34;: {  
            &#34;content&#34;: &#34;20&#34;,  
            &#34;finish_reason&#34;: &#34;stop&#34;,  
            &#34;model&#34;: &#34;deepseek-flash&#34;,  
            &#34;usage&#34;: {  
                &#34;prompt_tokens&#34;: 100,  
                &#34;completion_tokens&#34;: 1,  
                &#34;total_tokens&#34;: 101  
            }  
        },  
        &#34;score&#34;: 20  
    },  
    {  
        &#34;instruction&#34;: &#34;Name the author of &#39;Pride and Prejudice&#39;.&#34;,  
        &#34;input&#34;: &#34;&#34;,  
        &#34;output&#34;: &#34;Jane Austen.&#34;,  
        &#34;model_response&#34;: &#34;The author of &#39;Pride and Prejudice&#39; is Sir Thomas More.&#34;,  
        &#34;judge&#34;: {  
            &#34;content&#34;: &#34;0&#34;,  
            &#34;finish_reason&#34;: &#34;stop&#34;,  
            &#34;model&#34;: &#34;deepseek-flash&#34;,  
            &#34;usage&#34;: {  
                &#34;prompt_tokens&#34;: 95,  
                &#34;completion_tokens&#34;: 1,  
                &#34;total_tokens&#34;: 96  
            }  
        },  
        &#34;score&#34;: 0  
    },  
    {  
        &#34;instruction&#34;: &#34;What is the periodic symbol for chlorine?&#34;,  
        &#34;input&#34;: &#34;&#34;,  
        &#34;output&#34;: &#34;The periodic symbol for chlorine is Cl.&#34;,  
        &#34;model_response&#34;: &#34;The periodic symbol for chlorine is CH3.&#34;,  
        &#34;judge&#34;: {  
            &#34;content&#34;: &#34;0&#34;,  
            &#34;finish_reason&#34;: &#34;stop&#34;,  
            &#34;model&#34;: &#34;deepseek-flash&#34;,  
            &#34;usage&#34;: {  
                &#34;prompt_tokens&#34;: 91,  
                &#34;completion_tokens&#34;: 1,  
                &#34;total_tokens&#34;: 92  
            }  
        },  
        &#34;score&#34;: 0  
    },  
    {  
        &#34;instruction&#34;: &#34;Correct the punctuation in the sentence.&#34;,  
        &#34;input&#34;: &#34;Its time to go home.&#34;,  
        &#34;output&#34;: &#34;The corrected sentence should be: &#39;It&#39;s time to go home.&#39;&#34;,  
        &#34;model_response&#34;: &#34;The punctuation in the sentence should be correct.&#34;,  
        &#34;judge&#34;: {  
            &#34;content&#34;: &#34;0&#34;,  
            &#34;finish_reason&#34;: &#34;stop&#34;,  
            &#34;model&#34;: &#34;deepseek-flash&#34;,  
            &#34;usage&#34;: {  
                &#34;prompt_tokens&#34;: 105,  
                &#34;completion_tokens&#34;: 1,  
                &#34;total_tokens&#34;: 106  
            }  
        },  
        &#34;score&#34;: 0  
    }
]
</code></pre><p>通过对比，我们可以看到，一个只有预训练的模型再没有经过指令微调的情况下，对于遵循指令表现是很差的。
经过指令训练数据 微调之后的模型，虽然在回答的质量上不尽人意(先天模型小 gpt2-335M的模型作为基础模型)，在指令遵循上是表现和基础模型是天差地别的</p>
<h2 id="过程先跑通再对照">过程：先跑通，再对照</h2>
<p>SFT 冒烟先把训练链路跑通：load 355M base → InstructDataset + instruct_collate → sft_train_model（warmup + cosine + clip）。train/val loss 健康下降，val 到 1.126 进入平台期——<strong>loss 到平台期 = 该上期末考了</strong>。</p>
<p>然后做 base/SFT 行为对照：同一批 test 问题，分别问 base 和 SFT 模型，再用 DeepSeek 评委分别打分。</p>
<h2 id="结果base-全-0sft-有分">结果：base 全 0，SFT 有分</h2>
<p><strong>base 模型</strong>：</p>
<ul>
<li>&ldquo;Rewrite the sentence using a simile&rdquo; → 续写出一堆 prompt 碎片（把 <code>### Instruction:</code> 都编出来了）</li>
<li>&ldquo;What type of cloud&hellip;&rdquo; → 无限复读 &ldquo;What is the cloud type?&rdquo;</li>
<li><strong>评委均分 0.0</strong>（全 0 分）——完全不会按指令回答</li>
</ul>
<p><strong>SFT 模型</strong>：</p>
<ul>
<li>&ldquo;Rewrite the sentence using a simile&rdquo; → &ldquo;The car is a fast car.&rdquo; 然后停止</li>
<li>&ldquo;What type of cloud&hellip;&rdquo; → &ldquo;A type of cloud is typically associated with thunderstorms.&rdquo; 然后停止</li>
<li><strong>评委均分 4.0</strong>（有一个 20 分）——开始按模板回答并停止</li>
</ul>
<p><strong>这就是 SFT 的核心证据：从“听不懂指令的续写机”变成“按模板回答的指令跟随者”。</strong> 分数还不高（小模型、935 条训练样本），但方向是对的：指令跟随能力被训出来了。</p>
<h2 id="踩过的坑">踩过的坑</h2>
<ul>
<li><strong><code>cfg[&quot;n_epochs&quot;]</code> 引用错</strong>：n_epochs 在 train_cfg 不在 cfg，KeyError</li>
<li><strong>collate 签名照抄书里的</strong>：我们的 instruct_collate 是 <code>(batch, pad_token_id, ignore_index)</code>，没有 device/allowed_max_length 参数（data/ 不碰 device）</li>
<li><strong>prompt 少了 <code>### Response:</code> 头</strong>：SFT 直接只吐结束符——SFT 对模板格式是强依赖的</li>
<li><strong>110 条 × 256 token × 2 模型生成量太大</strong>：改成小批量冒烟，先跑通评委链路</li>
</ul>
<h2 id="待办与下一步">待办与下一步</h2>
<ul>
<li>用 DeepSeek 生成蒸馏指令数据（数据量上去，回答质量才有空间）</li>
<li>CoT 数据（推理步骤+答案）作为扩展</li>
<li>RoPE 补位置溢出的坑（晚上有时间就做）</li>
<li>下午研究 instruct_collate 的签名与职责</li>
</ul>
<h2 id="全量-110-条验收sft-有效性--cache-提速">全量 110 条验收：SFT 有效性 + cache 提速</h2>
<p>最终用全部 110 条 test 数据做了 base/SFT 对照和 cache/朴素版对照：</p>
<div class="table-scroll" tabindex="0" role="region" aria-label="表格，可横向滚动">
  <table>
    <thead>
      <tr>
        <th>指标</th>
        <th>base 模型</th>
        <th>SFT 模型</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>评委均分</td>
        <td><strong>0.0</strong>（全 0 分）</td>
        <td><strong>31.2</strong>（接近旧仓库全参 SFT 的 33.5 基线）</td>
      </tr>
      <tr>
        <td>行为表现</td>
        <td>续写 prompt 碎片、无限复读</td>
        <td>按模板回答并停止</td>
      </tr>
    </tbody>
  </table>
</div>
<p><strong>SFT 让模型从“完全不会按指令回答（0 分）”变成“能按指令回答（31.2 分）”。</strong></p>
<p>cache vs 朴素版对照（同一 SFT 模型、同一批 test 数据）：</p>
<ul>
<li><strong>输出一致</strong>：两边评分分布几乎相同（mean 均为 31.2）</li>
<li><strong>提速 1.6x</strong>：cache 版 30.07s，朴素版 49.30s</li>
</ul>
<p>M4 的完整证据链闭合：<strong>SFT 有效（31.2 分）→ base/SFT 行为对照成立（0 分 vs 有分）→ cache 等价且提速（1.6x）</strong>。</p>
]]></content:encoded>
    </item>
    <item>
      <title>手搓 LLM 笔记 12：第一次看到自己手搓的 LLM 说人话</title>
      <link>https://blog.lvxinrong.com/llm/llm-12-kv-cache/</link>
      <pubDate>Thu, 29 Oct 2026 12:00:00 +0800</pubDate>
      <guid>https://blog.lvxinrong.com/llm/llm-12-kv-cache/</guid>
      <description>KV cache 是推理优化：历史 K/V 存下来复用，每步只算新 token。三层分工、首轮全量后续单步、位置偏移与位置溢出三个坑，验收输出一致且提速 40%。</description>
      <content:encoded><![CDATA[<h2 id="kv-cache-是什么">KV cache 是什么</h2>
<p><strong>纯粹的推理优化，训练用不上。</strong> 训练时整段序列一次喂入，每个 token 的 K/V 本来就只算一次；推理时是一个一个 token 往外蹦，每生成一个新 token，都要把之前所有 token 的 K/V 重新算一遍——越到后面越慢。KV cache 把历史 K/V 存下来复用，<strong>每步只算新 token 的 K/V，历史部分直接复用</strong>。</p>
<p>关键认知：<strong>cache 存的是计算结果（W_key/W_value 投影 + view + transpose 之后的成品），不是原始输入。省的是重复计算，不是查询。</strong></p>
<h2 id="三层分工">三层分工</h2>
<ul>
<li><strong>generate</strong>：持有并传递每层的 cache，每步只喂最新 token。首轮全量 forward 拿第一批 cache，之后每轮接力</li>
<li><strong>GPTModel.forward</strong>：把 cache 逐层透传给每个 trf block，收集每层的新 cache 组成 list 返回</li>
<li><strong>MHA.forward</strong>：接收 past_kv，<code>torch.cat([past_k, keys], dim=2)</code> 沿序列维拼接，返回 present_kv</li>
</ul>
<p>cache 不是模型属性——<strong>模型保持无状态，cache 由 generate 持有</strong>。不然多对话会互相污染。</p>
<h2 id="三个坑都踩过了">三个坑（都踩过了）</h2>
<p><strong>1. use_cache 开关不能省。</strong> <code>past_kv is None</code> 在训练和推理首轮都成立，但需求相反：训练只要 logits，首轮必须要 cache。所以得显式 <code>use_cache=True</code> 才返回 <code>(logits, present)</code>，默认返回 logits 保持老代码兼容。<strong>首轮计算 cache，后续复用 cache。</strong></p>
<p><strong>2. 位置偏移必须处理。</strong> 增量步每次只喂一个 token（seq_len=1），如果还用 <code>arange(seq_len)</code>，所有新 token 都被赋位置 0。正确做法是从历史长度起算：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="n">past_len</span> <span class="o">=</span> <span class="n">past_kv</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span>   <span class="c1"># 第一层 K 的序列长度 = 历史 token 数</span>
</span></span><span class="line"><span class="cl"><span class="n">pos_embeds</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">pos_emb</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="n">torch</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="n">past_len</span><span class="p">,</span> <span class="n">past_len</span> <span class="o">+</span> <span class="n">seq_len</span><span class="p">,</span> <span class="n">device</span><span class="o">=</span><span class="n">in_idx</span><span class="o">.</span><span class="n">device</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">)</span>
</span></span></code></pre></div><p><strong>3. 位置溢出（欠账）。</strong> <code>pos_emb</code> 表只有 <code>context_length</code> 个位置，<code>past_len + seq_len</code> 超过就越界。M3 先限制 <code>max_new_tokens</code> 不超限，以后处理。</p>
<h2 id="验收">验收</h2>
<p>同一模型同一 prompt、贪心采样（temperature=0 保证确定性）：</p>
<ul>
<li><strong>输出逐字一致</strong>（朴素版 vs cache 版）</li>
<li><strong>提速可测量</strong>：8.2ms → 4.9ms（约 40%）</li>
</ul>
<h2 id="欠账--todo">欠账 / TODO</h2>
<ul>
<li><strong>位置溢出处理</strong>：滑动窗口（截掉最老历史 + 对应 cache，保持窗口不超 context_length），或者以后换 RoPE（无表位置编码，天然无上限）</li>
<li><code>test_m2_pretrain</code> 手撸（31 号）</li>
<li><code>i</code> 已从 generate 的循环里移除，改由 global_step 做连续 micro-batch 计数</li>
</ul>
<h2 id="历史性的一刻它说人话了">历史性的一刻：它说人话了</h2>
<p>512 个 token 的生成测试里，最终结果是这样的：</p>
<ul>
<li><strong>提速 3.6x</strong>：cache 版 10.00s，朴素版 36.10s</li>
<li><strong>输出连贯有逻辑</strong>：从“人类与 AI 的未来”一路写到机器智能的哲学讨论，不再是复读机</li>
<li><strong>中英文对照</strong>：DeepSeek 翻译也顺畅，直接可以发圈</li>
</ul>
<p>看到模型输出通顺英文的那一刻，我真实地起了鸡皮疙瘩。从“我可能真的写不出来”到“我造的模型说出的东西是通顺的”，中间每一步都是自己敲的：分词器、注意力、训练循环、KV cache。<strong>它不是我用来的，是我造出来的。</strong></p>
<p><img alt="KV cache 验收：输出一致 + 提速 3.6x" loading="lazy" src="https://blog.lvxinrong.com/llm/llm-12-kv-cache-run.png"></p>
]]></content:encoded>
    </item>
    <item>
      <title>手搓 LLM 笔记 11：PyTorch 与资源核算</title>
      <link>https://blog.lvxinrong.com/llm/llm-11-pytorch-resource-accounting/</link>
      <pubDate>Wed, 28 Oct 2026 12:00:00 +0800</pubDate>
      <guid>https://blog.lvxinrong.com/llm/llm-11-pytorch-resource-accounting/</guid>
      <description>训练成本不是黑盒：参数量、显存、FLOPs、时间的估算闭环；混合精度、算术强度、梯度累积与开工踩坑。</description>
      <content:encoded><![CDATA[<p>训练大语言模型时，资源消耗可以直接转换成时间和成本的 所以需要资源核算</p>
<p>FLOPs(Floating Point Operations, 浮点运算次数) 衡量计算复杂度的一个指标，表示一个算法或者模型在执行过程中所需的浮点运算的总次数</p>
<p>经验公式:</p>
<blockquote>
<p>总计算量 ≈  6 ✖️ 参数量 ✖️ Token数量</p>
</blockquote>
<p>6:  fowrad 计算一次约为 2 ✖️ 参数量，backward 约等于前向的2倍，也就是 4 ✖️参数量</p>
<p>时间计算公式:</p>
<blockquote>
<p>时间 = 总工作量 / 总算力</p>
</blockquote>
<p>硬件算力可以查，H100 峰值算力约 1979TFLOPS （FP16/BP16数据类型，且启用结构化稀疏）
训练普通的稠密模型 理论峰值减半 约990 TFLOPs</p>
<p>结构化稀疏: 一种模型压缩的方法，通常是对稠密模型按照50%的稀疏度进行剪纸
<img alt="结构化稀疏：对稠密模型按 50% 稀疏度剪枝" loading="lazy" src="https://blog.lvxinrong.com/llm/llm-11-structured-sparsity.png"></p>
<p>软硬件开销系数 (通常按照 30% ~ 60% 利用率估算更现实)</p>
<p>所以  <strong>在 1024 张 H100 显卡上，训练一个 70B（700亿参数）的模型，数据量是 15T（15万亿 tokens），大概要多久？</strong></p>
$$
\text{时间} = \frac{\text{总工作量}}{\text{总算力}} = \frac{6.3 \times 10^{24}}{5 \times 10^{17}} \approx 1.26 \times 10^7 \text{ 秒} \approx \mathbf{146} \text{ 天}
$$<p><strong>FP16</strong> 和 <strong>BF16</strong> 都是计算机中用于表示小数的<strong>浮点数数据类型</strong>，它们在<strong>深度学习</strong>（AI 模型训练和推理）中被广泛使用。它们的主要目的是<strong>减少内存占用</strong>并<strong>加速计算</strong>（因为占用空间比传统的 FP32 少一半）
FP16 (Half Precision / 半精度浮点数) 精度高 但表示范围小
BF16 (Bfloat16 / 脑浮点数) 精度低 但表示范围极大</p>
<blockquote>
<p>Percy 在课上解释说：“bf16 牺牲了精度来换取范围。对于深度学习来说，范围比精度重要得多，因为数值稳定性的主要威胁是溢出/下溢，而不是尾数精度不够。”</p>
</blockquote>
<p>内存估算
需要同时考虑 参数，梯度，优化器状态(不同优化器 参数量不同)</p>
<h1 id="张量-pytorchtensor">张量 pytorch.tensor</h1>
<p><code>jaxtyping</code> 提供的维度命名（如 “batch seq hidden”）在当前 PyTorch 生态中主要是“文档性质”的，不会在运行时自动强制检查维度是否真的匹配名称，但它能极大地提升代码的清晰度和可靠性。</p>
<pre tabindex="0"><code># 传统方式（容易写错维度顺序）
x = torch.ones(2, 2, 1, 3)  # batch seq heads hidden

# Jaxtyping方式（在类型注解中命名维度）
from jaxtyping import Float
x: Float[torch.Tensor, &#34;batch seq heads hidden&#34;] = torch.ones(2, 2, 1, 3)
</code></pre><p>使用 Einops 库对张量操作进行优化: Einops增加了少量语法开销，但其清晰的维度命名显著降低了调试难度，特别是在复杂的模型架构中
这个后续学习 记个待办</p>
<ul>
<li><strong>FLOPs</strong>（小写s）：执行的浮点运算总数，这是一个衡量计算量的指标，</li>
<li><strong>FLOP/s</strong>（每秒浮点运算）：指硬件每秒能执行的浮点运算次数，也写作 <strong>FLOPS</strong>（大写S）。这是一个衡量“速度”的指标。例如，H100 GPU峰值性能为 990 TFLOP/s。</li>
</ul>
<p>对比矩阵乘法 A (m×k) @ B (k×n) 的 FLOPs = 2 × m × k × n。当 k 较大时（如 k = 1024），矩阵乘法的 FLOPs 是加法的上千倍。对于现代深度学习模型（尤其是 Transformer、MLP 等），90%+ 的 FLOPs 来自矩阵乘法（线性层、QKV 投影、FFN 等）。其他操作（LayerNorm、Softmax、激活函数、加法残差连接等）虽然存在，但 FLOPs 可忽略不计。因此，<strong>在进行粗略但有效的资源估算时，只需计算所有矩阵乘法的 FLOPs 总和即可</strong>。</p>
<p>调用 loss.backward() 后，PyTorch 会从 loss 开始，沿着计算图回溯，自动计算出每个需要梯度的张量的梯度。</p>
<p>一个普适性的结论：在深度学习中，<strong>训练一次（前向+反向）的总 FLOPs 约等于 6 倍的“数据点数量 × 参数数量”</strong></p>
<p>在每次迭代开始前，需要清空上一次计算得到的梯度，否则梯度会累积。优化器在调用 <code>zero_grad</code> 函数清空梯度时，设置 set_to_none=True 是一种更高效的内存管理方式，它会将梯度指针设为 None，而不是将其置零，可以节省内存。</p>
<pre tabindex="0"><code>optimizer.zero_grad(set_to_none=True)
</code></pre><h3 id="检查点checkpointing"> 检查点（Checkpointing）</h3>
<p>大型语言模型的训练耗时极长，过程中几乎不可避免地会发生崩溃或中断，我们需要一种机制来保存进度，以便在中断后能够从中断点恢复，而不是从头开始</p>
<p>检查点需要包含两块，模型参数 和 优化器状态</p>
<blockquote>
<p>为了能够完整地恢复训练，检查点必须包含所有必要的状态信息。主要包括两个核心部分：</p>
<ul>
<li>模型参数：这是模型的核心，包含了所有可学习权重（nn.Parameter）的当前值。通过 model.state_dict() 可以获取一个字典，其中键是参数名称，值是对应的张量数据。
-优化器状态 (optimizer.state_dict())：这是很多人容易忽略但极其关键的部分。优化器（如 Adam、AdaGrad）不仅存储了当前的学习率，还维护着一些内部状态变量。
例如: 如果只保存了模型参数而没有保存优化器状态，那么在恢复训练时，优化器会从零开始，这会导致训练过程不连续，性能下降，甚至可能无法收敛。</li>
</ul>
</blockquote>
<p>checkpoint 保存检查点</p>
<pre tabindex="0"><code># 1. 创建一个字典，包含模型和优化器的状态
checkpoint = {
    &#34;model&#34;: model.state_dict(),
    &#34;optimizer&#34;: optimizer.state_dict(),
}

# 2. 使用 torch.save 将字典序列化并保存到磁盘文件
torch.save(checkpoint, &#34;model_checkpoint.pt&#34;) # 文件名通常使用 .pt 或 .pth 后缀
</code></pre><p>加载也需要两部分同时加载:</p>
<pre tabindex="0"><code># 1. 从磁盘文件加载保存的字典
loaded_checkpoint = torch.load(&#34;model_checkpoint.pt&#34;)

# 2. （后续步骤）将状态加载回模型和优化器
model.load_state_dict(loaded_checkpoint[&#34;model&#34;])
optimizer.load_state_dict(loaded_checkpoint[&#34;optimizer&#34;])
</code></pre><h3 id="混合精度训练-mixed-precision">混合精度训练 (Mixed Precision)</h3>
<p>将低精度(BF16/ FP 16) 用于消耗大但对精度要求不高的部分(激活值)。将高精度用于 对精度敏感的部分(参数和梯度)</p>
<p>PyTorch 的 AMP 库 (Automatic Mixed Precision)：PyTorch 提供了自动混合精度（AMP）库，会自动将安全的操作（如矩阵乘法）转为 bf16，将危险操作（如 exp、softmax）保留为 fp32：</p>
<pre tabindex="0"><code>with torch.amp.autocast(&#34;cuda&#34;, dtype=torch.bfloat16):
    x = torch.zeros(4, 8)  # 自动以 bf16 创建
</code></pre><p>数据搬运也是需要时间，所以总时间取决于 加速器速度FLOP/s 和 内存带宽Bytes/s</p>
<h3 id="算术强度">算术强度</h3>
<p>为了避免每次都要计算两个时间再比较，引入<strong>算术强度（Arithmetic Intensity）</strong>：</p>
<blockquote>
<p>加速器强度 = FLOP/s / Bytes/s   H100 约295FLOP/bytes
算数强度 = FLOPs / Bytes  该操作每搬运1字节能做多少FLOP</p>
</blockquote>
<p>算数强度 &lt; 加速器强度  Memory-bound 瓶颈在数据传输
算数强度 &gt; 加速器强度  Compute-bound 瓶颈在计算</p>
<p>python中 列表的append()和extend 都是原地修改列表。
<code>append(x)</code>：把 <code>x</code> 当作<strong>一个整体元素</strong>加到末尾</p>
<pre tabindex="0"><code>a = [1, 2]
a.append([3, 4])
print(a)  # [1, 2, [3, 4]]
</code></pre><p><code>extend(iterable)</code>：把可迭代对象里的元素<strong>逐个拆开</strong>加到末尾</p>
<pre tabindex="0"><code>a = [1, 2]
a.extend([3, 4])
print(a)  # [1, 2, 3, 4]
</code></pre><p><code>extend</code> 接收的是可迭代对象，比如列表、元组、字符串、集合等</p>
<h2 id="今天的坑m2-开工实录">今天的坑（M2 开工实录）</h2>
<h3 id="梯度累积三次-backward-一次-step">梯度累积：三次 backward 一次 step</h3>
<p>一开始写成了“把所有 loss 攒进 list，最后一次 backward”——这样所有计算图都攒在手里，显存越攒越大，完全背离了梯度累积的初衷。正确姿势是<strong>每个小批立刻 backward（释放计算图），梯度累加在 .grad 里，攒够 N 批再 optimizer.step()</strong>。
归一化也有两种等价写法：<code>sum(loss_i)/N</code> 和每个 <code>loss_i/N</code> 再 backward，因为梯度是线性的，结果一样，但后者省显存。
触发条件用 <code>(i+1) % accum_step == 0</code> 一个表达式通吃，不用给 accum_step=1 单写分支。</p>
<h3 id="zero_grad-的位置决定成败">zero_grad 的位置决定成败</h3>
<p>原来的老代码在循环顶部 zero_grad()，改成累积模式后如果还留着，<strong>前几批攒下的梯度还没 step 就被清掉了</strong>，累积直接白干。口诀：<strong>梯度只在“用掉之后”清零（step 之后），不能在“攒的过程中”清零。</strong></p>
<h3 id="gitignore-的目录匹配会误伤">.gitignore 的目录匹配会误伤</h3>
<p>写 <code>data/</code> 会匹配<strong>所有层级</strong>的 data 目录，把 <code>src/squid/data/</code> 代码包也忽略了（新文件变灰、git status 看不到）。要只排除根目录的语料目录，必须写 <code>/data/</code>（前导斜杠锚定根目录）。</p>
<h3 id="total_loss-是-list-不是张量">total_loss 是 list 不是张量</h3>
<p><code>total_loss / accum_step</code> 会炸，因为 list 不能除以整数；而且把 loss 存进 list 不 backward，等于把计算图全留着。loss 是张量，应该当批归一化后立刻 backward，不是攒起来。</p>
<h2 id="bpb-的含义与下降意味着什么">BPB 的含义与“下降意味着什么”</h2>
<p><strong>BPB（Bits Per Byte）的本质是衡量语言模型把文本压缩了多少：给这段文本编码，平均每个字节要花多少比特。数值越低，说明模型对文本的预测能力越强，压缩效率越高。</strong></p>
<p>两个参照点帮助记忆：</p>
<ul>
<li>BPB 接近 0：模型几乎能完美预测文本，每个字节只需极少比特</li>
<li>BPB = 8：完全不会预测，每个字节都得老老实实存 8 bit，等于没有压缩</li>
</ul>
<p>所以 <strong>BPB 下降 = 模型用更少的比特就能编码同样的文本 = 模型在变好</strong>。它和 val_loss 下降的区别是：val_loss 是“每个 token 的预测难度”，BPB 把它折算成了“每个字节的成本”——这样不同词表、不同模型之间才能公平比较。</p>
<h2 id="容量与深度扫描数据决定上限">容量与深度扫描：数据决定上限</h2>
<p>M2 最小闭环之后，用同一批语料、同一训练量做了容量与深度对照，结论比配置本身值钱。</p>
<h3 id="emb_dim-扫描20-epoch其他锁死">emb_dim 扫描（20 epoch，其他锁死）</h3>
<div class="table-scroll" tabindex="0" role="region" aria-label="表格，可横向滚动">
  <table>
    <thead>
      <tr>
        <th>emb_dim</th>
        <th>最终 val_loss</th>
        <th>BPB</th>
        <th>结论</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>64</td>
        <td>7.02</td>
        <td>3.63</td>
        <td>容量不足</td>
      </tr>
      <tr>
        <td>128</td>
        <td>6.59</td>
        <td>3.42</td>
        <td>仍在受益</td>
      </tr>
      <tr>
        <td><strong>256</strong></td>
        <td><strong>5.99</strong></td>
        <td><strong>3.10</strong></td>
        <td><strong>甜点</strong></td>
      </tr>
      <tr>
        <td>512</td>
        <td>6.26（过拟合）</td>
        <td>3.24</td>
        <td>开始背语料</td>
      </tr>
    </tbody>
  </table>
</div>
<p>512 出现了教科书式的过拟合：<strong>train_loss 一路降到 1.8，val_loss 却从 5.85 回升到 6.29</strong>——模型在背训练集，不是在学规律。所以容量甜点在 256 附近：64 欠拟合、512 过拟合。</p>
<p>验证代码:</p>
<pre tabindex="0"><code>&#34;&#34;&#34;M2 收官：真实语料 + 自训 BPE 的完整预训练。  
  
链路：pack_tokens 打包 → create_stream_loader → 小 GPT 预训练  
      → bpb 曲线 → generate_text 咿呀学语 → save_checkpoint 带 config。  
&#34;&#34;&#34;  
import math  
from pathlib import Path  
  
import torch  
  
from squid.data.token_stream import pack_tokens, create_stream_loader  
from squid.device import get_device  
from squid.generate.text import generate_text  
from squid.model.gpt import GPTModel  
from squid.train.common import calc_loss_loader  
from squid.train.pretrain import pretrain_model  
from squid.tokenizer.my_bpe_tokenizer import MyBPETokenizer  
from squid.checkpoints.store import save_checkpoint  
  
ROOT = Path(__file__).resolve().parents[1]  
DATA = ROOT / &#34;data&#34; / &#34;blog&#34;  
  
  
def test_m2_pretrain():  
    device = get_device()  
    tokenizer = MyBPETokenizer.from_directory(DATA / &#34;m2000&#34;)  
  
    # 1. token 流打包：训练语料与 held-out 分别打包  
    train_text = (DATA / &#34;train.txt&#34;).read_text(encoding=&#34;utf-8&#34;)  
    val_text = &#34;\n&#34;.join(p.read_text(encoding=&#34;utf-8&#34;) for p in DATA.glob(&#34;heldout-*.txt&#34;))  
  
    train_ids = pack_tokens([train_text], tokenizer, tokenizer.eos_id)  
    val_ids = pack_tokens([val_text], tokenizer, tokenizer.eos_id)  
  
    context = 128  
    train_loader = create_stream_loader(train_ids, context, batch_size=8, shuffle=True)  
    val_loader = create_stream_loader(val_ids, context, batch_size=8,  
                                      shuffle=False, drop_last=False)  
  
    # 2. 小模型：emb_dim 64、2 层、context 128  
    cfg = {  
        &#34;vocab_size&#34;: len(tokenizer.vocab),  
        &#34;context_length&#34;: context,  
        &#34;emb_dim&#34;: 256,  
        &#34;n_heads&#34;: 2,  
        &#34;n_layers&#34;: 4,  
        &#34;drop_rate&#34;: 0.0,  
        &#34;qkv_bias&#34;: False,  
    }  
    model = GPTModel(cfg).to(device)  
    optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)  
  
    # 3. 预训练：accum_step=4，bpb 用 held-out 的 bytes/token 折算  
    density = len(val_text.encode(&#34;utf-8&#34;)) / len(tokenizer.encode(val_text))  
    train_losses, val_losses, tokens_seen = pretrain_model(  
        model, train_loader, val_loader, optimizer, device,  
        num_epochs=20, eval_freq=50, eval_iter=5,  
        accum_step=4, bpb_density=density,  
    )  
    assert val_losses[-1] &lt; val_losses[0], &#34;val loss 应该下降&#34;  
  
    # 4. 咿呀学语：给模型一个开头，看它续什么  
    sample = generate_text(model, tokenizer, &#34;大模型&#34;,  
                           max_new_tokens=40, context_size=context,  
                           temperature=0.8, top_k=20, eos_id=tokenizer.eos_id)  
    print(&#34;\n=== 生成样例 ===\n&#34;, sample)  
  
    # 5. 存档：权重 + config + 元信息，完整还原训练现场  
    final_val = calc_loss_loader(val_loader, model, device)  
    save_checkpoint(ROOT / &#34;regression&#34; / &#34;m2-pretrain.pth&#34;,  
                    model, cfg, val_loss=final_val, merges=2000, tokens_seen=tokens_seen[-1])  
    print(f&#34;\n最终 val_loss={final_val:.3f}，checkpoint 已保存&#34;)
</code></pre><h3 id="n_layers-对照emb_dim256">n_layers 对照（emb_dim=256）</h3>
<p>4 层和 2 层基本持平（val_loss 6.03 vs 5.99），深度没有收益，后段 val 还开始上翘。最优配置停在 <strong>emb_dim=256、n_layers=2</strong>。</p>
<p>一句话总结：<strong>小数据面前，模型不是越大越好，是“配得上”才好。</strong> 压缩率有甜点、BPB 有甜点、模型容量也有甜点——全是测出来的，不是猜的。</p>
<h2 id="两个收尾的-bug">两个收尾的 bug</h2>
<p><strong>accum_step 大于每轮批次数</strong>：每 epoch 只有 4 个 batch，accum_step=5 时 <code>(i+1) % 5 == 0</code> 永远不成立，optimizer.step() 一次都不执行，模型完全不学。改成跨 epoch 的 global_step 连续计数才解决。以后看到 loss 完全不动，先查 step 到底执行了没有。</p>
<p><strong>decode 的 UnicodeDecodeError</strong>：字节级 BPE 的 token 可能只是半个汉字，模型自由生成的序列不一定是合法 UTF-8，直接 decode 会炸。改成 <code>decode(&quot;utf-8&quot;, errors=&quot;replace&quot;)</code>，非法片段显示为替换符即可——tiktoken 默认就是这么干的。</p>
]]></content:encoded>
    </item>
  </channel>
</rss>
