Divya is standing on a crowded Bengaluru bus, one hand on the rail and the other holding her phone. Her manager Arun has emailed her under the subject "Thursday review" and asked whether she can share her notes beforehand. She taps Reply and types "Thursday works for me. I will s". Before her thumb reaches the next key, a few words of grey text have appeared after the cursor: "end the notes tonight." She hasn't finished the word she was typing, and the phone has already guessed the rest of the sentence. She accepts it with one gesture and moves on to the next line.
That small moment hides several problems. Her phone didn't wait for her to finish a sentence, so a fresh guess had to be produced after almost every letter, and a thumb on a bus types a letter every few hundred milliseconds. That guess depends on things she never typed, namely that the email is about a review on Thursday, that Arun asked for notes, and that she is the sort of person who writes "I will" and not "I'll". It also has to stay quiet most of the time, because a wrong suggestion on every keystroke would be worse than none. And it has to do all this over email written by more than a billion people, without any engineer reading what they wrote. Software that predicts the next few words of a half-typed sentence is a language model, and the finished feature is Gmail's Smart Compose.
So the question this chapter answers is: how does Gmail finish Divya's sentence in the gap between two keystrokes, using the email she is replying to, and keep quiet when it isn't sure?
We'll build it the way an engineer would, from a table of common phrases, and fix each failure in turn. That takes us through a language model that reads the subject and the previous email, the choice between three ways of feeding it that context, beam search for generating the words, a confidence threshold for deciding when to show them, a second small model that adapts to Divya's own style, and the serving work that squeezed all of it into a latency budget measured in tens of milliseconds. We rely on the team's own 2019 KDD paper and Google's own posts throughout, and we say plainly where the internals are unpublished.
01What we're building, and how big
1.1 What it has to do
Smart Compose has a narrower job than it first looks. Divya is writing the message herself, and the system's task is to extend the sentence she has begun by a few words, shown as a faint suggestion she can accept or ignore. It doesn't write the whole email, and it doesn't reply on her behalf. Google's earlier feature, Smart Reply, did the second of those, offering a few ready-made one-tap answers to an incoming message. Smart Compose is meant for the moment after Divya has decided to write something of her own, and the paper says so directly: Smart Reply's suggestions are "constrained to short phrases and appear only once in the composition process", where Smart Compose offers suggestions along the way.
From that job we can list what the system has to be. It has to be relevant to this email: the same typed words should lead to different suggestions depending on the subject, the message being answered, the time of day and the writer's locale (the paper's examples are "Good morning" against "Good evening", and the spelling "behaviour" for en-GB and "behavior" for en-US). It has to be fast, because the suggestion is useless if it arrives after Divya has already typed the next letter. It has to be quiet, showing a suggestion only when the system is confident, since an interruption on every keystroke would drive people to turn the feature off. It should be personal, matching how each person writes. It has to work across several languages. And it has to be private and fair: the paper says the system had to be built "without anyone on the project being able to look at the underlying data", and that the models must never expose a user's private information or reproduce the biases of the text they learned from.
1.2 How big is it?
Published numbers come from different years, so we'll date them. In 2016, the Smart Reply paper by Anjuli Kannan and colleagues said the earlier feature was responsible for "assisting with 10% of all mobile responses" in Inbox by Gmail and was built to process several hundred million messages a day. Google announced Smart Compose in May 2018, and the Google Research blog post of May 16, 2018, by Yonghui Wu described Gmail as having "more than 1.4 billion diverse users". By the time of the May 2019 paper, that figure had grown to more than 1.5 billion, and the authors quoted a third-party estimate of 281 billion emails sent per day across all providers. They report that the system saves users "over one billion characters of typing" each week. On June 3, 2019, Google's Workspace Updates blog announced that Smart Compose, which was already available to G Suite users, was expanding to Gmail on Android and iOS, so Divya's bus ride is a case the paper, written a few weeks earlier, only hints at.
Training data is plentiful too. After preprocessing, the paper's English data set held roughly 8 billion messages, split 80% for training and 20% for testing. Spanish, French, Italian and Portuguese were added later, with roughly 4, 2, 1 and 2 billion messages respectively.
Time supplies the numbers that matter most for the design. Chen et al. require that "the 90th percentile latency" be "under 60ms", and it cites a classic usability result that roughly 0.1 second is the limit for a system to feel instantaneous. Google's 2018 blog post puts the target as "ideally within 100ms". Both are measured against how fast people type, which brings us to a back-of-envelope estimate.
Divya types at roughly 40 words a minute, counting five characters per word including the space. About how many milliseconds pass between two of her keystrokes, on average? Then suppose, purely as an illustration, that 100 million people compose email on a given day and each sends 800 keystrokes to the server. How many requests per second is that on average, and how many CPU cores would you need if each request took 300 milliseconds of CPU time, as it did in the first CPU-only version?
Show the answer
Forty words a minute is 200 characters a minute, a little over three a second, so roughly 300 milliseconds between keystrokes on average. Typing comes in bursts, so the gaps are often shorter, and a suggestion that takes 300 ms is stale by the time it appears. That is why the team aims for tens of milliseconds, well inside one gap.
Our illustrative load is 100 million times 800, which is 80 billion requests a day, or roughly 925,000 a second on average (the real figure is unpublished). At 0.3 CPU-seconds each, that is roughly 277,000 cores busy all day just to answer them, before counting peaks. Google's blog post says the initial CPU serving averaged "hundreds of milliseconds" per request, and that moving most of the work to TPUs brought it down to "tens of milliseconds". Latency and cost both come out of the same arithmetic, and the whole design is shaped by it.
Several figures are not published, and we won't make them up: the real request volume, the size of the production model, how many machines serve it, and how often models are retrained. We'll flag each one as we reach it.
02Version 1: a table of common phrases
The obvious first design needs no machine learning. Take a large pile of sent emails, count how often each short run of words is followed by each next word, and store the counts in a lookup table. When Divya has typed "I will s", we look up the last couple of words, find the most common continuation, and show it. Chain a few lookups together and we can offer a whole phrase. A table of word-sequence counts used this way is an n-gram language model, where n is how many words the lookup is allowed to look at, and it's the traditional way to predict the next word. Chen et al. note why engineers liked it: the n-gram model "permits easy factorization in probability computation" and compress into compact finite state automata that are "amenable to large-scale distributed serving".
This design has real strengths, and we'll come back to one of them later. Each lookup is nearly free, the table is easy to inspect, and for stock phrases such as "Thank you for your" it's right most of the time. It breaks in ways that tell us what to fix.
It breaks first because it can only see the last few words. Table 6 of the paper shows what that costs. Take two emails whose subjects are "Thursday" and "Tuesday", where the previous message says "Thursday is great!" or "Tuesday is great!", and the writer has typed "I will work on T". A table that looks at "will work on T" has no way to know which day to finish with, because the answer lives in a different message. Their model suggests "hursday" in the first case and "uesday" in the second. Time of day, the locale and the subject carry the same kind of information, and none of them are in the last three words.
Size is the second break. With a vocabulary of 50,000 words there are 50,000 cubed, roughly 125 trillion, possible three-word sequences, nearly all of which will never appear in any training set. A longer window sees more context but meets sequences it has never seen, so n-gram systems add rules for backing off to shorter histories. We'll meet that machinery again in section 07. Third, everyone gets the same table, so Divya's habit of writing "I will" instead of "I'll" never shows up.
There's a nearby design that avoids the sparsity problem, and it's the one Gmail had already shipped. Smart Reply reads the whole incoming message with an LSTM (a recurrent neural network that reads one word at a time and keeps a running summary) and picks from a fixed list of short replies written ahead of time. To avoid scoring every reply on the list, it stores them in a trie, a tree in which each path from the root spells out one reply, and runs a left-to-right beam search that keeps only hypotheses that stay inside the trie. Its authors report that this costs time proportional to the beam width times the reply length, with both typically between 10 and 30, and not to the size of the reply list. With a beam of 128 the top result matched exhaustive scoring 99% of the time.
That list is exactly what Smart Compose can't have. Smart Reply's authors found that in a sample of 10 million short responses, more than 40% occurred only once, so a fixed list of full sentences can't cover what people write. Our suggestion also has to extend a half-typed sentence from the middle, after almost every keystroke, with no list to look up. Chen et al. say this plainly: Smart Reply "only needs to generate responses once for each mail, whereas Smart Compose attempts to suggest possible extensions for every sentence prefix a user has typed in real time". Smart Compose has to generate words, one after another, from a model of language.
| Where the suggestion comes from | Plus | Minus |
|---|---|---|
| Fixed list of replies (Smart Reply, 2015-16) | Every suggestion is vetted ahead of time, search cost doesn't grow with the list, easy to keep diverse | Closed set that can't cover open writing, one set of suggestions per email, no completion of a half-typed sentence |
| N-gram phrase table | Nearly free to look up, compact, easy to inspect and retrain | Sees only a few words, huge and sparse for longer windows, blind to the subject and the previous email |
| Neural language model with context | Reads any context, generalises to word sequences it has never seen, generates open-ended text | Heavy to run on every keystroke, needs careful serving, can memorise and reflect bias |
Google chose the third for the main model, and it kept the second for a smaller job later, as the personal model of section 07. Our work now is to make the third affordable. We start with what a language model is and how context goes into it.
03A language model that reads the context
A table fails because it can only count what it has seen. Instead we want a function that takes everything relevant to Divya's sentence and returns, for every word in the vocabulary, the probability that it comes next. That function is a language model, and we can write down exactly what it computes. Say the email body so far is the words and everything else we know about the situation is a bundle that we'll call the context: the subject, the previous email, the date and time, the locale. That model gives a distribution over the next word, . Multiplying these one-step probabilities gives the probability of a whole phrase, which is the chain rule of probability:
Here the prefix is what Divya has typed, is the suggestion we're proposing, and is the part of the suggestion before word . That product is how we'll score candidate phrases in section 05. Their training objective is "to maximize the log probability of producing the correct target sequence given the input for all data samples in the training corpus". That is the same as minimising the average negative log probability the model gives to the word that was written. Every position in every training email supplies one example, because for each position we know the right answer. Nobody has to label anything by hand.
Model quality is reported as log perplexity, the average of over the test positions. (The paper writes it in an entropy-style formula, and doesn't state the base of the logarithm.) Lower is better, because a lower value means the model gave more probability to what people wrote. If we read the logarithm as natural, a log perplexity of 3.26 is a perplexity of , as if the model were choosing among roughly 26 equally likely words at each position, out of a vocabulary of 50,000.
3.1 What goes into the training data
The training data is email that people wrote themselves. Chen et al. list the context fields they attach to each message: the previous email if this one is a reply, the subject, the date and time (used as discrete features, so the model can learn "Good morning" and "Happy Thanksgiving"), and the writer's locale. Then it applies the same preprocessing as Smart Reply. Messages are checked for language and those in other languages are discarded, sentences are split into words and punctuation, and "infrequent words and entities like personal names, URLs, e-mail addresses, phone numbers etc. are replaced by special tokens". Quoted original messages and forwarded messages are removed, and so are salutations and closings such as "Hi John" and "Best regards, Mary".
The steps come without an explanation of each one, so what follows is our reading of what they protect against. Replacing names and numbers with placeholders keeps the model from learning, and later repeating, any particular person's details. Dropping quoted text keeps it from training on other people's words as if the sender had written them. Stripping salutations removes the most predictable lines in every email. Left in, they would take up a large share of the training signal for no benefit to the later sentences. After this the English data set has roughly 8 billion messages and a vocabulary of the 50,000 most frequent words, with a word-level model.
3.2 Where the compute goes
The vocabulary size matters more than it looks, and we can see why by counting. Its baseline is an LSTM with two layers of 1,024 units, a 256-number embedding for each word, and a 50,000-word output layer. For the version with context, the input to the first layer is 768 numbers: the 256-number embedding of the current word plus two averaged 256-number context vectors that we'll meet in the next section. An LSTM layer holds four weight matrices (three gates and a candidate), each taking the layer's input plus its previous 1,024 outputs, so the first layer has million weights and the second has million. Word embeddings take million. Then the output layer, which turns 1,024 numbers into one score per word, takes million.
Those add up to roughly 79.7 million, and Table 1 of the paper lists 79.8 million parameters for exactly this model, so the accounting is right. It also shows that the output layer is nearly two thirds of the model, and that for every word we generate, the arithmetic of one step is roughly 67 million multiply-adds, of which the output layer is more than three quarters. Recurrent layers, the part that reads the sentence, are the smaller cost. That's why section 08 treats the size of the vocabulary as a serving decision.
3.3 Does the context help?
Before building the real thing, we can check on a miniature that reading the context does what we want. This program generates a toy mailbox. Some emails are about a day of the week and reply with "i can do thursday . i will send the notes on thursday ." (or Monday, Tuesday, Friday), and the rest are about food and reply "yes i love some tea . see you at tea ." (or coffee, lunch, dinner). Each email's context is the subject word plus a few words of the previous message, averaged into one vector, the same trick the paper uses. Our model has two parts: a table that scores the next word from the previous word alone, and a second table that adds a score from the averaged context. We train it with softmax cross-entropy and compare it with the same model without the context table.
Try it Does reading the context lower the loss? A miniature LM-A
import numpy as np
rng = np.random.default_rng(3)
days = ["monday", "tuesday", "thursday", "friday"]
foods = ["tea", "coffee", "lunch", "dinner"]
vocab = ["<s>", "yes", "i", "can", "do", "will", "send", "the", "notes",
"on", "works", "for", "me", ".", "love", "some", "at", "see",
"you"] + days + foods
ix = {w: i for i, w in enumerate(vocab)}
V = len(vocab)
def email():
if rng.random() < 0.5:
d = rng.choice(days)
body = ["i", "can", "do", d, ".", "i", "will", "send", "the",
"notes", "on", d, "."]
ctx = [d, "can", "we", "meet"]
else:
f = rng.choice(foods)
body = ["yes", "i", "love", "some", f, ".", "see", "you", "at",
f, "."]
ctx = [f, "do", "you", "want"]
return ctx, ["<s>"] + body
def encode(n):
X, C, Y = [], [], []
for _ in range(n):
ctx, body = email()
c = np.zeros(V)
for w in ctx:
if w in ix: c[ix[w]] += 1 / len(ctx) # averaged bag
for a, b in zip(body[:-1], body[1:]):
X.append(ix[a]); C.append(c); Y.append(ix[b])
return np.array(X), np.array(C), np.array(Y)
def fit(X, C, Y, use_ctx, steps=1500, lr=3.0):
Wp = np.zeros((V, V)); Wc = np.zeros((V, V))
for _ in range(steps):
z = Wp[X] + (C @ Wc if use_ctx else 0)
p = np.exp(z - z.max(1, keepdims=True))
p /= p.sum(1, keepdims=True)
g = p.copy(); g[np.arange(len(Y)), Y] -= 1; g /= len(Y)
np.add.at(Wp, X, -lr * g)
if use_ctx: Wc -= lr * (C.T @ g)
return Wp, Wc
def nll(m, X, C, Y, use_ctx):
Wp, Wc = m
z = Wp[X] + (C @ Wc if use_ctx else 0)
z = z - z.max(1, keepdims=True)
lp = z - np.log(np.exp(z).sum(1, keepdims=True))
return -lp[np.arange(len(Y)), Y]
Xtr, Ctr, Ytr = encode(3000)
Xte, Cte, Yte = encode(1000)
hard = np.isin(Yte, [ix[w] for w in days + foods]) & (Xte != ix["<s>"])
for use in (False, True):
m = fit(Xtr, Ctr, Ytr, use)
l = nll(m, Xte, Cte, Yte, use)
name = "with context" if use else "no context "
print(f"{name}: log-perplexity {l.mean():.3f}, "
f"on the day/food words {l[hard].mean():.3f}")
c = np.zeros(V)
for w in ["thursday", "can"]: # "we", "meet" are not in vocab
c[ix[w]] += 0.25
z = m[0][ix["on"]] + (c @ m[1] if use else 0)
p = np.exp(z - z.max()); p /= p.sum()
print(f" P('thursday' | 'notes on', subject Thursday) = "
f"{p[ix['thursday']]:.2f}")
1.407 and the model puts only 0.25 on “thursday” after “notes on”. With the averaged context vector the loss on those words falls to 0.180 and the probability of “thursday” rises to 0.83. Overall log-perplexity drops from 0.493 to 0.101.Context lowers the average log perplexity from 0.49 to 0.10, but the interesting number is the second one. On the day and food words, the positions where the answer lives in the context and nowhere else, the loss falls from 1.41 to 0.18. Each block's last line shows what that means for Divya's case: after "notes on", with the subject mentioning Thursday, the model with context puts 83% on "thursday", and the model without it spreads the probability across the four days and gives roughly 25%. The real result in the paper has the same shape, on a different scale. Adding the subject and previous email to an LSTM-2-1024 cut test log perplexity from 3.39 to 3.26, a drop of 0.13, and the gain is concentrated at the positions where context decides the word.
This arrangement shows up wherever text is generated under a condition: image captioning feeds a picture vector into every step of a language model, and a chat model reads its system prompt and the conversation before continuing it. A chat model is the extreme version of what we're about to build, with the context supplied as ordinary tokens in front of the text to be continued.
04Three ways to feed the model its context
We know the model needs the subject and the previous email. What we haven't decided is how they enter. A subject is a few words, but a previous email can run to hundreds, and every choice we make about reading it gets paid for on every keystroke. Chen et al. compare three architectures and train each at several sizes, on English data with 32 NVIDIA P100 GPUs for each experiment.
In the first, LM-A, the language model reads only Divya's body text, one word per step. Each context field has a dedicated context encoder, and its output is joined to the word embedding at every step. That encoder is kept deliberately plain: "the averaged token embeddings as our context encoding for each field". Averaging means that each field becomes one fixed-length vector, the mean of its words' embeddings, no matter how long the field is.
In the second, LM-B, there is no context encoder. We pack the subject, the previous email body and the current body into one long sequence with special separator tokens, and the language model reads the lot as ordinary text. This is simpler in structure, and, as the paper says, it "leads to much longer sequence length". A third design, a sequence-to-sequence model (seq2seq), works like the translation systems of that era. An encoder reads the subject and previous email, and a decoder, attending back over the encoder's states, writes the current body.
Here is how the three compare on test log perplexity at similar sizes, using Tables 1, 3 and 4 of the paper.
| Architecture | Model | Parameters | Test log perplexity |
|---|---|---|---|
| No context (baseline) | LSTM-2-1024 | 77.7M | 3.39 |
| LM-A | LSTM-2-1024 | 79.8M | 3.26 |
| LM-A | Transformer-768-2048 | 84.3M | 3.08 |
| LM-A | Transformer-1536-8192 | 310.2M | 2.90 |
| LM-B | LSTM-2-1024 | 77.7M | 3.26 |
| LM-B | Transformer-2048-8192 | 507.0M | 2.86 |
| Seq2seq | LSTM-2-1024 | 179.7M | 3.09 |
| Seq2seq | Transformer Big (1024-8192) | 430.7M | 2.96 |
Three things stand out. LM-A and LM-B reach almost the same quality at the same model type and size, so the simple averaged context is no worse than reading the context as text. Seq2seq with LSTMs is clearly better than LM-A with LSTMs (3.09 against 3.26), and the authors read that as a sign that "an encoder-decoder architecture with attention is more effective in modeling the context information". And Transformers beat LSTMs of similar size: the 84-million-parameter Transformer is 0.18 below the 80-million-parameter LSTM.
On quality alone, the answer would be a big Transformer, in LM-B or seq2seq form. Google ends up elsewhere, and the 2018 blog post says why in a sentence about seq2seq: it "failed to meet our strict latency constraints by orders of magnitude." Section 09 puts numbers on the latency side. For now what matters is how the choice was framed. Per the paper, "due to the strict production latency constraint and very high request volume, we conclude that LM-A is the most production-appropriate model." The blog describes the final model as a hybrid in which the word embeddings of the subject and previous email are averaged, as in a bag-of-words model, and then fed into an RNN language model at every decoding step. That hybrid is "faster than the seq2seq models with only a slight sacrifice to model prediction quality". The size of the production model isn't given.
| Option | Plus | Minus |
|---|---|---|
| Seq2seq encoder-decoder | Best use of the previous email, good perplexity even with LSTMs | Two networks and attention to run per request, missed the latency target by orders of magnitude (2018 blog) |
| LM-B, one packed sequence | Simplest model, any architecture works unchanged | Much longer sequences, so more computation per request, with no quality gain over LM-A |
| LM-A, averaged context embeddings | Context encoded once and reused each step, cheap, matches LM-B quality | Averaging discards word order inside the subject and previous email |
So Google picked LM-A, and it paid for the choice in a small amount of context understanding. Examples in the paper show what survives the averaging. In Table 6, a reply "Look f" under the subject "Meet" gets "orward to seeing you", and "Y" in answer to "Do you want tea?" gets "es please". It says the model captures context well "despite the simplistic approach of using averaged embeddings to encode each field".
Why average the context instead of reading it with a proper encoder?
Because the cost is paid on every keystroke and the benefit is small. Averaging is one lookup per word, done once per request. It can't tell "Arun asked Divya to send notes" from "Divya asked Arun to send notes", but it does retain which words are present, and in short business email the presence of "Thursday", "notes" and "review" carries most of what a suggestion needs. A Transformer encoder over a long previous email is the kind of cost the paper's future-work section says it would like to afford "at minimum latency cost", and doesn't claim to have.
Where else this shows up: a retrieval-augmented language model packs retrieved documents into the prompt, as LM-B does with a longer prefix, and a speech recogniser can feed the user's contact names into its language model as context, as LM-A does with a bag of names. That tradeoff between reading context as tokens and encoding it into a vector is one that every conditioned language model makes.
05Turning probabilities into a phrase: beam search
The language model gives Divya's phone one thing, the probability of each next word. A suggestion is several words long, so we have to chain those probabilities into a phrase and choose which phrase to show. One simple method is greedy decoding: take the single most likely next word, append it, ask again, and repeat. It costs one model step per word, as cheap as generation gets. It also fails in a predictable way. A word that looks best on its own can lead to a dead end. Suppose, as a constructed case, that the first word is "A" with probability 0.5 or "B" with 0.4, but after "A" the best continuation has probability only 0.3, and after "B" it is 0.95. Greedy takes "A" and ends with a phrase of probability 0.5 × 0.3 = 0.15, while "B" would have given 0.4 × 0.95 = 0.38.
We fix this by keeping several partial phrases alive at once and letting the later steps decide. Chen et al. use beam search and describe the procedure in a few sentences. We maintain a heap of the best candidate sequences. At each step, every candidate is extended by each of its most likely next tokens, the new sequences go into the heap, and the heap is pruned back to the best . A candidate is complete when it generates a sentence-ending punctuation token or the special end-of-sequence token, or reaches a maximum length. Completed candidates are added to the set of suggestions, and the search ends "when no new candidate sequences are added". Values of , and the maximum length aren't published, though the evaluation covers suggestions of up to 15 words.
In the figure, Divya's prefix ends in the middle of a word, "s". To handle this, the paper restricts the first step of the search: "if the prefix ends mid-word, the first step of beam search starts constrained by only feasible completions of the prefix". Since the model has a word-level vocabulary, the feasible completions are the words that start with "s", such as "send", "see" and "start". It never has to spell anything letter by letter. That keeps the vocabulary at 50,000 words and the step count at one per word. That same hook lets the application drop tokens "that are offensive or otherwise undesirable for product reasons" while the search runs, and it lets the application decide which tokens end a candidate, for instance a period, if the product shouldn't suggest beyond the end of a sentence.
Each row of the figure is scored by the product of its word probabilities, or equivalently by the sum of their logarithms. Take the row "send the notes .". Its probabilities are 0.55, 0.70, 0.60 and 0.90, and they multiply to roughly 0.21. Row two, "see you there .", gets 0.20, 0.60, 0.40 and 0.85, roughly 0.04. Comparison between candidates uses a refinement of that score, the subject of the next section.
| Decoding method | Plus | Minus |
|---|---|---|
| Greedy | One model step per word, the cheapest possible | Commits to the best first word and can't recover from it |
| Beam search | Finds high-probability phrases, returns several candidates with scores | Costs about model steps per word generated; still approximate |
| Random sampling | Varied suggestions, no search machinery | The same prefix can give different phrases, and a single draw gives a weak confidence score |
| Beam over a fixed list (Smart Reply) | Only vetted replies are ever produced | Needs a closed list, which open completion doesn't have |
Google chose beam search for Smart Compose. A comparison against greedy decoding isn't reported, so we don't know how much it gained; what the text does say is that the candidates' scores serve a second purpose, ordering the heap during the search and deciding whether to show anything at all. A method that returns several scored phrases suits that job, and a method that returns one phrase doesn't.
Nearly every system that generates sequences uses a search like this one. Machine translation systems decode with a beam, speech recognisers keep a beam of word hypotheses, and large language models offer it as an alternative to sampling. Cost is the thing to watch here: beam search multiplies the work per generated word by the beam width, and the serving section spends much of its effort on that.
06Knowing when to stay quiet
Beam search always returns something. After almost any prefix it will finish with a phrase, and most of those phrases would be wrong. If Divya sees a wrong guess after every other letter, she learns to ignore the grey text, or turns it off. A suggestion is good only if it's right often enough to be worth the glance. So the question after generating a phrase is whether to show it, and the system has to be allowed to say nothing.
Smart Reply had solved the same problem with a separate model: a feedforward network that looked at an incoming message and predicted whether the user would reply to it at all, so the LSTM ran only on messages that were likely to be answered. Smart Compose does it without a second model. Instead, the score that ranks candidates inside the beam also serves as the confidence. It is defined as "a length-normalized log conditional probability":
Here is the number of words in the suggestion and the rest is the chain-rule product of section 03, in log form. Dividing by gives the average log probability per word. Without it, every extra word multiplies in another number below one, so long phrases would always score worse than short ones and the system would almost never show a long suggestion. A suggestion is shown only if its score is above a triggering threshold , and only the single best candidate is ever shown.
Nobody tunes the threshold by feel. Per the paper, it is set "based on a target triggering frequency/coverage". Coverage is the fraction of moments at which the system shows a suggestion, and it plays the role that recall plays in a classifier. If we want the system to show something on 20% of keystrokes, we collect scores from a held-out stream of typing and choose as the value that 20% of them exceed. Everything else about the system then follows from coverage and from how often the shown suggestions turn out right. This is a precision-first design: the product owners choose how much to show, and the model has to make what it shows count.
Suppose a model's top suggestion exactly matches what the writer would have typed 41% of the time when we show every suggestion. If we keep only the 20% of suggestions the model is most confident about, what share of those do you expect to be exactly right: about 41%, about 60%, or above 80%? And if the model's confidence score is noisy, so it can't tell its good guesses from its bad ones, what happens to that number?
Show the answer
With a trustworthy confidence score the answer is above 80%, and the experiment below gets 80.8% on its synthetic data. With a noisy score it rises only to about 53%. All of the gain from staying quiet comes from the model's ability to know when it knows, so the quality of the confidence score matters as much as the quality of the model's guesses.
We can check this on synthetic data. This program builds 400,000 imaginary suggestions of up to 15 words. At each word the model's chosen word is right with probability , which makes the model calibrated by construction, and the whole suggestion counts as an exact match only if every word is right. Confidence is the length-normalised log probability from the equation above. We sort the suggestions by confidence and report the exact-match rate among the top 100%, 50%, 20%, 10% and 5%. Then we repeat with noise added to the confidence, standing in for a model that is worse at judging its own guesses, and with a score that uses only the first word.
Try it Trade coverage for accuracy with a length-normalised confidence score
import numpy as np
rng = np.random.default_rng(7)
N = 400_000
L = np.minimum(rng.geometric(0.28, N), 15) # words per suggestion
# probability the model's chosen word is right at each step (calibrated)
p = rng.beta(2.5, 1.0, (N, 15))
live = np.arange(15)[None, :] < L[:, None]
right = rng.random((N, 15)) < p
exact = np.all(right | ~live, axis=1) # whole phrase matches
mean_lp = (np.log(p) * live).sum(1) / L # length-normalised
def sweep(conf, label):
order = np.argsort(-conf)
print(label)
for cov in (1.0, 0.5, 0.2, 0.1, 0.05):
keep = order[: int(cov * N)]
print(f" show {cov:>4.0%}: exact match {exact[keep].mean():6.1%}"
f" avg words {L[keep].mean():.1f}")
sweep(mean_lp, "confidence = length-normalised log-prob (calibrated)")
noisy = mean_lp + rng.normal(0, 0.5, N)
sweep(noisy, "confidence = same score plus noise (a worse model)")
sweep(np.log(p[:, 0]), "confidence = first word only")
41.2% exact match. With the calibrated score, keeping the top 20% gives 80.8% and the top 5% gives 95.9%. With a noisy score the same cut gives 52.9% and 58.0%, and a first-word-only score reaches 55.4% and 57.3%. Average suggestion length falls from 3.5 to 1.3 words as the threshold tightens.A calibrated score turns a 41% exact-match system into one that is right 81% of the time when it speaks on one keystroke in five, and 96% of the time on the most confident twentieth. A noisy version, with identical guesses, tops out at 58%. In the last block, looking only at the first word is nearly as poor as noise, because a suggestion's quality depends on every word in it. One more detail in the output is easy to miss. Average length of shown suggestions falls from 3.5 words to 1.3 as the threshold tightens, because a short phrase has fewer chances to include a weak word and so its average log probability is more extreme. That behaviour comes from the simulation, and the paper doesn't report the average length of shown suggestions. It's a reminder that a threshold shapes what gets shown as well as how much.
Real numbers from the paper point the same way. In Table 2, the model's exact-match rate for one-word suggestions is roughly 85%, and it falls to between 32% and 44% for five-word suggestions, so longer phrases are right less often and more of them get filtered out by the threshold. In the multilingual setting, the paper sets "language-specific triggering confidence threshold" values so that every language has coverage similar to English, since the same threshold applied to a model with different calibration would show a different amount.
Why show only one suggestion?
Chen et al. state the practice, "we provide only the top suggestion to users", and don't give a reason. One obvious reason is the interface: a line of grey text after the cursor has room for one phrase, and offering several would ask Divya to choose while she's typing. A second reason follows from the design itself. Showing one suggestion makes coverage easy to define and to control, and every extra option would be another chance to be wrong in front of her.
Selective prediction, answering only when confident, appears across applied machine learning. A fraud model alerts on the transactions above a score cutoff, a spam filter sets a threshold that trades missed spam against lost mail, and a medical triage model can be tuned to speak up only on cases it's sure about. In each, the threshold is a product decision made with a precision and coverage curve in hand, as in the figure above.
07Writing like Divya: a personal model
The model so far is trained on billions of messages and gives everyone the same answer for the same words and context. Divya's manager might write "I will send over the deck" and she writes "I'll shoot over the notes". Table 8 of the paper shows the effect on a test account. On that account the user has typed "Will this work for sm", and the global model suggests "all group?", a perfectly ordinary completion, while the user's own word is "artcompose". A model trained on everyone can't know a person's project names, her sign-offs or her habit of ending questions with a question mark.
An obvious fix is a model trained on Divya's own mail, and the obvious version is to fine-tune a copy of the neural network for each user. That would mean storing and serving a model of roughly a hundred million parameters for each of more than a billion accounts. Its authors state what the personal model has to be instead: "small, adaptive, easy for serving and periodical re-training". Google's choice is the one we dismissed in section 02. For each user they train "a light-weight language model", an n-gram model with Katz backoff on that user's own Sent folder. Per the paper, the personal data is "his or her 'Sent' e-mails in the past a few months", with a vocabulary extracted by frequency, a minimum occurrence threshold and a maximum size.
7.1 What a Katz n-gram model does
An n-gram model estimates the next word from counts. For a three-word history it looks at how often that history was followed by each word, and uses the ratio. When the history was never seen, the ratio has nothing to work with, so Katz backoff steps down to a shorter history and tries again. For a word after a history , with the history shortened by one word:
Here is a count in Divya's mail and is a discount that shaves a little probability off every seen event. That freed mass is what hands to the unseen words, in proportion to what the shorter history predicts. (We write the backoff weight as to keep free for the blend below.) A model like this needs little data to reach reasonable quality, and that is the paper's reason for choosing it over a neural alternative. It's compact when stored as a weighted finite automaton, a graph whose paths are word sequences carrying probabilities. Words that appear in neither vocabulary are assigned "a tiny probability to ensure that the probability of all possible words sum up to one".
7.2 Blending the two
A personal n-gram model on a few months of mail is weak at ordinary English and strong on quirks. A global model is the reverse. We want both, and the paper mixes their distributions "at each time step of the beam search procedure" by linear interpolation:
Both terms are probabilities over the same words and each sums to one, so the mixture does as well. Here the weight says how much to trust the personal model: zero is the global model alone and one is Divya's model alone. Note which model reads the context. On the global side, the term takes the subject and previous email, while an n-gram model has no slot for them, so the personal term depends only on the preceding words. Blending happens inside the beam, so a word Divya likes can enter the beam at the first step and then be extended by the global model, instead of being compared with finished global suggestions at the end.
Chen et al. keep the weight as simple as they can: "we keep the model as simple as possible and make use of a constant interpolation weight". It admits that an ideal system would estimate a different weight for each context with its own model, and it declines to pay that overhead. That constant is found offline and then checked in an online experiment.
The paper evaluates the blend at 11 different values of the weight, from 0 (global only) to 1 (personal only), keeping coverage about the same each time. Where do you expect the exact-match rate to peak: near 0, near 0.4, or near 1?
Show the answer
It rises as the weight increases, peaks at 0.4, and then drops. That's the paper's own wording in its description of Figure 4. A weight of 0 can't capture personal style, and a weight of 1 means a small n-gram model working alone, and, as the authors put it, "is not as powerful as the global neural language model in making generic predictions". After launch the team observed "around 6% relative gain in the Click-Through-Rate (CTR) of suggestions and 10% relative gain in ExactMatch".
Why should there be an interior peak at all? We can reproduce it in a toy world. This program gives every simulated user a strong shared model of next words in 30 contexts, plus six personal favourite words that they use in every context. Our personal model is deliberately weak: only counts of the user's own words, with no context at all. We sweep the blend weight and measure average log-likelihood on held-out text and the top-1 hit rate, for users with 30, 300 and 3,000 tokens of personal history.
Try it Blend a weak personal model with a strong global one and sweep the weight
import numpy as np
rng = np.random.default_rng(11)
V, C, USERS = 60, 30, 300 # words, contexts, simulated users
glob = rng.dirichlet(np.full(V, 0.15), C) # shared model p(w | c)
alphas = np.linspace(0, 1, 11)
def run(n_sent):
ll = np.zeros(len(alphas)); acc = np.zeros(len(alphas))
for _ in range(USERS):
fav = rng.choice(V, 6, replace=False)
quirk = np.zeros(V); quirk[fav] = rng.dirichlet(np.ones(6))
true = 0.65 * glob + 0.35 * quirk[None, :] # user's real habits
cnt = np.zeros(V) # personal model: counts only,
for c in rng.integers(0, C, n_sent): # no context
cnt[rng.choice(V, p=true[c])] += 1
pers = 0.999 * cnt / n_sent + 0.001 / V
tc = rng.integers(0, C, 400) # held-out tokens
tw = np.array([rng.choice(V, p=true[c]) for c in tc])
for k, a in enumerate(alphas):
mix = a * pers[None, :] + (1 - a) * glob
ll[k] += np.log(mix[tc, tw]).mean()
acc[k] += (mix[tc].argmax(1) == tw).mean()
return ll / USERS, acc / USERS
print("personal tokens | log-lik: a=0, best, a=1 | top-1: a=0, best, a=1")
for n in (30, 300, 3000):
ll, acc = run(n)
print(f"{n:>9} | {ll[0]:6.2f} {ll.max():6.2f} {ll[-1]:6.2f}"
f" | {acc[0]:.3f} {acc.max():.3f} {acc[-1]:.3f}"
f" best alpha {alphas[acc.argmax()]:.1f}")
-6.42 log-likelihood against -4.90 for the global model, and the best blend reaches -3.14. With 3,000 tokens the personal model alone gets -3.61, and the best blend is still ahead at -2.97. Top-1 rises from 0.149 to 0.179 at a weight of 0.6, and the weight of 1 is worse than the best blend in every row.In every row, the best blend beats both extremes. With 30 tokens of history, the personal model alone is a disaster (log-likelihood −6.42, far worse than the −4.90 of the global model) but a blend still lifts the score to −3.14, because even a small sample finds the pet words. With 3,000 tokens the personal model alone is much better (−3.61), yet the best mixture is still clearly ahead of it at −2.97, and the top-1 rate climbs from 0.149 to 0.179. In this toy the best weight doesn't move much between users, the situation a constant weight is designed for. Chen et al.'s own result, a peak at 0.4, is a statement about their data and not a constant of nature.
| Personalisation option | Plus | Minus |
|---|---|---|
| Global model only | Nothing per user to store or retrain, simplest to serve | Same suggestion for everyone; misses names, jargon and style (Table 8) |
| Fine-tune the neural model per user | Could adapt in context, not only in word choice | A large model per account, heavy to retrain and serve, needs far more data per user |
| Per-user n-gram blended with the global model | Small, trains on modest data, mixes at every beam step, cheap to serve | Sees only a few preceding words, no context, one fixed weight for everyone |
| Train on the device (federated learning) | Personal text never leaves the phone | Models must be tiny, and training needs idle charging devices |
Google chose the third. Google's 2018 blog post still described personal language models as something the team was "working on incorporating", and the May 2019 paper reports that it launched, with the gains above. Row four is a comparison, not something Smart Compose is documented to use. In the Gboard keyboard work by Andrew Hard and colleagues (2018), a recurrent language model with 1.4 million parameters, shipped as a 1.4-megabyte file, was trained across phones with federated averaging. It reached top-1 next-word recall of 16.4%, against 16.5% for the same model trained on the server, and 13.0% for the n-gram system it replaced. Their latency expectation is stricter than Gmail's: "Users typically expect a visible keyboard response within 20 milliseconds of an input event". Nothing in the Smart Compose paper says where Divya's personal model is trained or stored, so we don't know whether anything of hers runs on the phone.
Why not fine-tune the neural network for each person?
Section 03's numbers make the case. An 80-million-parameter model, mostly a vocabulary-sized output layer, would take roughly 300 megabytes at 32-bit precision, and storing one per account would multiply that by more than a billion accounts, with each copy needing retraining as Divya's habits changed. An n-gram model in compact automaton form needs far less data and far less space, can be rebuilt from a few months of sent mail on a schedule, and mixes into the beam with a single multiply-add per candidate word. Its price is that it can't understand context, and that's why it's a partner to the global model and not a replacement.
Mixing a small adapted model into a large general one at each step of decoding is an old idea in speech recognition, where a recogniser's language model is adapted to a speaker's vocabulary this way. Related work in the paper points to an earlier study that is "also a linear interpolation between an n-gram and recurrent neural network language model". Keyboards, search boxes and code editors with personal dictionaries and recently used names all do the same, in different clothes.
08Other languages, and the cost of a big vocabulary
Divya writes in English, but Gmail's users don't. Next the paper extends Smart Compose to Spanish, French, Italian and Portuguese, and the obvious design is one word-level model per language, each trained exactly as the English one was. That fails on cost. Section 03 showed that the output layer of a 50,000-word model is nearly two thirds of its parameters, and a language with many word forms needs a larger word vocabulary to avoid constant unknown words. Its verdict is that word-level multilingual models "require a large vocabulary size to account for rare words in each language", and that "would make the models prohibitively slow to serve within systems with strict latency requirements".
Its remedy, inspired by Johnson et al.'s multilingual translation system, is wordpieces. Instead of one vocabulary entry per word, a fixed list of frequent word fragments is learned from the data, and a rare word is spelled out as a sequence of fragments. A word such as "unfriendly" might become three pieces (this split is only an illustration), and a very rare word falls back on shorter ones. Vocabulary stays at 50,000 entries however many languages share it, and the unknown-word rate stays low, because any word can be built from pieces. With wordpieces, a single model can serve all four languages, and languages with little data can borrow strength from similar languages with more.
For each language, the paper compares three variants, all using the LM-A architecture with an LSTM of two 1,024-unit layers:
| Language (messages) | Monolingual word | Monolingual wordpiece | Multilingual wordpiece |
|---|---|---|---|
| Spanish (4 billion) | 75.90% | 72.59% | 71.73% |
| French (2 billion) | 70.75% | 69.54% | 69.64% |
| Italian (1 billion) | 70.50% | 67.44% | 67.48% |
| Portuguese (2 billion) | 69.04% | 72.20% | 72.65% |
The numbers are ExactMatch from Table 9. For Spanish, French and Italian, the monolingual word model wins and the shared model gives up between about 1 and 4 points. Spanish, the largest of the four, loses the most, and the authors take that as a sign that a large language's quality is impaired the most by sharing a model. Portuguese goes the other way: the multilingual model beats both monolingual ones by 3.6 points over its word model, in line with the idea that it benefits from the closely related Spanish, French and Italian data. A caution applies to the perplexity column that sits beside these in the paper. Per-token perplexities for word models and wordpiece models measure different units, because a wordpiece model predicts fragments, so the two columns aren't strictly comparable, and ExactMatch on whole words is the cleaner comparison.
Google's decision was explicit: "based on an overall consideration of both quality and maintenance requirements, we deployed a multilingual wordpiece model in production" for the four languages, with a language-specific triggering threshold so that coverage matches English. English stays on its own word-level model. That is a clear tradeoff of a few points of exact match in some languages for one model to train, serve and monitor, and its cost shows in Table 9.
09Serving: fitting a model into a keystroke
We now have a model that is good enough, and the question is whether it can run fast enough, because the best design on paper is worthless if the grey text arrives after the next letter. Remember the requirement that the 90th percentile of latency stays under 60 milliseconds, with inference on "almost every keystroke". In the paper's words, neural language models are "stateful, heavy-weight and computationally expensive", and, as the paper puts it, they are "not easily parallelized".
9.1 The life of one request
Smart Compose runs inside a streaming RPC server, a service that keeps a connection open for the length of a writing session, instead of answering each request cold. A higher-level Gmail service decides whether a message is eligible and, if it is, opens the stream. After that, "with each new keystroke the user types, new requests are presented to the server". Each request is made of two kinds of steps, and each step is a single time-step of inference of the language model. Prefix encoding steps feed the words Divya has typed into the model to build up its hidden state, the model's running summary of everything so far. Beam search steps then explore extensions of that prefix, as in section 05. Context lookups for the subject, previous email and date are done once and concatenated at every step.
Two details keep the work small. A user has a "sticky assignment to a server", so the server can keep her model state between requests, and the paper says "much of this computation can typically be skipped by using cached results from previous requests", so "the cost of prefix encoding is typically proportional to how much the user has typed since the last request". And since the model works in words, the letters typed in the middle of a word add no complete token to the prefix.
Divya has typed 60 words and is partway through the 61st. Say the beam is 4 candidates wide and the suggestion runs 6 words. How many single time-step model evaluations does one request need if the server remembers nothing from her previous keystroke, and how many if it has cached her state from one keystroke ago, with no new complete word typed since? (These sizes are illustrative.)
Show the answer
With no memory, the server must encode all 60 prefix words, then run 6 beam steps for 4 candidates each, for 60 + 24 = 84 evaluations. With the cached state and no new complete word, the prefix cost is zero and only the 24 beam evaluations remain, and they can run as 6 batched steps of 4. Once the prefix is cached, the beam search is the cost. That matches the paper's Table 5, where producing one suggestion costs roughly 9.5 times a single LSTM step on average.
- KeystrokeDivya types the "s" of "I will s" on her phone. New text goes to the server over the open stream. Network time between her phone and Google's servers isn't published.
- GateThe Gmail service that opened the stream already decided that this message is eligible. No further detail is published on what makes a message ineligible.
- RouteHer sticky assignment sends the request to the server holding her cached model state from her last keystroke, which removes most of the prefix work.
- PrefixThe server encodes only the complete words typed since the last request, and looks up the subject, the previous email and the time features once.
- BeamThe beam search runs. Its steps are batched across many users' requests and executed on a TPU, while the host CPU handles "application logic, caching and beam search book-keeping", and the personal model is blended in at each step. Its first step is restricted to words starting with "s".
- FilterThe top candidate's score is compared with the threshold. Offensive tokens were dropped during the search, and suggestions with a gendered pronoun are removed (section 12). Where in the pipeline each filter sits is unpublished.
- RenderIf a suggestion survives, it goes back along the stream and the phone draws the grey text. Only one latency budget is published, the whole-request target: 90th percentile under 60 ms. How it divides among these steps is unpublished.
9.2 Quality against latency, and the hardware
The paper's Table 5 reports how much each candidate model costs, with everything relative to one time-step of the smallest LSTM, measured on CPU. A single step of the two-layer 2,048-unit LSTM costs 2.29 times as much, and of the big Transformer, 5.42 times. A whole suggestion costs more, since it runs many steps: averaged over the test set, 9.51 times for the smallest LSTM, 20.87 for the wider LSTM, 19.71 for the small Transformer and 37.96 for the large one.
Here the paper explains why the Transformer's lead in quality turns into a loss in latency. During generation it must keep "self-attention keys and values from all previous decoding steps for all the layers of the model", so each new step reads more than the last and the cost grows with suggestion length. In the three length buckets of Table 5, the gap between the small Transformer and the smallest LSTM grows from 6.9 units (1 to 5 words: 10.78 against 3.91) to 9.1 (6 to 10 words) and 15.7 (11 to 15 words). An LSTM carries a fixed-size state, so each step costs the same however far along it is.
That leaves hardware. According to the blog post, the first CPU version averaged "hundreds of milliseconds", well over the budget, and the team moved the heavy arithmetic to accelerators in two stages. First-generation TPUs ran the matrix multiplications and activations but not operations such as softmax, which had to run on the host CPU. Then the second-generation Cloud TPU, which supports more of TensorFlow's operations, took over, with the XLA compiler fusing operations. Meanwhile the host kept the application logic, the caching and the beam-search bookkeeping. To use the accelerator well, the system batches the prefix steps and the beam steps of many requests together. Table 7 gives the effect, again relative to CPU: TPUv1 cut 90th percentile request latency to 0.16 times and raised throughput to 13.3 times, and TPUv2 reached 0.10 times and 93.3 times.
| Serving hardware | Plus | Minus |
|---|---|---|
| CPU | No special hardware, simplest operations | Average latency in the hundreds of milliseconds at first, and the lowest throughput |
| TPUv1 | 0.16x latency, 13.3x throughput | Some operations such as softmax still ran on the host CPU |
| TPUv2 (Cloud TPU) | 0.10x latency, 93.3x throughput, most operations on the accelerator | Requires batching across requests and ties the serving stack to one hardware family |
Google chose the second-generation TPU and, in the blog's words, improved the average latency "to tens of milliseconds". Cost is operational as much as technical: the model has to stay inside what the compiler and chip support, and batching means each request shares the chip with others. Hardware didn't change the model choice, though; it made the small, cheap model affordable at this volume. Its list of future directions still names "taking advantage of the latest hardware accelerators", along with a Transformer that applies self-attention only over a fixed-size window of recent steps, which would stop the cost per step from growing.
If TPUs are so much faster, why not run the big Transformer on them?
Table 7 of the paper shows a tenfold latency gain and a roughly ninety-fold throughput gain relative to CPU, but Table 5 shows the large Transformer costing about four times what the smallest LSTM does per suggestion. An accelerator closes the gap between the cheap model and the budget at Gmail's volume. It doesn't close the gap for a model that is four times heavier and still has to answer within the same tens of milliseconds, for every keystroke of a billion users. Written in 2019, the paper concludes that most of the advanced models "failed to meet our strict latency constraints" and leaves the question for future work.
This section's prefix cache is the same idea as the key-value cache that large language model servers keep between turns of a chat, and batching across users is what keeps a GPU or TPU busy in those systems as well. Chapter 31 covers both in detail.
10Training data, labels and the loop that feeds itself
We've built the system around a trained model without saying much about what it learned from. Training examples are the emails people wrote, and the label for every position is the word that came next. Every position in billions of messages is a training example with no human annotation, so the data scale is possible. It also means that the labels carry whatever the writers did, good and bad.
10.1 Where training and serving differ
In training, the model sees the true previous words and predicts one word at a time. In serving, it sees Divya's typed prefix, which is true, and then its own generated words, and those aren't. The metrics are designed with that mismatch in mind. Log perplexity measures the one-step quality, and ExactMatch measures whole generated phrases against the real continuation, so a model that is good at one-step prediction but drifts when it feeds on its own output would show up in ExactMatch. A second difference is that people stop typing mid-word, while the training examples are whole words. A constrained first step in the beam search from section 05 handles that at serving time without changing how the model is trained.
Training details are reported down to the stabilisers. They use Adam, uniform label smoothing, and an adaptive gradient clipping rule: "a training step is discarded completely if the log of the gradient norm value exceeds four standard deviations of its moving average". Experiments ran on 32 NVIDIA P100 GPUs each. Production models are trained on Cloud TPUs in a "quarter-pod, 64-chip setup", and the paper points out a benefit of using the same hardware family to train and serve: there are "no longer training/serving skews such as training in floating-point but serving with quantization". Google's 2018 blog adds that the team used a full TPUv2 Pod for experiments. How often the global model is retrained is unpublished; the personal models are described as needing "periodical re-training".
10.2 The loop
Here's a risk the published sources don't discuss, which we can reason about. Smart Compose trains on user-composed email. Once the feature is live, some of what people send is text they accepted from a suggestion. A future model trained on that mail learns from its own predecessor's words and sees them as ordinary writing. If accepted phrases are over-represented in the next corpus, the model grows more sure of them, they get shown more, and accepted more. Nothing in the paper says how, or whether, the team separates accepted suggestions from typed text in training. Teams in this position generally have two levers: keep an old, pre-launch slice of data in the mix, or tag accepted spans and treat them differently, and we don't know which the team uses. A related effect in recommendations, where a system trains on what it chose to show, is the loop that chapter 41 follows. At launch the effect is probably small, since few sent emails contain accepted text, and it would grow with adoption.
10.3 Not leaking Divya's mail, or anyone's
The most serious risk of training a language model on private email is that it memorises a sequence from one person's message and later emits it as a suggestion to someone else. Google's defence has two parts. One is the preprocessing of section 03, which replaces names, addresses and numbers with placeholder tokens and drops quoted text. Another is a test. Per the paper, "we have done extensive testing to make sure that only common phrases used by multiple users are memorized by our model, using findings from Carlini et al.", and the 2018 paper by Nicholas Carlini and colleagues, The Secret Sharer, applies its method to Smart Compose as its largest case study.
That method plants a canary, a random sequence that never occurs naturally, in the training data a chosen number of times, trains the model, and measures how much more likely the model finds the canary than other sequences of the same format. Take a set of all possible random sequences of that format. Rank every sequence in by the model's log perplexity on it, so the sequence the model finds most likely has rank 1. Then the canary's exposure is
An exposure of 0 means the canary ranks last, as if the model had never seen it. Its maximum, , means it ranks first. An exposure of 10 means the canary's rank is , so it sits in the top thousandth of the candidates. For Smart Compose, the canaries were five or seven words long, with the first two and last two words fixed as context and the middle ones random. They were inserted between 1 and 10,000 times into training data of about a billion sequences. A secret that appeared once in a billion sequences showed no sign of being memorised. Even a canary inserted 10,000 times reached an exposure of only 10. The paper describes that as the model being 1,000 times more likely to generate it than another random phrase, "but it is still not a very likely output, let alone the most likely".
This test measures memorisation of rare, planted secrets, so it's evidence about the risk and not a proof. It also shows that what the model learns is shaped by repetition: a phrase used by many people, such as "Thank you for your help", is learned thoroughly, and a phrase that one person wrote once is not. Carlini et al. list stronger defences, including clipping gradients and adding noise to training (differential privacy), and the Smart Compose paper doesn't say whether it uses them. Engineers worked under the same constraint. No one on the project could look at the underlying data, the paper says, and the Smart Reply paper describes the practice that goes with it: all data encrypted, engineers inspecting only aggregate statistics.
Testing a model for what it has memorised before release is now common for language models. Later work by Carlini and colleagues (2021) extracted verbatim training sequences from GPT-2, which shows the worry is real for large models.
11Measuring it: offline numbers and online ones
Divya's suggestion is right or wrong in a moment, but the team has to compare models that differ by a fraction of a percent and decide which ships. Testing every candidate on live users is slow and expensive, and the paper says so as one of its challenges: "we therefore need to devise proper efficient offline evaluation strategy and metrics which correlate well with online metrics that are critical to the product." The paper uses two offline metrics.
One is the log perplexity of section 03, which needs no generation at all and measures the average quality of next-word probabilities over a test set. ExactMatch@N, the second, measures the generated phrases themselves. For a predicted phrase that is N words long, it's the percentage of the predicted phrases that "exactly matches the first N words in the ground truth text". A weighted average over all lengths up to 15 is reported as "Overall". In symbols, with the set of shown suggestions that are N words long, the suggestion and the words the writer typed:
One more rule keeps the comparison honest. To compare models fairly the authors "first select model-specific triggering confidence thresholds to make sure all models have the same coverage, and then compute the ExactMatch results out of triggered suggestions". That's the point of section 06: without matched coverage, a model that speaks only on easy cases would look better than one that speaks more often.
Why compute ExactMatch only on the suggestions that were shown?
Because the product only ever shows those. A model's accuracy on all the phrases it could have generated includes many it would never display, and counting them would punish a model for being honest about its uncertainty. Matching coverage across models closes the loophole from the other side, since a model could otherwise improve its score by showing only trivial suggestions.
11.1 What the numbers say
Table 2 of the paper lists ExactMatch for four of the LM-A models. Putting it next to the log perplexities from Table 1 shows how the two metrics relate:
| Model (LM-A) | Log perplexity | ExactMatch@1 | @3 | @5 | Overall |
|---|---|---|---|---|---|
| LSTM-2-1024 | 3.26 | 84.63% | 40.25% | 31.82% | 66.99% |
| LSTM-2-2048 | 3.13 | 84.89% | 43.79% | 36.18% | 68.31% |
| Transformer-768-2048 | 3.08 | 83.93% | 43.37% | 41.10% | 66.94% |
| Transformer-1536-8192 | 2.90 | 85.33% | 47.87% | 43.92% | 67.73% |
Look at the two Transformer rows against the first LSTM. Log perplexity for the small Transformer is 0.18 lower than the LSTM's, and its five-word ExactMatch is nine points higher, yet its overall ExactMatch is 66.94%, a hair below the LSTM's 66.99%. Moving to the largest Transformer lowers log perplexity by 0.36 and gains 0.74 points overall. Overall ExactMatch barely moves because most suggestions are short, and on one-word suggestions every model scores between 84% and 85%. Chen et al. hypothesise that the improvement in perplexity "is mostly in places where the model is relatively low in confidence and Smart Compose is unlikely to be triggered". ExactMatch is "more important to production", the authors write, so the 0.36 improvement in the metric that doesn't decide what users see did not outweigh the latency bill.
| Metric | Where measured | What it can't tell you |
|---|---|---|
| Log perplexity | Offline, every position in the test set | Dominated by low-confidence positions the product never shows |
| ExactMatch@N, at matched coverage | Offline, shown suggestions only | Counts a near miss the same as nonsense, and uses only text people typed |
| Coverage | Offline, set by the threshold | Says nothing about whether the shown suggestions are right |
| Click-through rate of suggestions | Online | Needs a live experiment, and acceptance isn't the same as usefulness |
| Characters saved | Online, aggregate | The paper's headline figure, "over one billion characters" a week, but not a quality measure |
| 90th percentile latency | Online and in load tests | A constraint more than a metric: a model that misses 60 ms doesn't ship, however good |
Online results are described briefly. After launch, personalisation brought around 6% relative gain in click-through rate of suggestions and 10% relative gain in ExactMatch, so both kinds of metric moved together. Its blend weight was "first estimated from offline experiments, then verified by online experiments to ensure suggestion quality improves compared with using global model alone". Nothing in the paper gives the design of those experiments, such as the share of traffic, the duration or the guardrails, so we'll treat the standard machinery of random user assignment and a guardrail on latency as how a team in this position would work, and not as documented detail.
Selecting a model on an offline metric that is cheap and a proxy for an online one is the standard arrangement in applied machine learning, and chapter 25 covers its failure modes. Table 2's pattern is one of them: two metrics can agree on direction and disagree on size, and the team has to know which one tracks what users see.
12What went wrong, and what it cost
The sources describe a system that worked, so most of this section is about tradeoffs the team accepted, and one defect they found in testing. Neither the paper nor the blog reports a public incident or a retired feature, and we won't invent any.
12.1 Him and her
The defect is in section 7 of the paper. Its authors write: "we found instances of gender-occupation bias when testing our models." One example takes two sentences. When a user typed "I am meeting an investor next week", the model suggested "Did you want to meet him", and for "I am meeting a nurse next week" it suggested "Did you want to meet her". Nobody had instructed the model to do this. No cause is given, but the usual explanation is that in the text a model learns from, investors are more often called "he" and nurses "she", so the model repeats the statistics as though they were facts about the meeting. Google's blog post, citing the 2017 study by Aylin Caliskan and colleagues on human-like biases in language corpora, says that these associations "are deeply entangled in natural language data, which presents a considerable challenge to building any language model".
Google's decision, in one sentence of the paper, was this: "To limit the impact, we removed any suggestions with a gender pronoun and continue to explore algorithmic approaches to handle bias."
| Response to the bias | Plus | Minus |
|---|---|---|
| Ship the model as trained | No engineering cost, best raw ExactMatch | Repeats stereotypes to a billion people, in the user's own voice |
| Filter every suggestion containing a gendered pronoun | Cheap, certain and easy to audit; the failure the team found can no longer occur | Also removes correct, harmless suggestions, and does nothing about other biases that don't use pronouns |
| Rebalance the data or train the bias out of the model | Addresses the cause | The associations are entangled in language, there was no reliable method, and a debiased model still needs testing |
| Rebuild the product to suggest less | Less exposure of any kind of error | Removes the feature's value |
In the 2019 paper, Google reports taking the second option, and it calls the step a way to "limit the impact". How many legitimate suggestions the filter removes isn't quantified, and whether it is still in place today is unpublished. What a filter can do is make one specific harm impossible. It can't prove the model is fair, and it only works for harms that someone has thought to look for. This is the usual shape of the choice in deployed language models: an exact rule for a known failure now, and an open research problem for the rest.
Why filter the output instead of fixing the model?
A rule on the output works the same day it's written, and its behaviour is easy to state and test: no suggestion contains these words. A change to the training data or the objective would have to be retrained, evaluated and shown not to harm quality, with no agreed method at the time, as the blog admits. Google did both, in order: the filter now, and continued exploration of "algorithmic approaches" for later.
12.2 The other bills
The remaining costs came from choosing speed and maintainability over the best available model, and the paper's tables put numbers on each of them. Latency ruled out the Transformers and seq2seq models of section 04. Even the best of them lowered log perplexity from 3.26 to 2.90 and raised overall ExactMatch by 0.74 points, and this improvement was left unused. A multilingual model cost between 1 and 4 points of ExactMatch in three of the four languages, in return for one model instead of four. Privacy cost the team direct access to the data, and the paper accepts that the models might still memorise phrases, relying on tests to bound the risk. And the first version, on CPU, was far too slow, so the design depended on a hardware generation, with the first TPU leaving operations such as softmax on the host before the second generation fixed it.
One more cost isn't in any table. Smart Compose is a product where the person is the evaluator, and a suggestion that is subtly off in tone, or one that doesn't say what the writer meant, can be accepted by a hurried thumb on a bus. ExactMatch can't measure that, and the click-through rate counts the acceptance as a success. That risk isn't discussed in the paper, and we mention it because the logged metrics can't see it.
13The whole system
Putting the pieces together, one keystroke from Divya's phone passes through a stream to a server that keeps her session's state. That server encodes whatever she has just typed, looks up the context of the email, and runs a beam search in which a global neural language model and her personal n-gram model each contribute a probability at every step. A threshold chosen for a target coverage decides whether the best phrase is shown, and filters remove offensive words and gendered pronouns. All of this happens on a TPU shared with other users' requests, inside a 90th-percentile budget of 60 milliseconds. Offline, the global model is trained on a corpus of billions of cleaned messages on the same hardware family it's served on, the personal models are rebuilt from each person's Sent mail, and every candidate is judged on log perplexity and on ExactMatch at matched coverage before an online experiment decides.
Several parts of this picture are unpublished: the request volume, the production model size and beam parameters, how many machines serve it, the retraining schedule, and where the filters sit in the pipeline. Sources describe the system as of 2018 and 2019, and we don't know what Gmail runs today. Future work in the paper lists Transformers with local attention and pre-trained language models as directions to try.
14Summary
- Smart Compose is a language model, not a list of replies. Smart Reply picked from vetted one-tap answers once per email. Smart Compose extends a half-typed sentence on almost every keystroke, so it has to generate words (Chen et al., 2019).
- Typing speed sets the time budget. Keystrokes arrive a few hundred milliseconds apart, so the paper requires the 90th percentile of latency to stay under 60 ms, and the 2018 blog says "ideally within 100ms".
- An n-gram table fails on context and size. It can't see the subject or the previous email, and its table explodes as the window grows. Its "Thursday" and "Tuesday" examples need information from another message.
- Context enters the model at every step. It predicts the next word from the typed prefix plus the subject, the previous email, the date, time and locale, and the loss is the average negative log probability of the word written.
- Averaged context embeddings beat the alternatives on latency. LM-A, LM-B and seq2seq were compared. LM-A matched LM-B's quality at lower cost, and seq2seq missed the latency target "by orders of magnitude".
- Beam search generates the phrase, and its score doubles as confidence. A heap of the best candidates is extended word by word, the first step is limited to completions of the half-typed word, and the length-normalised log probability orders the candidates.
- Staying quiet is a design requirement. A phrase is shown only if its score clears a threshold set for a target coverage, and only the top suggestion is shown. Showing fewer suggestions makes the shown ones more often right.
- Personalisation is a second, tiny model mixed in at every beam step. A Katz-backoff n-gram on the user's Sent mail is blended as , with a constant weight that peaked at 0.4 offline and gave about 6% more clicks online.
- Vocabulary size is a latency decision. Nearly two thirds of an LSTM-2-1024 model is its output layer, so four languages share one 50,000-wordpiece vocabulary even though word models scored higher for three of them.
- Serving is the hard engineering. A sticky server keeps cached state, requests are batched across users, and the move from CPU to TPUv2 cut latency to 0.10 times and raised throughput 93-fold.
- Privacy and fairness had to be handled in the design. Google's team tested for memorisation with canaries and removed all suggestions containing a gendered pronoun after finding a gender-occupation bias, and it said it was still exploring better fixes.
15Build this
The ideas in this chapter fit in a weekend on a laptop. You can build a small Smart Compose for short text and watch each design choice change the numbers.
Pick a public corpus of short messages with subjects and replies, for example the Enron email corpus, and hold out 20% as a test set. Everything you build will be judged on ExactMatch at matched coverage, the way the paper does it.
- Preprocess as the paper does: drop quoted text and salutations, replace names, numbers and addresses with placeholder tokens, and keep a vocabulary of the 10,000 most frequent words.
- Train a small LSTM language model twice, once on the body alone and once with the subject and previous message as averaged embeddings concatenated at every step. Compare test log perplexity, and look at the positions where the context should decide the word.
- Write beam search with a beam of 4, a maximum of 8 words and a first step restricted to words that start with the typed letters. Score candidates by length-normalised log probability.
- Choose thresholds that give coverage of 100%, 50%, 20% and 5% on a held-out stream, and report ExactMatch@1, @3 and overall at each coverage. Plot the curve and compare it with section 06.
- Train a smoothed bigram model on a single author's messages and blend it with the neural model at every beam step. Sweep the weight from 0 to 1 and find the peak. Repeat for authors with 100 and 5,000 messages.
- Time one request with and without a cache of the hidden state, for prefixes of 10 and 100 words, and plot 90th percentile latency against beam width.
16Interview questions
BeginnerWhy can't Smart Compose be built the way Smart Reply was?
Smart Reply reads an incoming message once and picks from a fixed list of vetted short replies, using an LSTM and a trie-constrained beam search so that the cost doesn't grow with the list. Smart Compose has to extend whatever the user has typed so far, from the middle of a sentence, after almost every keystroke, and what people write is too varied for a list: Smart Reply's authors found that over 40% of short responses in a sample of 10 million occurred only once. So Smart Compose is a language model that generates words, conditioned on the typed prefix and on the email's context.
BeginnerWhat latency does Smart Compose need, and why?
In 2019 the paper required the 90th percentile of latency to be under 60 ms, citing the classic result that about 100 ms is the limit for a system to feel instantaneous. In 2018 the blog said "ideally within 100ms". Typing at roughly 40 words a minute gives about 300 ms between keystrokes on average, and the model runs on almost every keystroke, so a suggestion that arrives late is stale. A first CPU version averaged hundreds of milliseconds, and that pushed the team to TPUs.
BeginnerWhat is beam search, and why use it instead of picking the top word each step?
Beam search keeps the best partial phrases at each step, extends each with its most likely next words, and prunes back to , until phrases end at punctuation, an end token or a maximum length. Greedy decoding commits to the best first word and can't recover if that word leads to a poor continuation: 0.5 × 0.3 against 0.4 × 0.95 in a constructed case. Beam search costs about model steps per word, but it returns several scored candidates, and the score is what the trigger uses.
IntermediateHow does the system decide whether to show a suggestion?
It scores the best beam candidate by its length-normalised log probability, , and shows it only if the score is above a threshold. Its threshold is chosen to hit a target coverage, the fraction of keystrokes that show a suggestion: take scores from held-out typing and pick the quantile. Length normalisation stops long phrases being penalised just for having more words. Lower coverage raises the exact-match rate of what is shown, as long as the score is a good judge of the model's own accuracy, and each language gets its own threshold so coverage stays comparable.
IntermediateCompare LM-A, LM-B and seq2seq for feeding in context. Which did Google choose?
LM-A is a language model over the body, with each context field encoded by averaging its token embeddings and concatenating the result to the word embedding at every step. LM-B packs subject, previous email and body into one sequence with separators. That is simpler but much longer. Seq2seq encodes the context and decodes the body with attention. At equal size LM-A and LM-B had similar log perplexity (3.26 for LSTM-2-1024 in both), seq2seq LSTM was better (3.09), and Transformers beat LSTMs. Google chose LM-A because the latency budget ruled out the others, and the blog describes the result as a bag-of-words context feeding an RNN-LM, with only a slight loss of quality.
IntermediateHow is personalisation done, and why interpolate probabilities?
Each user gets a small Katz-backoff n-gram model trained on their Sent mail from the past few months, stored as a weighted finite automaton. At every beam step the next-word probability is , with a constant chosen offline (the paper's peak is 0.4) and verified online. Mixing inside the beam lets a personal word enter the beam and be extended by the global model, instead of comparing finished phrases. Reported gains were roughly 6% in suggestion click-through rate and 10% in ExactMatch. A per-user neural model would be too large and too hungry for data, and a context-dependent weight would need its own model.
IntermediatePerplexity improved by 0.36 but ExactMatch barely changed. Why, and which metric do you trust?
Log perplexity averages over every position, and most of the improvement from a bigger model lands where the model is unsure, and the system doesn't show a suggestion there. ExactMatch is measured only on shown suggestions at matched coverage, and most of those are short, where all models score about 84% to 85%. Between LSTM-2-1024 and Transformer-1536-8192 the paper gets 3.26 against 2.90 in perplexity, and 66.99% against 67.73% overall. For production, the paper says, ExactMatch matters more. Neither replaces an online experiment, and that's why click-through rate and a latency constraint come last.
DeepHow would you test whether a model like this leaks one user's email to another?
Use the canary method from The Secret Sharer, which the Smart Compose team applied. Insert random sequences that can't occur naturally into the training data a chosen number of times, train, then rank each canary among all random sequences of the same format by the model's perplexity. Exposure is , so a canary the model ranks first has the maximum. For Smart Compose, a canary seen once in a billion sequences showed no memorisation, and one inserted 10,000 times reached exposure 10, roughly 1,000 times likelier than a random phrase and still not extractable. It bounds the risk for rare secrets and doesn't prove safety, so you pair it with preprocessing, and possibly with gradient clipping and noise.
DeepYour model suggests "her" after "meeting a nurse". What do you do, and what does it cost?
Google's team found this and removed every suggestion containing a gendered pronoun while continuing research on algorithmic fixes. A filter is cheap, certain and auditable, and it makes that specific failure impossible. It also drops harmless suggestions, and it addresses nothing that doesn't use pronouns, so it isn't a fairness guarantee. Retraining on rebalanced data or adding a debiasing objective treats the cause but has no reliable method and needs retraining and re-evaluation, since the associations are entangled in the language. In practice you ship the filter now, build test prompts for other known biases, and keep investigating the model.
DeepWalk through the cost of one request and where caching and batching help.
A request is prefix-encoding steps plus beam-search steps, each a single time-step of the model. Context lookups happen once. A sticky server keeps the hidden state from the last request, so prefix cost is proportional to the new complete words typed (often zero mid-word), and then the beam search dominates: about 9.5 times a single LSTM step per suggestion in Table 5. Batching prefix and beam steps across users keeps the accelerator busy. On a vocabulary of 50,000, the output layer is about three quarters of each step's arithmetic, so shrinking the vocabulary or fusing the softmax matters. On the phone itself, as in Gboard, you would shrink the model to about a million parameters and a 10,000-word vocabulary to meet a 20 ms expectation.