Cover of Language Models from the Ground Up, edition 2026.11.16, code FY8Q-PVVV Language Models from the Ground Up FY8Q-PVVV 24 editions since Oct 2026 Rolling Edition 2026.11.16

从零开始构建语言模型

版次 2026.11.16 示例于 2026年11月19日 通过 86个示例中有86个通过 变化内容

AI 翻译。由人工以英文核验。 我们如何制作图书

译自英文版图书,版次 2026.11.16。 阅读原文

语言模型如何工作,一次构建一个部分:下一个词预测、词元、嵌入、神经网络模型、注意力与 transformer、在 CPU 上训练小模型、选词、开放模型内部包含什么,以及指令微调如何改变它。

适合谁 本书写给熟悉 Python 和 NumPy、但刚开始了解语言模型如何工作的读者:既包括调用 LLM API、想知道其内部运行机制的开发者,也包括转向语言处理工作的数据科学家。

开始阅读
版次历史自 2026年十月 以来的 24个版次每个版次及其变更内容
2026.10.12026.11.16
2026.11.16 · 2026年11月21日文字修订,新内容44节已更改

目录

11章,阅读约需 8小时 27分钟,包含 86个示例。

  1. 1预测下一个词

    读完本章,你将能够:通过计数,用商店的商品名称构建一个完整的语言模型;用它在购物者输入时建议下一个词;用它生成文本;并用一个数字衡量它对从未见过的文本的预测效果。

  2. 2Token(词元)

    读完本章,你将能够从零构建一个字节对编码(byte-pair encoding)分词器,通过衡量每种词表大小的代价来选定词表规模,并读懂一个开源语言模型的分词器,达到能够手工应用其合并规则的程度。

  3. 3Counting further back

    By the end of this chapter you can build an n-gram language model that looks several tokens back, smooth it with Kneser-Ney so it handles text it hasn't seen (smoothing gives some probability to what the counts never saw, as chapter 1 showed), measure the baseline that every neural model in this book is measured against, and see why counting, however clever, runs out of road.

  4. 4Words as vectors

    By the end of this chapter you can turn every token of the store's text into a short vector of numbers, so that tokens used in similar ways get similar vectors, by two methods: compressing counts of which tokens appear together, and training a small model to predict each token's neighbours.

  5. 5神经语言模型

    读完本章,你将能够构建一个神经语言模型,根据前面若干词元构成的窗口预测下一个词元;手工推导并检验它的梯度;用 PyTorch 训练它;并在公平的条件下与计数基线进行比较。

  6. 6注意力

    学完本章,你将能够手工计算注意力:为每个词元的查询(query)与之前每个词元的键(key)的匹配程度打分,把分数转换为权重,再对这些权重所选出的值(value)取平均。

  7. 7Transformer 块

    读完本章,你将能够用注意力、归一化、门控前馈层和位置信息这几个部分,通过残差连接组装出一个 transformer 块,再把多个块堆叠成完整的语言模型。

  8. 8训练一个小模型

    学完本章,你可以从头到尾训练一个小型 transformer,并对结果做出判断。

  9. 9Choosing the next token

    By the end of this chapter you can turn a language model's probabilities into text, and choose how: always the likeliest token, the likeliest whole text by beam search, or a sample shaped by a temperature, a top-k or top-p cut, a repetition penalty and a minimum length.

  10. 10Inside an open model

    By the end of this chapter you can read an open language model with what this book has built: count where its parameters go, work out what it costs to run, score text with it fairly against a model with a different tokenizer, find the attention patterns of chapter 6 in its heads, test what it copies, and learn what its size buys on the store's text, and what it doesn't.

  11. 11从预测到遵循指令

    学完本章,你能够解释一个预测下一个词元的模型如何变成遵循 requests 的模型,构建完成这一转变的两个训练损失,并衡量这一转变解决了什么、没有解决什么。

引用本节

格式

每种格式均引用英文原书,本译本以其为准。

每种格式都会注明该版次。其链接会打开当前版次,节标题处会说明该节文本最后一次修改的时间。访问日期和检索日期即为您打开此页的当天。