从零开始构建语言模型
语言模型如何工作,一次构建一个部分:下一个词预测、词元、嵌入、神经网络模型、注意力与 transformer、在 CPU 上训练小模型、选词、开放模型内部包含什么,以及指令微调如何改变它。
适合谁 本书写给熟悉 Python 和 NumPy、但刚开始了解语言模型如何工作的读者:既包括调用 LLM API、想知道其内部运行机制的开发者,也包括转向语言处理工作的数据科学家。
在 Kindle 或任意电子阅读器上阅读
EPUB 格式也适用于 Apple Books、Kobo 及大多数电子阅读器。
发送到 Kindle
将本版次的 EPUB 发送至 简体中文.
-
批准我们的地址
亚马逊仅向您已批准的地址所发送的内容投递至 Kindle,且每项邮件服务须单独批准。请将我们的地址添加到您的已批准个人文档电子邮件列表中。
books@rollingedition.com打开亚马逊的个人文档设置. 在亚马逊上,该选项位于“管理您的内容和设备”、“偏好设置”、“个人文档设置”下。
已发送。几分钟后将出现在您的 Kindle 书库中。
如果未能送达,几乎总是第 1 步的批准设置有问题:请检查 books@rollingedition.com 是否已列入您的已批准个人文档电子邮件列表。
您已保存图书的每个新版次也将发送到您的 Kindle。
这不是 Kindle 地址。地址应以 @kindle.com 结尾,可在亚马逊的“个人文档设置”中找到。
你今天已发送{count}本图书,这是单个账户一天可发送的最大数量。请明天再试。
今日可发送的书籍已达上限。请明天再试。
图书未能发送,请几分钟后重试。
本版次体积过大,无法通过电子邮件发送。
发送到 Kindle 功能随 Labs 提供。
这不是 Kindle 地址。地址应以 @kindle.com 结尾,可在亚马逊的“个人文档设置”中找到。
图书未能发送,请几分钟后重试。
或者下载 EPUB 文件,并将其拖放到亚马逊的“发送至 Kindle”页面。
Kindle is a trademark of Amazon.com, Inc.
目录
11章,阅读约需 8小时 27分钟,包含 86个示例。
-
1预测下一个词
读完本章,你将能够:通过计数,用商店的商品名称构建一个完整的语言模型;用它在购物者输入时建议下一个词;用它生成文本;并用一个数字衡量它对从未见过的文本的预测效果。
-
2Token(词元)
读完本章,你将能够从零构建一个字节对编码(byte-pair encoding)分词器,通过衡量每种词表大小的代价来选定词表规模,并读懂一个开源语言模型的分词器,达到能够手工应用其合并规则的程度。
-
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.
-
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神经语言模型
读完本章,你将能够构建一个神经语言模型,根据前面若干词元构成的窗口预测下一个词元;手工推导并检验它的梯度;用 PyTorch 训练它;并在公平的条件下与计数基线进行比较。
-
6注意力
学完本章,你将能够手工计算注意力:为每个词元的查询(query)与之前每个词元的键(key)的匹配程度打分,把分数转换为权重,再对这些权重所选出的值(value)取平均。
-
7Transformer 块
读完本章,你将能够用注意力、归一化、门控前馈层和位置信息这几个部分,通过残差连接组装出一个 transformer 块,再把多个块堆叠成完整的语言模型。
-
8训练一个小模型
学完本章,你可以从头到尾训练一个小型 transformer,并对结果做出判断。
-
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.
-
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从预测到遵循指令
学完本章,你能够解释一个预测下一个词元的模型如何变成遵循 requests 的模型,构建完成这一转变的两个训练损失,并衡量这一转变解决了什么、没有解决什么。