<?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/%E6%8C%87%E4%BB%A4%E5%BE%AE%E8%B0%83/</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/%E6%8C%87%E4%BB%A4%E5%BE%AE%E8%B0%83/</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/%E6%8C%87%E4%BB%A4%E5%BE%AE%E8%B0%83/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 笔记 07-2：换底座，从 33.5 分的 GPT-2 到 86.5 分的 Qwen</title>
      <link>https://blog.lvxinrong.com/llm/llm-07-2-switch-base/</link>
      <pubDate>Mon, 19 Oct 2026 21:00:00 +0800</pubDate>
      <guid>https://blog.lvxinrong.com/llm/llm-07-2-switch-base/</guid>
      <description>上一篇的 355M 模型交出 33.5 分和 58 个 0 分。这篇是它的对照组：同一份数据、同一个判官、同一个测试集，换成 Qwen2.5-1.5B base 再做一遍。结果底座把分数从 33.5 拉到 86.5，SFT 却几乎不提分——但它把「写小作文」改成了「直接回答」，也在超参贪心时弄丢了刚学会的知识。</description>
      <content:encoded><![CDATA[<blockquote>
<p>上一篇的结尾贴了 355M 的答卷：33.5 分，58 条 0 分。分数难看，但证据链是完整的——也正因为完整，才看得清问题不在训练脚本，而在底座。这篇是它的对照组：<strong>同一份数据、同一个判官、同一个 110 条测试集</strong>，把模型从手搓的 GPT-2 355M 换成 Qwen2.5-1.5B base，再做一次指令微调。系列规则不变：写下来的必须是我自己搞懂的，翻车的地方如实写。</p>
</blockquote>
<h2 id="一起点335-分和-58-个-0-分问题出在哪">一、起点：33.5 分和 58 个 0 分，问题出在哪</h2>
<p>上一篇的记录里，GPT-2 355M 用 1100 条 Alpaca 数据全参微调 2 个 epoch，DeepSeek 判官给出的结果是：</p>
<pre tabindex="0"><code>mean = 33.5    median = 0    0 分 = 58 条（52.7%）
exact match（归一化）= 15.5%
平均回答长度 = 17 token，128 token 截断 1 条，模板残留 2 条
</code></pre><p>（上一篇贴的是 33.9 / 57 条，本文统一用留存文件重算的 33.5 / 58 条。同一份回复两次打分差 0.4 分——这本身就是本篇后半段要展开的主题：<strong>评委是变量</strong>。）</p>
<p>当时做过一轮归因：58 个 0 分里，<strong>没有一条是空回答、模板残留或截断</strong>，全是“正常文本但答错了”。典型的样本：</p>
<div class="table-scroll" tabindex="0" role="region" aria-label="表格，可横向滚动">
  <table>
    <thead>
      <tr>
        <th>指令</th>
        <th>正确答案</th>
        <th>355M 的回答</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>chlorine 的元素符号</td>
        <td>Cl</td>
        <td><strong>C</strong></td>
      </tr>
      <tr>
        <td>找出句式类型</td>
        <td>interrogative</td>
        <td><strong>imperative</strong></td>
      </tr>
      <tr>
        <td>改写句子（被动→副词）</td>
        <td>The lecture was delivered <strong>clearly</strong>.</td>
        <td>原句照抄</td>
      </tr>
      <tr>
        <td>生成幽默轶事</td>
        <td>Why was the math book sad?&hellip;</td>
        <td>编了个无关的长故事，被 128 token 截断</td>
      </tr>
    </tbody>
  </table>
</div>
<p>配合 train loss 0.30 / val loss 0.64 的过拟合曲线，结论很朴素：<strong>格式它学会了，知识它没有</strong>。1100 条数据改变不了底座的厚度。</p>
<p>于是有了那个命题——<strong>预训练决定“知道什么、能做什么”，后训练决定“怎么表现出来”</strong>。这个命题要在这一篇里被定量验证。</p>
<h2 id="二换底座为什么最后是-qwen25-15b">二、换底座：为什么最后是 Qwen2.5-1.5B</h2>
<h3 id="21-三条路">2.1 三条路</h3>
<div class="table-scroll" tabindex="0" role="region" aria-label="表格，可横向滚动">
  <table>
    <thead>
      <tr>
        <th>路线</th>
        <th>代码改动</th>
        <th>训练耗时</th>
        <th>预期 0 分率</th>
        <th>保留“从零构建”链路</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>GPT-2 774M</td>
        <td>改一行 <code>CHOOSE_MODEL</code></td>
        <td>~7 分钟</td>
        <td>53% → 40~45%</td>
        <td>✅</td>
      </tr>
      <tr>
        <td>GPT-2 1.5B</td>
        <td>同上</td>
        <td>~15 分钟</td>
        <td><del>35</del>40%</td>
        <td>✅</td>
      </tr>
      <tr>
        <td><strong>Qwen2.5-1.5B base + LoRA</strong></td>
        <td>新脚本</td>
        <td>~4 分钟/epoch</td>
        <td><strong>预计 &lt;15%</strong></td>
        <td>❌</td>
      </tr>
    </tbody>
  </table>
</div>
<p>选第三条的原因不是“新”，而是<strong>对照实验需要变量干净</strong>：GPT-2 774M 的容量翻倍了，但知识底子还是 2019 年 40GB WebText 那一套，花 40 分钟很可能只换来“0 分率从 53% 降到 43%”的边际改善；而 Qwen2.5 在 18T token 上预训练，知识是另一个量级，才能真正检验“底座决定上限”。</p>
<h3 id="22-为什么用-base不用-instruct">2.2 为什么用 base，不用 Instruct</h3>
<p>这一点是实验设计的关键。如果直接拿 Instruct 模型来做 SFT，它出厂就已经会按指令回答，SFT 的效果会被掩盖——你分不清格式对齐是训练带来的还是本来就有。</p>
<p>所以对照组必须是<strong>未微调的 base</strong>：它知道“氯的元素符号是 Cl”，但不知道怎么“以回答问题的姿态”说出来。SFT 前后一对比，被改变的到底是什么，一目了然。</p>
<h3 id="23-为什么不是最新的-qwen38">2.3 为什么不是最新的 Qwen3.8</h3>
<p>写这篇时 Qwen 已经更新到 3.8 代，但 3.8 目前公开的是总参数 2.4T、激活 95B 的 MoE——本机 48GB 统一内存跑不动，那是 API 或云端推理的体量。能在 M4 Pro 上做 LoRA 消融的是小尺寸 base 版本；Qwen2.5-1.5B 的生态兼容性最稳，<code>peft</code> / <code>transformers</code> 踩坑最少。想用新一代也很简单——只改 <code>MODEL_NAME</code>，其余一行不动。</p>
<h3 id="24-手搓的-gptmodel-去哪了">2.4 手搓的 GPTModel 去哪了</h3>
<p>换到 HF 栈之后，第 4~6 章手写的 <code>GPTModel</code>、<code>generate_text_util</code>、<code>train_model_simple_py</code> 在新脚本里全部闲置了。不是白写——它们是读懂 HF 源码的坐标系：</p>
<div class="table-scroll" tabindex="0" role="region" aria-label="表格，可横向滚动">
  <table>
    <thead>
      <tr>
        <th>我的实现（GPT-2 结构）</th>
        <th>Qwen2.5 的结构</th>
        <th>为什么变</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><code>tok_emb</code> + <code>pos_emb</code>（可学习绝对位置）</td>
        <td><code>wte</code> + <strong>RoPE</strong>（旋转位置编码）</td>
        <td>支持长度外推，context 1024 → 32k+</td>
      </tr>
      <tr>
        <td><code>LayerNorm</code></td>
        <td><strong>RMSNorm</strong></td>
        <td>省去均值计算</td>
      </tr>
      <tr>
        <td>GELU 两层 MLP（<code>c_fc</code>→<code>c_proj</code>）</td>
        <td><strong>SwiGLU</strong> 三层（<code>gate_proj</code>/<code>up_proj</code>/<code>down_proj</code>）</td>
        <td>同参数量下效果更好</td>
      </tr>
      <tr>
        <td>MHA：12 个 Q 头 = 12 个 KV 头</td>
        <td><strong>GQA</strong>：12 个 Q 头只配 2 个 KV 头</td>
        <td>省 KV cache 显存——正好对上之前问的“为什么只有 KV cache”</td>
      </tr>
      <tr>
        <td><code>qkv_bias=True</code></td>
        <td>默认无 bias</td>
        <td>训练稳定性</td>
      </tr>
      <tr>
        <td>词表 50257</td>
        <td>词表 151936</td>
        <td>多语言</td>
      </tr>
    </tbody>
  </table>
</div>
<p>真正被替换的只有三件：模型定义、生成函数、训练循环。<strong>被保留的是最值钱的部分</strong>——<code>format_input</code> 模板、<code>InstructionDataset</code> 的掩码思路、110 条测试集切分、判官打分流水线。实验之所以可比，靠的就是这些没动。</p>
<h2 id="三代码ch07_qwenpy">三、代码：<code>ch07_qwen.py</code></h2>
<h3 id="31-训练侧lora--只对回答算-loss">3.1 训练侧：LoRA + 只对回答算 loss</h3>
<p>模板和 GPT-2 版本逐字一致（<code>format_input(entry) + &quot;\n\n### Response:\n&quot;</code>），prompt 部分的 label 置 <code>-100</code>：</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">prompt</span> <span class="o">=</span> <span class="n">format_input</span><span class="p">(</span><span class="n">e</span><span class="p">)</span> <span class="o">+</span> <span class="s2">&#34;</span><span class="se">\n\n</span><span class="s2">### Response:</span><span class="se">\n</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"><span class="n">answer</span> <span class="o">=</span> <span class="n">e</span><span class="p">[</span><span class="s2">&#34;output&#34;</span><span class="p">]</span> <span class="o">+</span> <span class="n">tokenizer</span><span class="o">.</span><span class="n">eos_token</span>
</span></span><span class="line"><span class="cl"><span class="n">p_ids</span> <span class="o">=</span> <span class="n">tokenizer</span><span class="p">(</span><span class="n">prompt</span><span class="p">,</span> <span class="n">add_special_tokens</span><span class="o">=</span><span class="kc">False</span><span class="p">)[</span><span class="s2">&#34;input_ids&#34;</span><span class="p">]</span>
</span></span><span class="line"><span class="cl"><span class="n">a_ids</span> <span class="o">=</span> <span class="n">tokenizer</span><span class="p">(</span><span class="n">answer</span><span class="p">,</span> <span class="n">add_special_tokens</span><span class="o">=</span><span class="kc">False</span><span class="p">)[</span><span class="s2">&#34;input_ids&#34;</span><span class="p">]</span>
</span></span><span class="line"><span class="cl"><span class="n">ids</span>    <span class="o">=</span> <span class="p">(</span><span class="n">p_ids</span> <span class="o">+</span> <span class="n">a_ids</span><span class="p">)[:</span><span class="n">MAX_LEN</span><span class="p">]</span>
</span></span><span class="line"><span class="cl"><span class="n">labels</span> <span class="o">=</span> <span class="p">([</span><span class="o">-</span><span class="mi">100</span><span class="p">]</span> <span class="o">*</span> <span class="nb">len</span><span class="p">(</span><span class="n">p_ids</span><span class="p">)</span> <span class="o">+</span> <span class="n">a_ids</span><span class="p">)[:</span><span class="n">MAX_LEN</span><span class="p">]</span>
</span></span></code></pre></div><p>LoRA 挂在注意力与 MLP 的全部投影上（这是第一轮激进配置；文末的推荐配置是 r=8, α=16）：</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">lora_config</span> <span class="o">=</span> <span class="n">LoraConfig</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="n">task_type</span><span class="o">=</span><span class="n">TaskType</span><span class="o">.</span><span class="n">CAUSAL_LM</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">r</span><span class="o">=</span><span class="mi">16</span><span class="p">,</span> <span class="n">lora_alpha</span><span class="o">=</span><span class="mi">32</span><span class="p">,</span> <span class="n">lora_dropout</span><span class="o">=</span><span class="mf">0.05</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">target_modules</span><span class="o">=</span><span class="p">[</span><span class="s2">&#34;q_proj&#34;</span><span class="p">,</span> <span class="s2">&#34;k_proj&#34;</span><span class="p">,</span> <span class="s2">&#34;v_proj&#34;</span><span class="p">,</span> <span class="s2">&#34;o_proj&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                    <span class="s2">&#34;gate_proj&#34;</span><span class="p">,</span> <span class="s2">&#34;up_proj&#34;</span><span class="p">,</span> <span class="s2">&#34;down_proj&#34;</span><span class="p">],</span>
</span></span><span class="line"><span class="cl"><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="n">model</span> <span class="o">=</span> <span class="n">get_peft_model</span><span class="p">(</span><span class="n">model</span><span class="p">,</span> <span class="n">lora_config</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="c1"># trainable params: 18,464,768 || all params: 1,562,179,072 || trainable%: 1.1820</span>
</span></span></code></pre></div><p><strong>1.18% 的参数可训练</strong>，其余 98.8% 冻结。优化器只接可训练参数：</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">optimizer</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">optim</span><span class="o">.</span><span class="n">AdamW</span><span class="p">([</span><span class="n">p</span> <span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">model</span><span class="o">.</span><span class="n">parameters</span><span class="p">()</span> <span class="k">if</span> <span class="n">p</span><span class="o">.</span><span class="n">requires_grad</span><span class="p">],</span> <span class="n">lr</span><span class="o">=</span><span class="n">LR</span><span class="p">)</span>
</span></span></code></pre></div><p>一次优化 = 2 个 micro-batch（<code>GRAD_ACCUM=2</code>），<code>loss = model(**batch).loss / 2</code> 后 <code>backward</code>，每 2 步 <code>step()</code> 一次。</p>
<h3 id="32-生成侧hf-自带-kv-cache">3.2 生成侧：HF 自带 KV cache</h3>
<p>评估用的是 <code>model.generate(..., max_new_tokens=128, do_sample=False)</code>。和第 7 章手写的 <code>generate</code> 最大区别不是代码长短，而是 <strong>HF 的实现自带 KV cache</strong>：每生成一个 token 只算新位置，而不是把整个前缀重新 forward 一遍。110 条测试样本的完整评估因此从“不敢想”变成 1~2 分钟。</p>
<h3 id="33-工程坑记录">3.3 工程坑记录</h3>
<ul>
<li><strong>模板多一个空格</strong>：<code>f&quot;### Response: \n“</code> 比书上模板多一个空格，BPE 会多切出一个 <code>' '</code> token（id 220），loss 和抽取都和书对不上。改成 <code>”### Response:\n&quot;</code> 后对齐。</li>
<li><strong><code>allowed_max_length=1204</code></strong>：比 <code>context_length=1024</code> 还大，等于没截断；一旦样本超长，位置编码直接越界。改回 1024。</li>
<li><strong><code>num_workers=8</code> + macOS</strong>：Python 3.12 在 macOS 默认 <code>spawn</code>，脚本顶层又没写 <code>if __name__ == &quot;__main__&quot;</code>，子进程重新 import 主模块导致无限套娃。改 <code>num_workers=0</code> + main guard 解决。</li>
<li><strong>MPS 随机数独立</strong>：要复现就得同时 <code>torch.manual_seed</code> 和 <code>torch.mps.manual_seed</code>；计时要在末尾 <code>torch.mps.synchronize()</code>，否则 GPU 队列还没排空。</li>
</ul>
<h2 id="四评估协议三个判据两个口径">四、评估协议：三个判据，两个口径</h2>
<ul>
<li><strong>测试集</strong>：110 条，与 GPT-2 完全同一批。</li>
<li><strong>判官</strong>：DeepSeek <code>deepseek-flash</code>，<code>temperature=0</code>，输出 0–100 整数。</li>
<li><strong>两种 prompt</strong>（这本身是第二组实验）：
<ul>
<li><strong>字面口径</strong>：按与参考答案的接近程度打分（和上一篇一致，可与 GPT-2 直接比较）；</li>
<li><strong>语义口径</strong>：只判事实/指令正确性，不判措辞、长度与格式。</li>
</ul>
</li>
<li><strong>三个无 API 成本的辅助指标</strong>：归一化 exact match、平均 token 数、128 token 截断数。判官会抖，客观指标不会。</li>
</ul>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">prompt（语义口径）：
</span></span><span class="line"><span class="cl">You are grading a model answer. Judge ONLY factual/instructional correctness,
</span></span><span class="line"><span class="cl">NOT wording, length, or format. A semantically equivalent answer is full marks.
</span></span><span class="line"><span class="cl">...
</span></span><span class="line"><span class="cl">Score 0-100. Respond with the integer only.
</span></span></code></pre></div><h2 id="五第一轮base-vs-激进-sft--换底座赢麻了sft-白忙了">五、第一轮：base vs 激进 SFT —— 换底座赢麻了，SFT 白忙了</h2>
<h3 id="51-结果">5.1 结果</h3>
<p><strong>字面口径</strong>（与 GPT-2 同口径）：</p>
<div class="table-scroll" tabindex="0" role="region" aria-label="表格，可横向滚动">
  <table>
    <thead>
      <tr>
        <th>组别</th>
        <th>均分</th>
        <th>中位</th>
        <th>0 分率</th>
        <th>≥80 占比</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>GPT-2 355M + SFT</td>
        <td><strong>33.5</strong></td>
        <td>0</td>
        <td>52.7%</td>
        <td>25.5%</td>
      </tr>
      <tr>
        <td>Qwen base</td>
        <td>84.4</td>
        <td>100</td>
        <td>8.2%</td>
        <td>82.7%</td>
      </tr>
      <tr>
        <td>Qwen + SFT（激进）</td>
        <td>84.3</td>
        <td>100</td>
        <td>9.1%</td>
        <td>81.8%</td>
      </tr>
    </tbody>
  </table>
</div>
<p><strong>生成侧指标</strong>：</p>
<div class="table-scroll" tabindex="0" role="region" aria-label="表格，可横向滚动">
  <table>
    <thead>
      <tr>
        <th>组别</th>
        <th>exact match</th>
        <th>平均 token</th>
        <th>截断</th>
        <th>空回答</th>
        <th>模板残留</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>GPT-2 355M</td>
        <td>15.5%</td>
        <td>17.0</td>
        <td>1</td>
        <td>0</td>
        <td>2</td>
      </tr>
      <tr>
        <td>Qwen base</td>
        <td>24.5%</td>
        <td><strong>31.4</strong></td>
        <td><strong>6</strong></td>
        <td>0</td>
        <td>0</td>
      </tr>
      <tr>
        <td>Qwen SFT（激进）</td>
        <td><strong>42.7%</strong></td>
        <td>13.1</td>
        <td>0</td>
        <td>0</td>
        <td>0</td>
      </tr>
    </tbody>
  </table>
</div>
<h3 id="52-观察一base-根本不需要教知识">5.2 观察一：base 根本不需要“教知识”</h3>
<p>未微调的 base 在同样的模板下，直接答对了这些题：</p>
<pre tabindex="0"><code>雷暴云类型      → cumulonimbus
氯的元素符号    → Cl
《傲慢与偏见》作者 → Jane Austen
</code></pre><p>上一轮 355M 答错的同一道 chlorine 题，base 没经过任何 SFT 就答对了。<strong>知识是预训练给的</strong>，这句话从“猜”变成了“看到”。</p>
<h3 id="53-观察二sft-在强底座上几乎不提分只改形状">5.3 观察二：SFT 在强底座上几乎不提分，只改形状</h3>
<p>字面口径下 base 84.4、SFT 84.3，<strong>逐条对比 110 条里有 91 条分数完全相同</strong>。但 SFT 明确改变了三件事：</p>
<ul>
<li>exact match 24.5% → 42.7%；</li>
<li>平均长度 31.4 → 13 token（base 爱写小作文，SFT 只给答案）；</li>
<li>128 token 截断 6 条 → 0 条（base 会陷入「without my phone without my phone&hellip;」的复读，SFT 不会）。</li>
</ul>
<p>base 的失败模式是“知道答案但话太多、停不下来”，SFT 修的正是这个。判官分不动，是因为它本来就答对了。</p>
<h3 id="54-观察三灾难性遗忘--sft-把知识写坏了">5.4 观察三：灾难性遗忘 —— SFT 把知识写坏了</h3>
<p>这是这一轮最意外的发现。以“base 给 100 分、SFT 却 &lt;60 分”定义知识回退，激进配置出现了 <strong>9 条</strong>（其中 8 条是真错，1 条是判官误判——列表式分类那道）：</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>CO2</td>
        <td><strong>C2O2</strong></td>
      </tr>
      <tr>
        <td>硫的沸点</td>
        <td>444.6°C</td>
        <td><strong>112°C</strong></td>
      </tr>
      <tr>
        <td>判断句式（Did you&hellip;?）</td>
        <td>question</td>
        <td><strong>imperative</strong></td>
      </tr>
      <tr>
        <td>挑出形容词（run/tall/quickly）</td>
        <td>tall</td>
        <td>tall <strong>和 quickly</strong>（副词）</td>
      </tr>
      <tr>
        <td>鲨鱼分类</td>
        <td>Fish</td>
        <td><strong>Reptiles</strong></td>
      </tr>
      <tr>
        <td>I am lost 的意大利语</td>
        <td>Sono perso</td>
        <td><strong>Ti sei perso</strong>（“你迷路了”）</td>
      </tr>
      <tr>
        <td>see you later 的西班牙语</td>
        <td>hasta luego</td>
        <td><strong>Vuelva a verme tarde</strong></td>
      </tr>
      <tr>
        <td>用 elucidate 造句</td>
        <td>用了该词</td>
        <td><strong>句子没用 elucidate</strong></td>
      </tr>
    </tbody>
  </table>
</div>
<p>1100 条数据、<code>lr=2e-4</code>、2 个 epoch——模型为了贴合 Alpaca 的措辞，把预训练学的知识挤掉了。这就是<strong>灾难性遗忘（catastrophic forgetting）</strong>。</p>
<h2 id="六第二轮把学习率降下来知识真的回来了">六、第二轮：把学习率降下来，知识真的回来了</h2>
<p>直觉判断：遗忘是“更新太猛”造成的。把总更新幅度砍到 1/8：</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">LR</span> <span class="o">=</span> <span class="mf">5e-5</span>        <span class="c1"># 2e-4 → 5e-5</span>
</span></span><span class="line"><span class="cl"><span class="n">NUM_EPOCHS</span> <span class="o">=</span> <span class="mi">1</span>   <span class="c1"># 2 → 1</span>
</span></span><span class="line"><span class="cl"><span class="n">r</span><span class="o">=</span><span class="mi">8</span><span class="p">,</span> <span class="n">lora_alpha</span><span class="o">=</span><span class="mi">16</span>   <span class="c1"># r=16, alpha=32 → r=8, alpha=16</span>
</span></span></code></pre></div><p>结果：</p>
<div class="table-scroll" tabindex="0" role="region" aria-label="表格，可横向滚动">
  <table>
    <thead>
      <tr>
        <th>条目</th>
        <th>base</th>
        <th>激进</th>
        <th>保守（1ep/5e-5/r8）</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>CO2 分子式</td>
        <td>100</td>
        <td>0</td>
        <td><strong>100</strong></td>
      </tr>
      <tr>
        <td>硫沸点</td>
        <td>100</td>
        <td>0</td>
        <td><strong>90</strong>（444 vs 444.6）</td>
      </tr>
      <tr>
        <td>句式判断</td>
        <td>100</td>
        <td>0</td>
        <td><strong>85</strong>（「a question」）</td>
      </tr>
      <tr>
        <td>形容词</td>
        <td>100</td>
        <td>0</td>
        <td><strong>100</strong></td>
      </tr>
      <tr>
        <td>I am lost 意语</td>
        <td>85</td>
        <td>0</td>
        <td><strong>90</strong>（Mi sono perso）</td>
      </tr>
      <tr>
        <td>see you later 西语</td>
        <td>100</td>
        <td>0</td>
        <td><strong>100</strong>（hasta luego）</td>
      </tr>
      <tr>
        <td>elucidate 造句</td>
        <td>100</td>
        <td>0</td>
        <td><strong>95</strong>（The professor elucidated&hellip;）</td>
      </tr>
      <tr>
        <td>irony 定义</td>
        <td>100</td>
        <td>0</td>
        <td><strong>85</strong></td>
      </tr>
    </tbody>
  </table>
</div>
<p><strong>8 条全部修复。</strong> 语义口径均分 84.8，exact match 37.3%（比激进版低 5.4pp）。</p>
<p>结论升级：<strong>遗忘不是 SFT 的必然，是超参的选择</strong>。少训一点、慢一点，可以在“格式对齐”和“保住知识”之间找到平衡。</p>
<h2 id="七第三轮找甜点--1-epoch--1e-4--r8">七、第三轮：找甜点 —— 1 epoch / 1e-4 / r=8</h2>
<p>保守版把知识救回来了，但格式对齐退得有点多。把 lr 从 5e-5 提到 1e-4（总更新幅度仍是激进版的 1/4），再跑一轮：</p>
<div class="table-scroll" tabindex="0" role="region" aria-label="表格，可横向滚动">
  <table>
    <thead>
      <tr>
        <th>指标</th>
        <th>保守 5e-5</th>
        <th><strong>中配 1e-4</strong></th>
        <th>激进 2e-4×2</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>exact match</td>
        <td>37.3%</td>
        <td><strong>39.1%</strong></td>
        <td>42.7%</td>
      </tr>
      <tr>
        <td>语义均分</td>
        <td>84.8</td>
        <td><strong>86.5</strong></td>
        <td>83.6</td>
      </tr>
      <tr>
        <td>0 分率</td>
        <td>8.2%</td>
        <td><strong>6.4%</strong></td>
        <td>15.5%</td>
      </tr>
      <tr>
        <td>真实知识回退</td>
        <td>3 条</td>
        <td><strong>2 条</strong></td>
        <td>8 条</td>
      </tr>
    </tbody>
  </table>
</div>
<p>中配还剩下 4 条“回退”，但其中 2 条是判官的锅（见下一节），真实错误只有“nostalgia 造句没用该词”和“鲨鱼被分类成爬行动物”两条。</p>
<p><strong>这就是甜点</strong>：<code>Qwen2.5-1.5B base + LoRA(r=8, α=16) + 1 epoch + lr 1e-4</code>。</p>
<p><img alt="七组打分结果：灰色为字面口径，蓝色为语义口径；右图为分数分布" loading="lazy" src="https://blog.lvxinrong.com/llm/llm-07-2-score-comparison-v2.png"></p>
<h3 id="补充为什么回退条数比均分更能说明问题">补充：为什么“回退条数”比均分更能说明问题</h3>
<p>看配对统计会更清楚（语义口径，vs base）：</p>
<div class="table-scroll" tabindex="0" role="region" aria-label="表格，可横向滚动">
  <table>
    <thead>
      <tr>
        <th>对比</th>
        <th>均分差</th>
        <th>95% 置信区间</th>
        <th>更好</th>
        <th>更差</th>
        <th>打平</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>激进 − base</td>
        <td>−2.14</td>
        <td>[−9.3, +5.0]</td>
        <td>8</td>
        <td>11</td>
        <td>91</td>
      </tr>
      <tr>
        <td>保守 − base</td>
        <td>−1.00</td>
        <td>[−6.2, +4.2]</td>
        <td>10</td>
        <td>37</td>
        <td>63</td>
      </tr>
      <tr>
        <td>中配 − base</td>
        <td>+0.68</td>
        <td>[−4.7, +6.0]</td>
        <td>12</td>
        <td>35</td>
        <td>63</td>
      </tr>
    </tbody>
  </table>
</div>
<p><strong>三个区间全部跨过 0</strong>——在这个已经很强的 base 上，SFT 对“判官均分”没有统计显著的影响。它产生的影响全部落在<strong>分布形状</strong>上：base 是“15 个 0 分 + 94 个 81–100 分”的极端两极化分布，中配把 0 分压到 7 条、把中间段补了 8 条。<strong>SFT 用“抹平少数满分”换来了“减少灾难性错误”。</strong></p>
<h2 id="八第四次实验评委自己也是变量">八、第四次实验：评委自己也是变量</h2>
<h3 id="81-两种-prompt-的差别">8.1 两种 prompt 的差别</h3>
<p>同一个 base 模型、同一批回答，只换判官 prompt：</p>
<div class="table-scroll" tabindex="0" role="region" aria-label="表格，可横向滚动">
  <table>
    <thead>
      <tr>
        <th>判官口径</th>
        <th>base 均分</th>
        <th>base 0 分率</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>字面</td>
        <td>84.4</td>
        <td>8.2%</td>
      </tr>
      <tr>
        <td>语义</td>
        <td>85.8</td>
        <td><strong>13.6%</strong></td>
      </tr>
    </tbody>
  </table>
</div>
<p>语义 prompt 把 0 分率<strong>提高了</strong>——它让判官更“二元化”（要么 100、要么 0）。这说明 “改 prompt 以减少格式偏见” 这个预期没有完全实现，判官行为本身难以预测。</p>
<h3 id="82-判官实锤误判的案例">8.2 判官实锤误判的案例</h3>
<ul>
<li><strong>列表式分类题</strong>：gold 是 <code>Mercury - Liquid / Oxygen - Gas / Wood - Solid</code>，SFT 答 <code>Solid: Wood / Liquid: Oxygen / Gas: Mercury</code>——内容全对，被判 <strong>0</strong>。</li>
<li><strong>德语翻译</strong>：<code>Badezimmer</code> 是 bathroom 的正确德语词之一，被判 <strong>0</strong>（gold 用 <code>Toilette</code>）。</li>
<li><strong>简洁的正确回答</strong>：base 用一整段解释得 100，SFT 一句话答对得 85——判官仍偏爱“长”。</li>
</ul>
<h3 id="83-波动有多大">8.3 波动有多大</h3>
<ul>
<li>同一份回复字面口径两次打分：84.2 / 84.4；</li>
<li>上一篇 GPT-2 记录 33.9 / 57 条 0 分，本次重算 33.5 / 58 条。</li>
</ul>
<p><strong>±0.5 分、±1 条 0 分是常态。</strong> 所以本篇所有结论都写“方向”和“区间”，不写“精确到小数点后一位的胜负”。</p>
<h2 id="九结论">九、结论</h2>
<ol>
<li><strong>底座决定上限，且是数量级的</strong>：同数据、同判官，GPT-2 355M 33.5 → Qwen2.5-1.5B 84<del>86。0 分率 52.7% → 6</del>13%。</li>
<li><strong>SFT 在强底座上是“塑形”不是“提分”</strong>：判官分无显著变化，但 exact match +14pp、回答长度腰斩、截断归零、极端错误减半。</li>
<li><strong>SFT 不是免费的</strong>：学习率/训练量过大会造成灾难性遗忘（CO2→C2O2、硫沸点 444.6→112）；把更新幅度降到 1/8 后全部修复。<strong>“教格式”和“毁知识”之间只差一个学习率。</strong></li>
<li><strong>评估口径是结论的一部分</strong>：同一模型换判官 prompt，0 分率从 8.2% 变 13.6%；报告必须注明口径，并用 exact match 这类客观指标交叉验证。</li>
<li><strong>推荐配置</strong>：<code>Qwen2.5-1.5B base + LoRA(r=8, α=16) + 1 epoch + lr 1e-4 + 只对 response 算 loss</code>。</li>
</ol>
<h2 id="十这篇笔记改掉的三句话">十、这篇笔记改掉的三句话</h2>
<p>实验之外，这篇笔记还修正了我三个张口就来的认知，按被推翻的顺序记：</p>
<p><strong>「一个差的模型，怎么微调都不会变强。」</strong>——不准确。355M 微调前后确实变了：会听指令、会吐结束符，「行为」变了；但知识问答照错，「能力」没动。准确的说法是：<strong>上限由预训练定死，后训练在上限之内调水位，水位的天花板是对齐数据的质量</strong>。alignment 便宜，capability 贵。</p>
<p><strong>「SFT 反正是给模型加东西。」</strong>——错。SFT 不是免费的：激进配置把 CO2 教成 C2O2、把硫的沸点从 444.6°C 写成 112°C。<strong>教格式和毁知识之间只差一个学习率。</strong>「后训练决定平均答复水平」这句话要加半句——在训练数据配得上的前提下。</p>
<p><strong>「国内模型是基础差、后训练厉害。」</strong>——也错，因果反了。真实剧情是算力受限逼出了全栈效率创新：MLA 压缩 KV cache（和 LoRA 同款的低秩思想，用在注意力上）、MoE 用稀疏换规模、FP8 砍精度换吞吐、GRPO 做后训练。<strong>不是后训练一层强，是三层都在拧毛巾</strong>。这个认知对我自己也有用：我的算力牌面比谁都紧，但约束不是借口，是设计的起点——nanochat 整个项目就是这个哲学。</p>
<p>顺带一个光谱观察：第六章「只解冻最后一块」、第七章「全参数微调」、本篇 LoRA「全冻结外挂低秩小路」——三种方案是同一个问题的三个答案：微调到底该动多少参数、动哪里。成本、效果、遗忘风险，三角取舍。</p>
<h2 id="十一模型仍然不会的题">十一、模型仍然不会的题</h2>
<p>两种口径下都 ≤20 分的 10 条，几乎全是<strong>变换类 / 开放创作类</strong>：</p>
<pre tabindex="0"><code>纠正标点        &#34;Its time to go home.&#34; → 不会
替换陈词滥调     &#34;It&#39;s very easy.&#34; → 不会
改为间接疑问句   → 不会
indefinite pronoun 转换 → 不会
幽默轶事创作     → 编的故事和“数学书为什么悲伤”无关
氯的沸点         -34°C → 不会
</code></pre><p>这是 1.5B 的能力边界，不是训练配置问题。Alpaca 里这类题的参考答案非常具体（「The corrected sentence should be: ‘It’s time to go home.’」），模型既不会做字符级编辑，也不会主动收束到那种格式。<strong>底座再大一号，这类题才会松动。</strong></p>
<h2 id="十二留痕文件与复现">十二、留痕文件与复现</h2>
<div class="table-scroll" tabindex="0" role="region" aria-label="表格，可横向滚动">
  <table>
    <thead>
      <tr>
        <th>文件</th>
        <th>内容</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><code>instruction-data-with-response.json</code> / <code>-scores.json</code></td>
        <td>GPT-2 355M 全参 SFT，字面口径</td>
      </tr>
      <tr>
        <td><code>qwen-base-with-response.json</code> / <code>-scores.json</code> / <code>-scores-semantic.json</code></td>
        <td>Qwen base，两种口径</td>
      </tr>
      <tr>
        <td><code>qwen-sft-with-response.json</code> / <code>-scores.json</code> / <code>-scores-semantic.json</code></td>
        <td>激进 LoRA（2ep/2e-4/r16）</td>
      </tr>
      <tr>
        <td><code>qwen-sft-lr5e5_ep1_r8-*</code></td>
        <td>保守 LoRA（1ep/5e-5/r8）</td>
      </tr>
      <tr>
        <td><code>qwen-sft-lr1e4_ep1_r8-*</code></td>
        <td><strong>中配 LoRA（推荐）</strong></td>
      </tr>
      <tr>
        <td><code>qwen2.5-1.5b-alpaca-lora{,-lr5e5_ep1_r8,-lr1e4_ep1_r8}</code></td>
        <td>三个 adapter</td>
      </tr>
    </tbody>
  </table>
</div>
<p>硬件与耗时（M4 Pro / 48GB / MPS）：GPT-2 355M 全参 2 epoch ≈ 2.85 分钟；Qwen LoRA 1 epoch ≈ 4 分钟；110 条生成评估 ≈ 1~1.7 分钟；110 条判官打分 ≈ 1.2 分钟。</p>
<h2 id="十三下一步">十三、下一步</h2>
<ol>
<li>给中配补字面口径分数，把四组表补完整；</li>
<li>对 2 条真实回退和 10 条 both-low 各打 3 次取平均，压掉判官噪声；</li>
<li>换更能体现 SFT 价值的任务（JSON 输出、多轮对话、固定表格），避开这个数据集的天花板；</li>
<li>想再验证一次“底座决定上限”，可以换 Qwen3-1.7B-Base 重跑同一套脚本，只改 <code>MODEL_NAME</code> 一行。</li>
</ol>
<h2 id="一句话总结">一句话总结</h2>
<p><strong>分数是评委给的，形状是训练给的，知识是预训练给的。</strong></p>
<p>上一篇的 355M 让我看清了“后训练不是知识注入”；这一篇的 Qwen 让我看清了它的另一半——<strong>后训练也不是免费的，它能把知识挤走</strong>。这两句话合起来，才是 SFT 的完整画像。</p>
<hr>
<p><em>前一篇：<a href="https://blog.lvxinrong.com/llm/llm-07-instruction-finetune/">手搓 LLM 笔记 07：指令微调，掩码、表面对齐与 AI 评委</a></em></p>
]]></content:encoded>
    </item>
    <item>
      <title>手搓 LLM 笔记 07：指令微调，掩码、表面对齐与 AI 评委</title>
      <link>https://blog.lvxinrong.com/llm/llm-07-instruction-finetune/</link>
      <pubDate>Mon, 19 Oct 2026 18:25:00 +0800</pubDate>
      <guid>https://blog.lvxinrong.com/llm/llm-07-instruction-finetune/</guid>
      <description>第七章把 GPT-2 微调成一个能听指令的模型：不换头、不冻结、全参数。数据管道里的 +1 和 -100 两根针脚、CPU 和 MPS 的一百倍差距、DeepSeek 当评委给出的 34 分，和 57 个 0 分背后的能力肖像。</description>
      <content:encoded><![CDATA[<blockquote>
<p>第七章把第六章那个会「分类」的 GPT-2 改造成一个能「听指令」的模型。数据管道抠出了两根针脚（+1 和 -100），训练时被 CPU 坑了一次，评估时亲手测出了「评委不同，分数不可比」。系列规则不变：写下来的必须是我自己搞懂的，答错的如实写。</p>
</blockquote>
<h2 id="一这一章在做什么不换头不冻结只换数据">一、这一章在做什么：不换头、不冻结、只换数据</h2>
<p>第六章分类微调：换掉输出头（50257 → 2），冻结大部分参数，只训最后一块 + 新头。</p>
<p>第七章指令微调：<strong>不换头、不冻结、全参数训练</strong>。模型结构和预训练时一模一样，输出还是 50257 维的 next-token 预测。改变的只有数据——从「连续文本」换成「指令 + 回答」的成对样本（1100 条，Alpaca 风格模板）。</p>
<pre tabindex="0"><code>Below is an instruction that describes a task. Write a response
that appropriately completes the request.

### Instruction:
{指令}

### Input:
{输入（可空）}

### Response:
{回答}
</code></pre><p>套模板这个动作，我学前预测时答对了方向：<strong>结构化本身就是模型要学习的内容</strong>。模板让模型学会「哪里是指令、哪里是回答」，推理时必须用同一个模板，套错了模型就不认识。</p>
<h2 id="二学前探针与验收约定">二、学前探针与验收约定</h2>
<p>这章开始和 Kimi 约定：学前探针只问主干（目标函数、数据流、结构差异），shape、API、参数细节放到学后验收。四个主干探针：</p>
<ul>
<li>Q1（目标函数）：指令微调的 loss 和预训练只差一个动作——掩码。✅</li>
<li>Q2（数据量）：几千条样本为什么够？✅（见第四节）</li>
<li>Q3（模板与停止）：模板让模型学会在哪里结束。✅</li>
<li>Q4（评估）：没有标准答案怎么规模化评估？✅（见第五节）</li>
</ul>
<h2 id="三数据管道验收7174">三、数据管道验收（7.1–7.4）</h2>
<h3 id="验收-q1两种填充">验收 Q1：两种填充</h3>
<p>inputs 用 50256 pad 对齐 batch；targets 同样先补 50256，再把<strong>除第一个之外</strong>的所有 50256 替换成 -100（<code>cross_entropy</code> 的默认 <code>ignore_index</code>，传进去自动跳过）。</p>
<p>保留第一个 50256 不掩盖，是为了让模型学会「说完就停」——把结束的权利交给模型自己。我第一遍把 50256 写成了 50257（词表大小），手误，但要警惕：词表 50257 个词，最后一个 id 是 50256。</p>
<p>推论：inputs 里的 padding 虽然参与前向计算，但它们对应的 targets 位置已经是 -100，所以 padding 对 loss 的贡献是零。</p>
<h3 id="验收-q2错位一位与-1">验收 Q2：错位一位与 +1</h3>
<p><code>inputs = padded[:-1]</code>、<code>targets = padded[1:]</code>，错位一位是 next-token 监督，和预训练一致。</p>
<p><code>batch_max_length = max(len) + 1</code> 的 <code>+1</code> 不是防越界（我第一遍答错了），而是<strong>给结束符留位置</strong>：多塞的 50256 经过错位后恰好落在「回答最后一个 token」的下一格，保证每个样本都包含「回答说完 → 出 50256」这条监督信号。</p>
<p>+1 和「保留第一个 50256 不掩盖」是同一个设计的两半：一个留位置，一个放行信号。</p>
<p>训练结束后这个设计在屏幕上跑了出来：</p>
<pre tabindex="0"><code>### Response: The meal is prepared every day by the chef.&lt;|endoftext|&gt;
</code></pre><p>模型答完主动输出了 <code>&lt;|endoftext|&gt;</code>——它学会了说「我说完了」。</p>
<h3 id="验收-q3指令部分盖不盖答错了记三笔账">验收 Q3：指令部分盖不盖——答错了，记三笔账</h3>
<p>问题：targets 里要不要把指令部分的 token 也置成 -100，让 loss 只在回答上累加？</p>
<p>我的结论（不盖）碰巧和书里默认一致，但论证错了两处：</p>
<ol>
<li><strong>BERT 类比是概念错位。</strong> 我以为「盖住指令有点像 BERT 让模型猜结论」。错。这里的掩码只发生在 targets 的 loss 层，inputs 原封不动，模型完整读到指令。三种 mask 分管三层：BERT 的 <code>[MASK]</code> 是输入 token（模型看不见），GPT 的 causal mask 在注意力矩阵（挡未来位置），SFT 的 loss mask 只影响梯度（不影响可见性）。</li>
<li><strong>指令微调是全部权重参与训练。</strong> 我以为「不是更新全部权重」。错。第六章冻结了大部分参数，第七章不做任何冻结——全参数、同结构、换数据。</li>
</ol>
<p>盖住指令的真实理由是「监督信号的焦点」：要让模型学会的行为是写回答，不是写指令。小数据集上两者差别不大，但业界主流 SFT 默认 completion-only。nanochat 阶段会再遇到这个开关。</p>
<h2 id="四为什么两轮就够了表面对齐假说">四、为什么两轮就「够了」：表面对齐假说</h2>
<p>训练只跑了 2 个 epoch，train loss 2.74 → 0.30，val loss 2.72 → 0.62，曲线平滑无过拟合。为什么这么快？</p>
<p><strong>因为指令微调不是学知识，是学姿势。</strong></p>
<ol>
<li><strong>知识早就在了。</strong> GPT-2 medium 预训练时见过几十亿 token，语法、常识全会。这两轮没有教任何新知识，教的是：看到 <code>### Instruction:</code> 就进入听话模式，回答要干脆，说完要吐 <code>&lt;|endoftext|&gt;</code>。这是行为格式的对齐，低维、好学。</li>
<li><strong>数据集高度同构。</strong> 1100 条、同一个模板、短平快回答，274 次梯度更新足够摸熟。</li>
<li><strong>loss 要会读。</strong> 交叉熵 0.657 ≈ 困惑度 1.93——但验证集和训练集同分布，窄分布上的低困惑度不等于通用能力。</li>
</ol>
<p>这个领域有个著名说法叫<strong>表面对齐假说</strong>（Superficial Alignment Hypothesis）：模型的能力几乎全部来自预训练，后训练只是调整它和人打交道的方式。我的 57 个 0 分（见下节）就是这个假说的实验证据。</p>
<h2 id="五训练事故cpu-和-mps-的一百倍">五、训练事故：CPU 和 MPS 的一百倍</h2>
<p>第一次训练，5 步跑了 3 分钟。原因：书里的代码是 <code>cuda if available else cpu</code>，Mac 没有 CUDA，直接落到 CPU。355M 全参数在 CPU 上，2 个 epoch 要 5 小时以上。</p>
<p>越等越不敢杀——这是沉没成本在拽人。正确的判断是：杀不杀和已经等了多久无关，只和继续等值不值有关。杀掉，改 MPS，重跑：<strong>完整训练 2 分 45 秒</strong>。一百多倍的差距。</p>
<p>这条纪律钉死：<strong>训练前先确认 device，确认方式是看日志第一行打出来的 device，不是凭感觉。</strong></p>
<p>device 改动是大肥鱼（另一个 AI）协助的，我做了口头验收：写死的 cpu 改成统一 device 变量，两处；权重加载走「先落 CPU 再 <code>.to(mps)</code>」的稳妥路径（<code>map_location=&quot;mps&quot;</code> 历史上有兼容性问题）。Kimi 又纠了我两个工程观念：</p>
<ul>
<li>张量要<strong>创建时就指定 device</strong>（<code>torch.tensor(data, device=device)</code>），而不是创建后 <code>.to(device)</code> 搬运——一搬 vs 百搬</li>
<li>device 要<strong>单一事实来源</strong>：把 <code>device_mac_util.py</code> 升级成 <code>get_device()</code> 函数，所有脚本共用，换 CUDA 机器一行业务代码都不用改。（已记入学习回炉待办）</li>
</ul>
<h2 id="六评估deepseek-当评委">六、评估：DeepSeek 当评委</h2>
<p>书里的评估方案是 LLM-as-judge：让另一个更强的模型给测试集的 110 条回答按 rubric 打分（0~100）。书里用 Ollama 本地跑 Llama 3 8B，我换成了 DeepSeek API——评委更强、不用本地下模型、一百多个请求成本可以忽略。</p>
<p>工程纪律三条：评委 <code>temperature=0</code>；结果文件里记录评委型号和日期（<code>judge: deepseek-flash, 2026-10-19</code>）；请求加重试。</p>
<h3 id="结果3409-vs-5032分数不可比">结果：34.09 vs 50.32，分数不可比</h3>
<p>书里用 Llama 3 当评委拿到 50.32，我用 DeepSeek 拿到 34.09。<strong>这两个分数不能直接比</strong>——分数只在同一个评委内部有意义，它是（模型，评委）这对组合的属性，不是模型自己的属性。</p>
<p>分布更有意思：</p>
<pre tabindex="0"><code>有效打分 110/110  |  mean=33.9  median=0  min=0  max=100
  0 分:   57  ███████████████████████████████
 1-20:    7  ███
21-40:    8  ████
41-60:    7  ███
61-80:    3  █
81-100:  28  ███████████████
</code></pre><p>双峰：57 个 0 分，28 个 81+。我的第一嫌疑是打分解析器坏了（DeepSeek 返回格式和 Ollama 不同，解析失败兜底 0）。查原始数据后反转：评委每次只返回一个数字 token，解析完全正常——<strong>这些 0 分大部分是罪有应得</strong>：</p>
<ul>
<li>氯的化学符号 → 答 C（碳）</li>
<li>疑问句类型 → 答 imperative（祈使句）</li>
<li>1000 克换算 → 答 0.1 千克</li>
<li>用 nostalgia 造句 → 造了一句不含 nostalgia 的</li>
</ul>
<p>Llama 3 的 50 分是宽宏大量，给「听起来像回事」的答案发参与奖；DeepSeek 是铁面判官，错就是 0。</p>
<h3 id="57-个-0-分画出的能力肖像">57 个 0 分画出的能力肖像</h3>
<p>把 0 分和高分按任务类型分开看，模型的真实画像出来了：</p>
<ul>
<li><strong>格式转换类</strong>（主动转被动、造比喻）→ 90+，指令微调<strong>学会了</strong></li>
<li><strong>知识事实类</strong>（化学符号、单位换算）→ 0，指令微调<strong>救不了</strong></li>
</ul>
<p>这就是表面对齐假说的实验版：<strong>微调教姿势，不教知识。</strong> 355M 的底子就这么多知识，1100 条指令只能教会它「怎么答」，教不会它「答什么」。</p>
<h3 id="实测样本节选">实测样本（节选）</h3>
<p><strong>高分区（81–100）</strong>——答得干脆的常识题和格式题：</p>
<blockquote>
<p><strong>指令</strong>：What is the capital of Denmark?
期望：The capital of Denmark is Copenhagen.
模型：The capital of Denmark is Copenhagen.（100 分）</p>
</blockquote>
<blockquote>
<p><strong>指令</strong>：Convert the sentence to passive voice. 输入：The gardener watered the plants.
期望：The plants were watered by the gardener.
模型：The plants were watered by the gardener.（100 分）</p>
</blockquote>
<blockquote>
<p><strong>指令</strong>：Convert the sentence to use an indefinite pronoun. 输入：Someone left a note.
期望：A note was left by someone.
模型：A note was left by someone.（100 分）</p>
</blockquote>
<blockquote>
<p><strong>指令</strong>：What is the chemical symbol for mercury?
期望：Hg.
模型：The chemical symbol for mercury is Hg.（100 分）</p>
</blockquote>
<p><strong>低分区（0 分）</strong>——精确知识、小语种、换算，全是 355M 底子的边界：</p>
<blockquote>
<p><strong>指令</strong>：What is the periodic symbol for chlorine?
期望：The periodic symbol for chlorine is Cl.
模型：The periodic symbol for chlorine is C.（0 分，氯答成了碳）</p>
</blockquote>
<blockquote>
<p><strong>指令</strong>：Create a sentence using the word &rsquo;nostalgia&rsquo;.
期望：Nostalgia washed over her as she looked through the old photos.
模型：The past was a distant memory.（0 分，句子本身不差，但没用 nostalgia 这个词）</p>
</blockquote>
<blockquote>
<p><strong>指令</strong>：Convert 1000 grams to kilograms.
期望：1000 grams is equal to 1 kilogram.
模型：1000 grams is 0.1 kilograms.（0 分）</p>
</blockquote>
<blockquote>
<p><strong>指令</strong>：Convert 7 kilometers to meters.
期望：7 kilometers is 7000 meters.
模型：7 kilometers is 7.048 meters.（0 分，错得一本正经还精确到小数点）</p>
</blockquote>
<blockquote>
<p><strong>指令</strong>：Translate &rsquo;library&rsquo; into Spanish.
期望：The Spanish word for &rsquo;library&rsquo; is &lsquo;biblioteca&rsquo;.
模型：Están llegarme.（0 分， multilingual 直接崩了）</p>
</blockquote>
<blockquote>
<p><strong>指令</strong>：What is the past tense of &lsquo;sing&rsquo;?
期望：The past tense of &lsquo;sing&rsquo; is &lsquo;sang.&rsquo;
模型：The past tense of ‘sing’ is “to sing.”（0 分）</p>
</blockquote>
<p>高分区也不全是格式题——丹麦首都、汞的符号这种「大众常识」它答得上来；一碰到精确换算、小语种、罕见知识就露馅。所以更准确的分界线是：<strong>预训练语料里高频出现的东西能保住，低频的保不住</strong>。微调没有增加任何一边的库存。</p>
<h2 id="七本章的新概念kv-cache">七、本章的新概念：KV cache</h2>
<p>学这章的晚上突然反应过来：KV cache 就是 trf 里 Q/K/V 的那个 K 和 V。谜底就在谜面上。</p>
<p>因果注意力下，生成第 n+1 个 token 时只有它的 Q 是新的；之前 token 的 K、V 在生成那步已经算完且永不变，存下来复用即可。而我的 <code>generate()</code> 每生成一个 token 就把整段序列重新过一遍模型——KV cache 消掉的就是这个重复劳动。再看新闻里「KV Cache 压缩」，就知道它在省什么了。</p>
<h2 id="八欠账记入学习回炉待办">八、欠账（记入学习回炉待办）</h2>
<ol>
<li><code>device_mac_util.py</code> 升级成 <code>get_device()</code> 单一入口</li>
<li>checkpoint 标准化：权重 + config + optimizer + val_loss 一起存，文件名带语义</li>
<li>GGUF 化 + Ollama 部署：<code>.pth</code> → HF 格式 → GGUF → Modelfile，和自己微调的 355M 聊天（nanochat 部署链的预演）</li>
<li>双评委评估：DeepSeek + 本地模型交叉打分（2025 年「一个命题喂多个大模型」想法的第一个落地场景）</li>
</ol>
<h2 id="九一句话总结">九、一句话总结</h2>
<p>指令微调没有新算法，全是针脚：一个 +1、一个 -100、一个模板、一个评委。模型的「听话」不在模型里，在这些决定里。</p>
<h2 id="十系列收官第一份完整答卷">十、系列收官：第一份完整答卷</h2>
<p>到这一章，《从零构建大模型》的正文走完，这个系列的第一季收官。最后把这份答卷的分数原样贴上——不好看，但它是我自己的模型、自己的评委、自己的数据：</p>
<pre tabindex="0"><code>评委：DeepSeek (deepseek-flash)，2026-10-19，temperature=0
对象：GPT-2 medium (355M)，1100 条指令数据微调 2 个 epoch
测试集：110 条

有效打分 110/110  |  mean=33.9  median=0  min=0  max=100
  0 分:   57  ███████████████████████████████
 1-20:    7  ███
21-40:    8  ████
41-60:    7  ███
61-80:    3  █
81-100:  28  ███████████████
</code></pre><p>从笔记 00 的立项书到今天，手上多了这些东西：一个手敲的分词流程、一套从单头到多头的注意力、一个 124M 的 GPT、一次小规模预训练和它的过拟合曲线、一个垃圾短信分类器、一个会听指令会说「我说完了」的 355M、以及一套给它打分还被评委上了一课的评估流水线。</p>
<p>分数不好，但证据链完整。接下来是第二遍回顾（欠的手写回炉在<a href="https://blog.lvxinrong.com/llm/backlog/">学习回炉待办</a>里），回顾和 nanochat 同步开始。</p>
]]></content:encoded>
    </item>
  </channel>
</rss>
