PRODUCT

Design

Content

Publish

RESOURCES

Blog

Careers

Docs

About

Writings

Which Word is Next?

Which Word is Next?

大语言模型

Preface: Following the previous #AI series and #MarvinMinsky series. This post is co-written with Claude.


1951: Prediction and Entropy of Printed English

Around 1950, Claude Shannon of Bell Labs and his wife, Mary, played a game at home. He pulled a book off the shelf, covered the title, and opened it to a random passage. Her job was to guess the passage one letter at a time. If she got a letter right, she moved on to the next. If she got it wrong, he told her the answer and the game continued. She got the first letter on her first try: T. Then h, e, a space. After the first word, many letters hardly needed guessing. What came before had already decided them.



In January 1951, Shannon turned the game into a paper, "Prediction and Entropy of Printed English," published in the Bell System Technical Journal. He wanted to measure how much of English is predictable. The answer was: a lot. In ordinary literary English, if you take the previous hundred letters into account, roughly three quarters of the text is redundant. "Redundant" here doesn't mean useless. It means it can be inferred from what came before. Shannon measured this in bits.



A bit is the amount of information you get from the answer to one yes-or-no question. Flip a coin and there are two possibilities; one question, "Is it heads?", settles it. That's 1 bit. With four possibilities, ask "Is it one of the first two?" and then "Is it the first?": two questions, 2 bits. With eight, each question rules out half, so three questions, 3 bits. Every time the number of possibilities doubles, you need one more question.



Now try it on a letter. English has 26 letters, plus a space, for 27 possibilities. Guess the way you would in a game of twenty questions, cutting the field in half each time. "Is it between A and M?" leaves about 14. Ask again and about 7 remain, then 4, then 2, then 1. Sometimes that takes four questions, sometimes five. Four questions can sort out at most 16 options (2 × 2 × 2 × 2), and five can sort out 32. Twenty-seven falls in between, and worked out exactly, the average comes to 4.75 questions. That's 4.75 bits per letter. That's the case where every letter is completely random, with no pattern to go on.

But real English has patterns. Shannon's experiments found that once the preceding text is taken into account, each letter carries only about 1 bit of new information on average, as if a single yes-or-no question were enough to pin down the next letter. The drop from 4.75 questions to 1 is what's redundant.

Strip the vowels out of a sentence: Th_ k_tt_n sl__ps _n th_ s_f_. Most people can still read it. Q is almost always followed by u; th is likely followed by e; after "The kitten sleeps on the," the next word is probably sofa, bed, or floor. Every letter you can delete and still guess is redundant.

The redundancy isn't waste. Speech happens amid noise, accents, and missed syllables, and the redundant part lets people understand even when some of it gets lost. It also means that what can be predicted can be compressed, and that a machine can learn to guess.


An N-Gram Model

The simplest version came from Shannon himself, and the method was counting. Go through a large body of text and tally which word most often follows which. "Drink" is usually followed by "water," "tea," or "wine," rarely by "table." Chain words together by these frequencies, one after another, and you get strings that look like English but mean nothing.

An n-gram model is a model that looks only at the last few words and guesses the next one from frequency counts. Look at two words to guess the third, and it's a trigram model. This approach was used for decades. Speech recognition and early machine translation both relied on it. But it had two fundamental problems.

A tiny example shows how it works. Suppose all the text the machine has ever read is four sentences: I drank water. I drank tea. I drank tea. He drank wine. A bigram model, which looks only at the previous word, records every pair of neighboring words and counts how often each appears. After "drank," the counts look like this:


Word after "drank"

Count

Probability

water

1

25%

tea

2

50%

wine

1

25%


Divide each count by the total and you have a probability. This table is everything the model knows. To guess the next word, it picks the most likely one: after "drank," it guesses "tea." To generate a sentence, it draws by probability, adds the word, then looks up the new word in the table, one word after another. Shannon did this by hand in 1948: open a book at random, find the current word, write down the word that follows it; then open to another page, find the word just written down, and see what follows that. English assembled this way is natural from one word to the next, and senseless as a whole.



A trigram model does the same thing but looks at the previous two words. After "I drank," "water" appears once and "tea" twice; after "he drank," "wine" appears once. Reading "he drank," the trigram model guesses "wine." The bigram model sees only "drank" and still guesses "tea." One more word of context, a slightly better guess. But give it "she drank," and there's no "she drank" in the table at all. The count is zero, and the model has no idea what comes next.

This approach was used for decades. Speech recognition and early machine translation both relied on it. But it had two fundamental problems.

First, it can't see far. Looking only two or three words back, it has no idea what the passage was about at the start. Try to look further and the number of combinations to count explodes: with ten thousand common words, there are a hundred million possible two-word combinations and a hundred quintillion five-word ones. Everything humans have ever published adds up to a few hundred trillion words, not even a rounding error against that. Even a perfectly ordinary phrase like "the pickled beans grandma made yesterday" may never have been written in exactly that order. If a sequence never appears, its count is zero, and the model has no idea what comes next. So it can only look two or three words back, because only sequences that short are common enough to count. Second, it doesn't understand similarity. To it, "cat" and "dog" are two unrelated symbols, as unrelated as "cat" and "piano." Having seen "the cat is sleeping on the sofa," it cannot infer that "the dog is sleeping on the sofa" also makes sense.


Neural Networks

A neural network is a web of very simple calculating units, each of which takes in a few numbers and passes one number on. Each unit, loosely called a neuron, does three things: it multiplies each incoming number by a weight, adds the results together, and squeezes the sum into a fixed range.



Say the question is whether to see a movie tonight. The inputs are the review score (8), whether a friend is going (yes, 1), and whether the theater is far (yes, 1). Give the score a weight of 0.5, the friend 2, the distance -1.5: 8 × 0.5 + 1 × 2 + 1 × (-1.5) = 4.5, which squeezes to nearly 1. Go. If the friend isn't going, the total drops to 2.5. Still go, but less sure. The unit understands nothing; every bit of its judgment lives in those weights.

Put many units side by side and you have a layer. Each one sees the same inputs but weighs them differently, so each picks up on something different. Feed one layer's outputs into the next, and the next, and the final layer gives the answer. A single layer can only make crude judgments; stacked layers can combine simple features into more and more complex ones.

At the start, all the weights are random and the network's answers are nonsense. In training, it sees a large number of examples. Each time, its answer is checked against the right one, and the error is passed backward from the last layer to the first, telling each weight whether to go up or down a little. After millions of these small corrections, the weights settle into something that gets the answers right. No one writes the rules. They are tuned out of the data.

In February 2003, Yoshua Bengio and three colleagues at the Université de Montréal published "A Neural Probabilistic Language Model" in the Journal of Machine Learning Research. Their proposal had three parts. Give every word in the vocabulary its own string of numbers; in their experiments, 30, 60, or 100 of them. Compute the probability of the next word from the numbers of the words before it, instead of looking it up in a table. And learn both the numbers and the way of computing with them at the same time, without anyone setting them in advance.



To guess what follows "he drank," the model looks up the numbers for "he" and "drank," lines them up side by side, and feeds them into a neural network, which puts out a probability for every word in the vocabulary: so much for wine, so much for tea, so much for table.

In training, it guesses the next word over and over across a large body of text. Each time it's wrong, two things get adjusted: the network's weights, and the numbers for the words it just used, both nudged so the right answer becomes more likely.



Over time, words that turn up in similar places end up with similar numbers. "He" and "she" are often followed by the same words, said, went, drank, so their numbers drift close together. Even if "she drank" has never appeared, its numbers look a lot like those of "he drank," and the network gives a similar answer. The paper's own example: having seen a sentence about a cat walking in the bedroom should make one about a dog running in a room seem nearly as likely, because cat and dog, bedroom and room, walking and running all sit near each other.

On both of the text collections they tested, the model clearly beat the best n-gram models of the day. The cost was speed. The paper itself noted that training a model with millions of parameters in a reasonable amount of time was a serious challenge in its own right. That is why the idea sat for a decade.


2013: word2vec

The idea took a decade to catch on. In 2013, researchers at Google released word2vec, a tool that could be trained quickly on enormous amounts of text. What it does is simple: each word learns to predict which words appear around it. Once training is done, every word has become a point in a space with a few hundred dimensions. A word vector is a string of numbers representing a word, where words with similar meanings sit close together.



The surprise was that directions in this space carry meaning too. Take the coordinates of "king," subtract "man," add "woman," and the nearest point is "queen." No one taught it what gender is. It simply found, across billions of words, that the difference between "king" and "queen" looks a lot like the difference between "man" and "woman."

But there is a limit: each word gets exactly one set of coordinates. "Bank" means both a financial institution and the edge of a river, and in word2vec it can only sit somewhere awkward in between. A word's meaning depends on context, and a word vector has no context.

To understand context, you have to read the whole sentence. The main tool for that at the time was the recurrent neural network. A recurrent neural network (RNN) is a network that reads from left to right, one word at a time, updating its "memory" after each word.



This "memory" isn't a piece of text. It's a string of numbers, usually a few hundred of them. Think of it as a small whiteboard that says, "Here's what I understand of this sentence so far." At the start, the whiteboard is blank: all zeros.

Take the sentence "The kitten sleeps on the sofa." When the network reads "kitten," it combines two things: what's currently on the whiteboard (still blank) and the word vector for "kitten." Each is multiplied by a set of weights, the results are added together, and the sum is passed through a function that squeezes the values into a fixed range. That gives a new whiteboard. The old one is wiped and replaced. Weights are the coefficients a neural network uses to mix its inputs; training is the process of adjusting them.

An activation function is a simple function a neural network applies after every mixing step. The one most commonly used in recurrent networks is the hyperbolic tangent (tanh), which squeezes any number into the range between -1 and 1: feed it 0.5 and you get 0.46; feed it 3 and you get 0.995; feed it 100 and you still get less than 1.

Why squeeze? Plug in some numbers and see. Suppose the network is reading this film review: "The cinematography is beautiful, the acting superb, the score moving, the opening thrilling, the dialogue memorable, but the middle is dull, the pacing sluggish, the ending rushed, and overall it's a letdown".

To keep things simple, we look only at the evaluative word in each clause. The first five are positive, and each adds +1 to the whiteboard. The last four are negative, and each adds -1. A real whiteboard holds a few hundred numbers; here we reduce it to one. As described above, each time a word is read, the new whiteboard equals the old whiteboard multiplied by a weight, plus whatever the new word contributes. The weight on the old whiteboard determines how much the past counts in the new whiteboard: below 1, the past fades step by step; above 1, the past is amplified step by step.

In a real network, the weights are learned, and among a few hundred of them some will always be greater than 1. Setting the weight to 2 here lets us see what happens when that's the case. So the rule is: multiply the number on the old whiteboard by 2, then add the word's +1 or -1. The whiteboard starts at 0. At "beautiful," 0 × 2 + 1 = 1. At "superb," 1 × 2 + 1 = 3. At "moving," 3 × 2 + 1 = 7. The squeezed column applies tanh after each step: at "beautiful," 0 × 2 + 1 = 1, which squeezes to 0.76; at "superb," 0.76 × 2 + 1 = 2.52, which squeezes to 0.99.


Word read

Contributes

Unsqueezed whiteboard

Squeezed whiteboard

beautiful

+1

1

0.76

superb

+1

3

0.99

moving

+1

7

0.99

thrilling

+1

15

0.99

memorable

+1

31

0.99

dull

-1

61

0.76

sluggish

-1

121

0.47

rushed

-1

241

-0.05

letdown

-1

481

-0.80


Start with the unsqueezed column. The five positive words push the number up to 31. From "dull" onward, the review turns negative, but each negative word subtracts only 1, while the whiteboard doubles at every step, so the number keeps climbing. By "letdown," the whiteboard reads 481. The network still thinks this is a rave. Keep reading, and the number would grow too large for the computer to store.

Now the squeezed column. The first five words push the whiteboard close to 1, and there it stops. It can't climb any higher. So when the negative words arrive, they pull it down quickly: 0.76 at "dull," 0.47 at "sluggish," negative by "rushed," and -0.80 after "letdown." The whiteboard changes its mind. It works like a limiter in a recording studio: no matter how loud the sound, it never goes past a ceiling, so one loud bang can't drown out everything that follows.

Then the network reads "sleeps." Same procedure: old whiteboard plus "sleeps," mix, squeeze, new whiteboard. Then "on," "the," "sofa," step by step. After the last word, what's on the whiteboard is the network's understanding of the whole sentence. To guess the next word, it computes the probability of every word from the current whiteboard.

The crucial point is that every step uses the same set of weights. Reading the first word and reading the hundredth word follow the same rules; only the incoming whiteboard and the word change. The same small network is used over and over in a loop, which is why it's called a recurrent neural network. It's also why it can read a sentence of any length.

To train it, you have it guess the next word across a large amount of text. When it guesses wrong, you measure how wrong, then pass that error backward through time: how the last step should be adjusted, how the step before that should be adjusted, all the way back to the first word. Because every step uses the same weights, all these adjustments end up added to the same set of weights.

The trouble is on the way back. Each step the error travels backward, it gets multiplied by the weights once more. Multiply a few dozen times and a number either shrinks toward zero or grows out of control. Multiply 0.9 by itself fifty times and you're left with 0.005; multiply 1.1 by itself fifty times and you get 117. In practice it's usually the first.


The Vanishing Gradient Problem

The vanishing gradient problem is when the error signal grows weaker as it travels backward, so that steps far in the past receive almost no adjustment. The result is that the network has a hard time learning that something thirty words back matters now. And because the whiteboard is rewritten in full at every step, what was written early on gets gradually washed out. Take "Joe is a baseball player, and after a good breakfast he went to the park and got two hits." By the time the network reaches "hits," "baseball" has faded almost to nothing on the whiteboard. The problem was identified in the early 1990s.




The LSTM (long short-term memory network), proposed in 1997, was the answer. Alongside the whiteboard, it adds a "conveyor belt" dedicated to keeping information over the long term. What's on the belt isn't rewritten in full at every step. It's controlled by three "gates." The forget gate was added around 2000; the original version had only two.



The forget gate decides which old contents on the belt should be erased. Reading a new subject, for instance, it erases the old one. The input gate decides which information from the current word is worth writing down. Reading "baseball player," it writes down "this passage is about baseball"; reading "good," it may write nothing. The output gate decides what to take off the belt for use at this step. Reading "hits," it takes out "baseball."

Each gate is itself a string of numbers between 0 and 1, where 0 is fully closed and 1 is fully open. When a gate opens, and how wide, is also something the network learns from data. No one tells it what a "subject" or "baseball" is.

More importantly, updates to the belt are additions and subtractions to what's already there, not a multiply-and-overwrite at every step. As long as the forget gate stays open, a piece of information can sit on the belt untouched for many steps. When the error signal travels backward, it can also ride the belt a long way without fading. That's why an LSTM remembers longer. By the mid-2010s, it was the most widely used architecture in speech recognition and machine translation.

But whether it's a plain recurrent network or an LSTM, one limit can't be removed: it has to finish reading "kitten" before it can read "sleeps." Every new whiteboard has to wait for the previous one to be computed.

In 2014, researchers used two of these networks for translation. The first reads the source sentence and compresses the whole thing into a fixed-length string of numbers; the second writes out the translation from that string, one word at a time. This is called an "encoder-decoder." The length of the string is fixed. Whether the source sentence has five words or fifty, it has to fit into a box of the same size. The longer the sentence, the more the translation starts to lose. That same year, Dzmitry Bahdanau and his collaborators came up with a patch, built around the attention mechanism, which lets the model decide at each step which parts of the input matter most. When translating "bank," for example, it looks for "river" or "money" in the source sentence.


The Attention Mechanism



Here's how it's computed. Each time the decoder is about to write a word, it takes its current state and compares it against every word in the source sentence, giving each one a score. The scores are converted into proportions that add up to 1: say "river" gets 0.7, "sat" gets 0.2, and the remaining words split the last 0.1. The information from each source word is then blended according to these proportions and handed to the decoder to write the next word. Before the next word, the scores are calculated all over again. The box is still the same size, but it's repacked at every step with only what that step needs.

The paper Bahdanau and his collaborators released in September 2014, "Neural Machine Translation by Jointly Learning to Align and Translate," includes a figure that draws these proportions as a grid of squares in varying shades.



On one side is an English sentence about an agreement on the European Economic Area signed in August 1992; on the other is the model's French translation. Most of the dark squares line up along a diagonal, because the two languages mostly share word order: the nth word of the translation lines up with the nth word of the source.

In one place, the diagonal bends. English says "European Economic Area," with two adjectives before the noun; French says "zone économique européenne," with the noun first and the adjectives after. When the model writes "zone," it skips the first two words and looks straight at "Area"; for "économique," it looks back one word; for "européenne," one more. No one told it that French adjectives come after the noun. It learned, from a large body of parallel translations, where to look and when.

Alignment is which word in the translation corresponds to which word in the source. Earlier statistical translation systems had to train a separate model just to work out alignment. Attention turned it into a by-product of translation itself. In 2016, Google Translate put this approach into its product.

Before that, it had used phrase-based statistical translation. The method starts with a large supply of the same sentences in two languages. The most common sources were the proceedings of bodies like the United Nations and the European Parliament, where every sentence is already translated into several languages by professional translators. From millions of such sentence pairs, the system works out which words correspond, then cuts frequently co-occurring words into phrases and records every way each phrase has been translated, along with how often. The Chinese 开会, "to meet," for instance, might be "have a meeting" or "hold a meeting." These phrase tables could run to hundreds of millions of entries.



To translate a new sentence, the system cuts it into pieces, picks a translation for each piece from the table, shuffles the order within a narrow range, and assembles thousands of candidate translations. It picks one based on two scores: the translation probabilities from the phrase table, and how much the result sounds like English. The second score comes from the same n-gram model described above: it looks only at whether two or three neighboring words commonly appear together.



Each piece holds up on its own, but no step ever actually understands the whole sentence. As sentences get longer, the seams start to show: subjects and verbs don't agree, pronouns point to the wrong person, the word order still carries traces of the original. That familiar quality of early machine translation, every word right and the whole thing unlike anything a person would say, comes from here.

In September 2016, Google announced that Chinese-to-English translation on its web and mobile versions had been switched entirely to the new neural network system, a direction handling about 18 million translations a day. The new system's encoder and decoder each had eight layers of LSTM, connected by attention. By Google's own human evaluations, across English–French, English–Spanish, and English–Chinese, translation errors fell by about 60 percent on average compared with the old system. The paper also acknowledged its flaws: it still dropped words, mistranslated names and rare terms, and translated one sentence at a time without regard to what the sentence meant in the surrounding paragraph.

Attention was still just an add-on. Underneath, the recurrent network still read one word at a time, and the tenth word had to wait for the ninth. On the hardware, that was a waste. More on this in the next post. 🧪

Preface:接续之前的 #AI 系列和 #MarvinMinsky 系列。本文由我和 Claude 合作完成。

1951:《英语印刷文本的预测与熵》

1950 年前后,贝尔实验室的 Claude Shannon 和妻子 Mary 在家里玩一个游戏。他从书架上抽出一本书,遮住书名,随手翻到一段。她的任务是一个字母一个字母地猜出这段话。猜对了,就猜下一个;猜错了,他就告诉她正确答案,游戏继续。她第一个字母一猜就中:T。接着是 h、e、空格。开头一个词之后,很多字母几乎不用猜,前面的内容已经把它们决定了。

1951 年 1 月,Shannon 把这个游戏写成了一篇论文,叫《英语印刷文本的预测与熵》(Prediction and Entropy of Printed English),发表在《贝尔系统技术期刊》上。他想测的是英语有多少是可以预测的。结论是:很多。在一般的文学英语里,如果把前面一百个字母都算上,大约四分之三的内容是多余的。这里的"多余",不是"没用",而是"可以从前文推出来"。Shannon 用来计量的单位叫比特。

比特,是回答一个是非题所得到的信息量。 抛一枚硬币,只有两种可能,问一句"是正面吗?"就知道了,这是 1 比特。四种可能,先问"在前两个里吗?",再问"是第一个吗?",两个问题,2 比特。八种可能,每问一次排除一半,三个问题,3 比特。可能性每翻一倍,就多需要一个问题。

现在拿一个字母来试试。英文有 26 个字母,加上空格,一共 27 种可能。像玩"二十个问题"那样猜,每次把范围砍掉一半。问"在 A 到 M 之间吗?",还剩大约 14 个;再问一次,剩大约 7 个,然后 4 个、2 个、1 个。有时问四次就够,有时要问五次。四个问题最多能区分 16 种可能(2 × 2 × 2 × 2),五个问题能区分 32 种。27 正好落在中间,精确算下来,平均是 4.75 个问题,也就是每个字母 4.75 比特。这是每个字母都完全随机、毫无规律可循时的情况。

但真实的英语有规律。Shannon 的实验发现,把前文考虑进去以后,平均每个字母只带大约 1 比特的新信息,相当于平均只要问一个是非题,就能确定下一个字母。从 4.75 个问题降到 1 个,省下的那部分,就是多余的。

把一句英文里的元音都删掉:Th_ k_tt_n sl__ps _n th_ s_f_。大多数人还是读得出来,原句是"The kitten sleeps on the sofa"(小猫睡在沙发上)。q 后面几乎总是 u;th 后面很可能是 e;读到"The kitten sleeps on the"之后,下一个词多半是沙发、床或者地板。每一个删掉也能猜出来的字母,都是多余的。

这种多余并不是浪费。说话的环境里到处是噪音、口音和听漏的音节,多余的部分让人即使漏掉一些,也能听懂。它还意味着,能预测的东西就能压缩,机器也能学着去猜。

N 元模型

最简单的版本就来自 Shannon 本人,方法是数。在一大堆文字里统计,某个词后面最常跟着哪个词。"喝"后面常常是"水"、"茶"、"酒",很少是"桌子"。照着这些频率一个词一个词往下接,就能生成一串看起来像语言、但没有意义的句子。

N 元模型(n-gram),是只看前面几个词、按统计频率猜下一个词的模型。 看前两个词猜第三个,就叫三元模型。这个办法用了几十年,语音识别和早期的机器翻译都靠它。但它有两个根本的问题。

一个很小的例子就能说明它是怎么运作的。假设机器读过的全部文字只有四句话:我喝水。我喝茶。我喝茶。他喝酒。只看前一个词的二元模型,会把每一对相邻的词都记下来,数一数各出现了几次。"喝"后面是这样的:

"喝"后面的词

出现次数

概率

水

1

25%

茶

2

50%

酒

1

25%

次数除以总数,就是概率。这张表就是模型的全部知识。要猜下一个词,它就选概率最高的:读到"喝",猜"茶"。要生成句子,它就按概率抽签,接上一个词,再拿这个新词去查表,一个一个往下接。Shannon 1948 年就手工这样做过:随手翻开一本书,找到当前这个词,写下它后面跟的那个词;再翻到另一页,找到刚写下的这个词,看它后面又跟什么。这样拼出来的文字,每两个相邻的词都很自然,整句话却不知所云。

三元模型是同样的做法,只是改成看前两个词。"我 喝"后面,"水"出现 1 次,"茶"出现 2 次;"他 喝"后面,"酒"出现 1 次。读到"他喝",三元模型会猜"酒";二元模型只看得到"喝",还是猜"茶"。多看一个词,就猜得准一点。但如果来了一句"她喝",表里根本没有"她 喝"这一项。次数是零,模型完全不知道该接什么。

这个办法用了几十年,语音识别和早期的机器翻译都靠它。但它有两个根本的问题。

第一,它看不远。只看前两三个词,就不知道一段话开头讲了什么。想看得远一点,要统计的组合就会爆炸:假设常用词有一万个,两个词的组合就有一亿种,五个词的组合有一万亿亿种。人类公开发表过的全部文字加起来,也只有几百万亿个词,连这些组合的零头都覆盖不了。就算是一句再平常不过的话,比如"外婆昨天腌的酸豆角",这几个词按这个顺序,也很可能从来没有人写过。一个组合没出现过,次数就是零,模型就完全不知道接下来该接什么。所以它只能看前两三个词,因为只有这么短的组合,才常见到数得出次数。第二,它不懂相似。对它来说,"猫"和"狗"是两个毫不相干的符号,就像"猫"和"钢琴"一样不相干。它见过"猫在沙发上睡觉",推不出"狗在沙发上睡觉"也说得通。

神经网络

神经网络,是由许多极其简单的计算单元连成的一张网,每个单元接收几个数,再传出一个数。 每个单元,通常叫作神经元,只做三件事:把每个输入的数乘上一个权重,把结果加在一起,再把这个和压到一个固定的范围里。

比如要决定今晚去不去看电影。输入有三个:影评分数(8 分),朋友去不去(去,记作 1),电影院远不远(远,记作 1)。给影评的权重是 0.5,朋友是 2,距离是 -1.5:8 × 0.5 + 1 × 2 + 1 × (-1.5) = 4.5,压完接近 1。去。如果朋友不去,总数就降到 2.5,还是去,但没那么确定了。这个单元本身什么也不懂,它全部的判断都藏在那几个权重里。

把很多个这样的单元并排放在一起,就是一层。每个单元看到的是同样的输入,但各自的权重不一样,所以各自关注的东西也不一样。把一层的输出交给下一层,再交给下一层,最后一层给出答案。单独一层只能做很粗的判断;叠起来的层,可以把简单的特征组合成越来越复杂的特征。

一开始,所有的权重都是随机的,网络给出的答案毫无意义。训练时,它会看大量的例子。每看一次,就把它的答案和正确答案对照,再把错误从最后一层往回传到第一层,告诉每个权重该往上调一点还是往下调一点。经过几百万次这样的小修正,权重就慢慢稳定在能给出正确答案的位置。没有人去写规则,规则是从数据里调出来的。

2003 年 2 月,Yoshua Bengio 和蒙特利尔大学的三位同事在《机器学习研究期刊》上发表了《神经概率语言模型》(A Neural Probabilistic Language Model)。他们的方案分三部分。给词表里的每个词配一串属于它自己的数字,在他们的实验里是 30、60 或 100 个。下一个词出现的概率,不再查表,而是用前面那几个词的数字算出来。数字本身,和用这些数字计算的方法,同时学出来,不需要任何人事先设定。

要猜"他喝"后面是什么,模型先查出"他"和"喝"各自的那串数字,把它们并排拼起来,送进一个神经网络。网络为词表里的每个词都算出一个概率:"酒"多少,"茶"多少,"桌子"多少。

训练时,它在一大堆文字上一遍又一遍地猜下一个词。每猜错一次,就调整两样东西:网络的权重,以及刚才用到的那几个词的数字。两样都往让正确答案更可能出现的方向推一点。

时间一长,出现在相似位置的词,就会有相似的数字。"他"和"她"后面常常跟着同样的词,说、去、喝,于是它们的数字慢慢靠在了一起。就算"她喝"从来没出现过,它的数字也和"他喝"很像,网络给出的答案也就差不多。论文自己举的例子是:见过一句关于猫在卧室里走动的话,就应该让一句关于狗在房间里奔跑的话显得差不多一样合理,因为猫和狗、卧室和房间、走和跑,在数字上都离得很近。

在他们测试的两个文本库上,这个模型都明显胜过了当时最好的 N 元模型。代价是速度。论文自己也指出,要在合理的时间内训练一个有几百万个参数的模型,本身就是一个严峻的挑战。这就是这个想法沉寂了十年的原因。

2013:word2vec

这个想法用了十年才流行起来。2013 年,Google 的研究者发布了 word2vec,一个可以在海量文字上快速训练的工具。它做的事很简单:让每个词去预测它周围会出现哪些词。训练完以后,每个词都变成了一个几百维空间里的点。词向量,是用一串数字表示一个词,意思相近的词,位置也相近。

让人吃惊的是,这个空间里的方向也有意义。拿"国王"的坐标,减去"男人",加上"女人",离得最近的点是"女王"。没有人教过它性别是什么。它只是在几十亿个词里发现,"国王"和"女王"之间的差别,很像"男人"和"女人"之间的差别。

但这里有一个限制:每个词只有一组坐标。英文的 bank 既是银行,也是河岸,在 word2vec 里它只能待在两者之间某个尴尬的位置。一个词的意思要看上下文,而词向量是没有上下文的。

要理解上下文,就得读完整句话。当时做这件事的主要工具是循环神经网络。循环神经网络(RNN),是从左到右一个词一个词地读、每读一个词就更新一次"记忆"的网络。

这个"记忆"不是一段文字,而是一串数字,通常有几百个。可以把它想成一块小白板,上面写着"读到目前为止,我对这句话的理解"。一开始,白板是空的,全是零。

拿"小猫睡在沙发上"这句话来说。网络读到"小猫"时,把两样东西放在一起算:白板上现在的内容(还是空的),和"小猫"的词向量。两样东西各自乘上一组权重,加在一起,再经过一个把数值压到固定范围里的函数,得到一块新的白板。旧白板被擦掉,换上新的。权重,是神经网络用来混合输入的系数;训练,就是不断调整这些系数的过程。

激活函数,是神经网络在每一次混合之后都要套上的一个简单函数。 循环网络里最常用的一个叫双曲正切(tanh),它会把任何数都压到 -1 和 1 之间:输入 0.5,得到 0.46;输入 3,得到 0.995;输入 100,还是不到 1。

为什么要压?代入数字看看。假设网络在读这样一句影评:"画面漂亮,表演出色,配乐动人,开头精彩,台词难忘,可惜中段无聊,节奏拖沓,结尾仓促,整体失望。"

为了简单,我们只看每个分句里那个评价的词。前五个是好话,每个给白板带来 +1;后四个是坏话,每个带来 -1。真正的白板上有几百个数,这里简化成只有一个。前面说过,每读一个词,新白板等于旧白板乘上一个权重,再加上新词带来的值。旧白板的权重,决定了过去的内容在新白板里占多大分量:小于 1,过去会一步步变淡;大于 1,过去会一步步被放大。

真实网络里的权重是学出来的,几百个权重里总会有一些大于 1。这里把它定成 2,就是为了看清楚这种情况下会发生什么。于是规则是:旧白板上的数乘以 2,再加上这个词的 +1 或 -1。白板一开始是 0。读到"漂亮",0 × 2 + 1 = 1;读到"出色",1 × 2 + 1 = 3;读到"动人",3 × 2 + 1 = 7。压过的那一列,是每一步算完以后再用双曲正切压一下:读到"漂亮",0 × 2 + 1 = 1,压完是 0.76;读到"出色",0.76 × 2 + 1 = 2.52,压完是 0.99。


读到的词

这个词带来

不压的白板

压过的白板

漂亮

+1

1

0.76

出色

+1

3

0.99

动人

+1

7

0.99

精彩

+1

15

0.99

难忘

+1

31

0.99

无聊

-1

61

0.76

拖沓

-1

121

0.47

仓促

-1

241

-0.05

失望

-1

481

-0.80


先看不压的那一列。五个好词把数字推到 31。从"无聊"开始,评价转成了负面,可每个坏词只减去 1,而白板每一步都要先翻一倍,数字照样往上涨。读到"失望",白板上是 481。网络还以为这是一句好评。再读下去,数字会大到计算机都存不下。

再看压过的那一列。前五个词把白板推到将近 1,然后就停在那里,涨不上去了。所以坏词一来,它很快就被拉了下来:读到"无聊"是 0.76,"拖沓"是 0.47,到"仓促"变成负数,读完"失望"已经是 -0.80。白板改变了主意。这就像录音棚里的限幅器:声音再大,也不让它超过上限,免得一声巨响把后面所有的声音都盖住。

回到"小猫睡在沙发上"。接着网络读"睡"。同样的做法:旧白板加上"睡",混合,压缩,得到新白板。然后是"在"、"沙发"、"上",一步一步来。读完最后一个词,白板上的内容就是网络对整句话的理解。要猜下一个词,它就从当前的白板算出每个词出现的概率。

最关键的一点,是每一步用的都是同一组权重。读第一个词和读第一百个词,遵循的是同样的规则,变的只是输入的白板和词。同一个小网络被一遍遍地循环使用,所以叫循环神经网络。也正因为这样,它可以读任意长度的句子。

训练它的办法,是让它在大量文字上猜下一个词。猜错了,就算出错得有多厉害,再把这个错误沿着时间往回传:最后一步该怎么调,前一步该怎么调,一直传回第一个词。因为每一步用的都是同一组权重,这些调整最后都加到同一组权重上。

麻烦就出在往回传的路上。错误每往回走一步,都要再乘一次权重。连乘几十次,一个数要么缩到接近零,要么大到失控。把 0.9 自乘五十次,只剩 0.005;把 1.1 自乘五十次,就变成了 117。实际情况通常是前一种。

梯度消失问题

梯度消失,是指错误信号在往回传的过程中越来越弱,很久以前的那些步骤几乎得不到任何调整。 结果是,网络很难学会"三十个词之前出现过的东西,现在很重要"。而且白板每一步都整块重写,早先写上去的内容会被一点点冲淡。比如"Joe 是个棒球运动员,吃完一顿丰盛的早餐后去了公园,打出了两个安打"。读到"安打"的时候,"棒球"在白板上已经模糊得快看不见了。这个问题在 1990 年代初就被人指出来了。

1997 年提出的 LSTM(长短期记忆网络),就是对它的回答。它在白板之外加了一条"传送带",专门用来长期保存信息。传送带上的内容不会每一步都被整块重写,而是由三道"门"控制。其中遗忘门是 2000 年前后才加上的,最初的版本只有两道。

遗忘门决定传送带上哪些旧内容该擦掉。比如读到一个新的主语,就把旧的主语擦掉。输入门决定当前这个词的哪些信息值得写上去。读到"棒球运动员",就写上"这段话和棒球有关";读到"丰盛的",可能什么都不写。输出门决定这一步从传送带上取出哪些内容来用。读到"安打",就取出"棒球"。

每道门本身也是一串 0 到 1 之间的数,0 是全关,1 是全开。门什么时候开、开多大,也是网络从数据里学出来的。没有人告诉它"主语"或者"棒球"是什么。

更重要的是,传送带上的更新,是在原有的基础上加加减减,而不是每一步都乘一遍再覆盖。只要遗忘门一直开着,一条信息就可以原封不动地在传送带上待很多步。错误信号往回传的时候,也可以沿着这条传送带走得很远而不消失。这就是 LSTM 能记得更久的原因。到 2010 年代中期,它已经是语音识别和机器翻译里使用最广的结构。

但不管是普通的循环网络还是 LSTM,都有一个去不掉的限制:必须读完"小猫",才能读"睡"。每一块新白板,都要等上一块算出来。

2014 年,研究者用两个这样的网络来做翻译。第一个读完原文,把整句话压缩成一串固定长度的数字;第二个从这串数字里,一个词一个词地写出译文。这叫"编码器-解码器"。那串数字的长度是固定的。不管原句是五个词还是五十个词,都得塞进同样大小的一个盒子里。句子越长,翻译丢的东西就越多。同一年,Dzmitry Bahdanau 和合作者想出了一个补丁,核心是注意力机制:让模型在每一步自己决定,输入里的哪些部分最重要。 比如翻译 bank 的时候,它会去看原句里有没有 river 或者 money。

注意力机制

具体是这样算的。解码器每要写一个词,就拿自己此刻的状态,和原句里的每一个词逐一比对,给每个词打一个分。这些分数再被换算成加起来等于 1 的比例,比如 river 占 0.7,sat 占 0.2,其余的词分掉剩下的 0.1。然后按这个比例,把原句里各个词的信息混在一起,交给解码器去写下一个词。写下一个词之前,再重新打一遍分。盒子还是那么大,但每一步都重新装,只装这一步用得上的东西。

Bahdanau 和合作者在 2014 年 9 月发布的论文《通过联合学习对齐和翻译来做神经机器翻译》(Neural Machine Translation by Jointly Learning to Align and Translate)里,有一张图,把这些比例画成了深浅不一的方格。

一边是一句英文,讲的是一份关于欧洲经济区的协议在 1992 年 8 月签署;另一边是模型写出的法文译文。深色的方格大多排成一条斜线,因为两种语言的语序大体一致:译文的第几个词,就对着原文的第几个词。

只有一个地方,斜线拐了弯。英文说 European Economic Area,两个形容词在前,名词在后;法文说 zone économique européenne,名词在前,形容词在后。模型写 zone 的时候,跳过了前面两个词,直接看向 Area;写 économique 时,往回看了一个词;写 européenne 时,再往回看一个。没有人告诉过它法语的形容词要放在名词后面。它是从大量对照译文里,自己学会了什么时候该看哪里。

对齐,是译文里的哪个词对应原文里的哪个词。 以前的统计翻译,要专门训练一个模型去弄清楚对齐。注意力把它变成了翻译本身的副产品。2016 年,Google 翻译把这套办法用进了产品。

在这之前,它用的是基于短语的统计翻译。这套办法先要找大量同一句话的两种语言版本。最常用的来源,是联合国、欧洲议会这类机构的会议记录,因为那里的每句话本来就要由专业译员翻成好几种语言。机器从几百万对这样的句子里统计出哪些词互相对应,再把经常一起出现的几个词切成短语,记下每个短语有过哪些译法、各自出现了多少次。比如中文的"开会",可能是 have a meeting,也可能是 hold a meeting。这样的短语表可以有几亿条。

翻译一句新的话时,系统把它切成几段,每段从表里挑一个译法,在小范围里调整语序,拼出成千上万个候选译文。挑哪一个,看两个分数:一个是短语表里的翻译概率,另一个是拼出来的句子像不像英文。第二个分数用的,正是前面讲过的 N 元模型:只看相邻的两三个词常不常一起出现。

每一段单独看都说得过去,但没有任何一步真正读懂了整句话。句子一长,拼接的痕迹就露出来了:主语和动词对不上,代词指错了人,语序还留着原文的影子。早年机器翻译那种每个词都对、连起来却不像人话的感觉,就是从这里来的。

2016 年 9 月,Google 宣布,网页版和手机版的中译英已经全部换成了新的神经网络系统,这个方向每天大约要翻译 1800 万次。新系统的编码器和解码器各有 8 层 LSTM,中间用注意力连起来。按 Google 自己的人工评测,在英法、英西、英中这几组语言上,翻译错误比旧系统平均减少了大约 60%。论文也承认了它的毛病:它仍然会漏词,会译错人名和罕见词,而且一次只翻一句,不管这句话在整段文章里是什么意思。

注意力仍然只是一个附件。底下的循环网络还是一个词一个词地读,第十个词必须等第九个词读完。放在硬件上,这是一种浪费。下一篇接着讲。🧪