---
title: "General Purpose Text Embeddings from Pre-trained Language"
description: "Du and colleagues test how a shared RoBERTa encoder can serve many text classifiers, balancing accuracy, computation and storage."
canonical: "https://research.elamur.ai/free/en/papers/du-2020-general-purpose-text-embeddings-pre/"
---
Elamur: [Mova](https://md.mova.elamur.ai/free/en/) · [Parse](https://mova.elamur.ai/free/en/parse/) · **Research** · [Gali](https://md.gali.elamur.ai/free/en/) · [MCP](https://mcp.elamur.ai/) · [Locations](https://md.locations.elamur.ai/free/en/) · [Weather](https://md.weather.elamur.ai/free/en/) · [Shryfti](https://md.shryfti.elamur.ai/free/en/)

[Elamur Research](https://md.research.elamur.ai/free/en/) · [this page in HTML](https://research.elamur.ai/free/en/papers/du-2020-general-purpose-text-embeddings-pre/)

[Elamur Research](https://md.research.elamur.ai/free/en/) / [papers](https://md.research.elamur.ai/free/en/papers/) / [2020](https://md.research.elamur.ai/free/en/papers/2020/) / General Purpose Text Embeddings from Pre-trained Language Models for Scalable Inference

# General Purpose Text Embeddings from Pre-trained Language Models for Scalable Inference

Paper · 2020 · Jingfei Du, Myle Ott, Haoran Li et al.

**Authors:** [Jingfei Du](https://md.research.elamur.ai/free/en/authors/jingfei-du/), [Myle Ott](https://md.research.elamur.ai/free/en/authors/myle-ott/), [Haoran Li](https://md.research.elamur.ai/free/en/authors/haoran-li/), [Xing Zhou](https://md.research.elamur.ai/free/en/authors/xing-zhou/) and [Veselin Stoyanov](https://md.research.elamur.ai/free/en/authors/veselin-stoyanov/) · **Year:** 2020 · **Venue:** Findings of the Association for Computational Linguistics: EMNLP 2020 · **Licence:** [CC BY 4.0 (ACL Anthology)](https://creativecommons.org/licenses/by/4.0/)

Findings of the Association for Computational Linguistics: EMNLP 2020 · [licence](https://creativecommons.org/licenses/by/4.0/)

- [Publisher's page](https://aclanthology.org/2020.findings-emnlp.271/)
- [PDF](https://aclanthology.org/2020.findings-emnlp.271.pdf)
- [DOI 10.18653/v1/2020.findings-emnlp.271](https://doi.org/10.18653/v1/2020.findings-emnlp.271)

## Summary

A system that reads a news article may need to assign it a topic, judge its sentiment and make several other predictions. Each decision calls for a different kind of evidence, but much of the work of processing the text can be shared. The authors ask whether a single encoder can do that expensive work once and produce features that small classifiers can reuse, including classifiers for tasks introduced later. They study the question with [RoBERTa](https://md.research.elamur.ai/free/en/papers/liu-2019-roberta-robustly-optimized-bert-pretraining/) across 14 [text classification](https://md.research.elamur.ai/free/en/concepts/text-classification/) datasets, ranging from judgments about individual texts to decisions about the relationship between two texts.

The authors first train RoBERTa jointly on several labeled datasets. They then freeze the encoder, keeping its weights fixed, and train a new classifier for a dataset excluded from that joint training. The new classifier can draw on features from several encoder layers and several positions in the input. The authors compare this approach with compressing the entire input into a single vector in advance. Keeping a vector for each position gives the eventual classifier more evidence to work with. It can learn which parts of the input matter to its own prediction while the expensive encoding remains common to all tasks.

Across the development sets, the authors’ preferred configuration, which averages encoder layers and uses task-specific attention over positions, reaches 88.4% average accuracy. Separate end-to-end RoBERTa classifiers reach 90.5%, and separate DistilRoBERTa classifiers reach 87.1%. The computational comparison depends on how many predictions are made from the same input. DistilRoBERTa has the lowest estimated operation count when there are 7 or fewer tasks. The frozen shared encoder becomes cheaper beyond that point because each additional task can reuse the encoding already computed for the text. Accuracy also depends on which datasets the encoder saw. Holding out an entire family of tasks reduces average accuracy to 86.6% with the same pooling configuration.

The paper also asks whether an encoding can be saved for use after the original classification run. Reducing the saved features to 8-bit values leaves the reported average at 88.4%. Storing only the sign of each feature reduces average accuracy to 88.0% and cuts feature storage by a factor of 16. The experiments thus describe a particular way to support future classification work. A system can keep a compact representation of each input and train a new classifier on top of it, with the accuracy of that classifier depending on what the shared encoder learned and what the saved representation retains.

## Deep dive: General Purpose Text Embeddings from Pre-trained Language Models for Scalable Inference

Du and colleagues test how a shared RoBERTa encoder can serve many text classifiers, balancing accuracy, computation and storage. · about 32 minutes to read

**In this deep dive**

1. [The problem and its context](#dd-the-problem-and-its-context)
2. [The method, step by step](#dd-the-method-step-by-step)
3. [Experiments and results](#dd-experiments-and-results)
4. [What the ablations show](#dd-what-the-ablations-show)
5. [Limitations](#dd-limitations)
6. [What came after](#dd-what-came-after)

### The problem and its context

#### The cost of asking several questions about the same text

The paper starts from a distinction between the work needed to read a text and the work needed to make a particular decision about it. A topic classifier can use the names and phrases that identify what a news article is about. A [sentiment analysis](https://md.research.elamur.ai/free/en/topics/sentiment-emotion/) classifier may care more about an evaluation expressed in a small part of the article. The decisions have different labels and training examples. Both, however, can benefit from a representation that already takes account of the surrounding words. If every classifier computes that representation independently, the system pays repeatedly for a substantial part of the same job.

In the approach the paper takes as its main accuracy reference, each task starts with a copy of the same pretrained encoder and adapts it to its own labeled examples. [Fine-tuning](https://md.research.elamur.ai/free/en/concepts/fine-tuning/) means continuing training from those existing weights. In end-to-end fine-tuning, the task can change weights all the way through the encoder, as well as in the final component that picks the label. The resulting copies generally differ from one another. Even if they receive identical text, an intermediate result from one copy cannot simply stand in for the result of another. Sharing the initial weights helps with training, while sharing the actual work of making predictions requires the weights used for that work to stay common.

This problem mattered in the setting the authors describe because large pretrained encoders were already strong across many [natural language processing](https://md.research.elamur.ai/free/en/concepts/natural-language-processing/) tasks, and the work they cite found that scaling those encoders could improve accuracy further. A system might therefore have good reasons to start with a large encoder, even as the number of predictions it needs to make puts pressure on its inference budget. Here inference means processing an input to produce predictions after training. The paper’s question is whether changing the way predictions share that processing can make a large encoder practical across a collection of tasks. [Language modeling and pretraining](https://md.research.elamur.ai/free/en/topics/language-models/)

Consider how the relevant unit of work changes. If an application needs a sentiment label for one review, the sentiment system must pay for whatever encoding it uses. If it needs several labels for that same review, each independent classifier adds another encoding pass. The authors’ proposed arrangement pays the large cost once and then adds a smaller amount of work for each label. The opportunity comes from multiple tasks using the same input. A workload that assigns different tasks to different texts offers a different opportunity for sharing, even when it uses the same classifiers.

#### The approaches already available

Prior work had shown several ways to adapt a pretrained encoder. The paper discusses end-to-end adaptation alongside feature extraction. In feature extraction, an encoder produces numerical descriptions of the input, and the downstream task learns how to use those descriptions. Work the authors cite found that full adaptation worked better than extracting features directly from pretrained [BERT](https://md.research.elamur.ai/free/en/papers/devlin-2019-bert-pre-training-deep-bidirectional/). Du and colleagues add a stage between pretraining and feature extraction. They ask whether joint training on labeled tasks can make the frozen features more useful to a later classifier.

General-purpose sentence encoders offered a particularly simple way to share features. They produced a vector whose size was the same for every sentence. The paper describes earlier approaches that learned such representations from supervised objectives, self-supervised objectives or a mixture of the two. A fixed-size vector is convenient because a classifier has a uniform input and the encoder can generate the representation before the eventual use is known. Prior evaluations on unseen tasks, as the paper describes them, often found a sizeable accuracy gap relative to separate fine-tuning. One question for the new experiments was how much of that gap depended on the way the encoder compressed its output.

The paper also draws on [contextualized word representations](https://md.research.elamur.ai/free/en/papers/peters-2018-deep-contextualized-word-representations/). In this approach a position in the text has a vector that depends on its context. Retaining those vectors gives the classifier access to a description of each part of the input. It can then learn which parts to use. The authors take this as a middle ground between a single summary vector and a separate encoder that can change all its computations for each new task. A set of position vectors grows with the input but can still be passed from an encoder to several relatively small classifiers.

Joint training was another established way to share work. In [multitask learning](https://md.research.elamur.ai/free/en/papers/caruana-1997-multitask-learning/), a common encoder receives training signals from several tasks. It can benefit from similarities among them and reuse its layers during inference. The arrangement is especially straightforward when the tasks are known in advance. Each of them helps shape the shared encoder, and each has a prediction component ready by the end of training. The authors focus on the operational difficulty that follows when the task list changes. If a new task must participate in joint training, updating the system entails training the shared encoder again. Different tasks may also have different schedules for retraining. [An Overview of Multi-Task Learning in Deep Neural Networks](https://md.research.elamur.ai/free/en/papers/ruder-2017-overview-multi-task-learning-deep/)

The paper discusses an adaptation method that puts task-specific capacity inside each encoder layer. This approach gives a task some freedom to change the computation without updating all the pretrained weights. The authors point out that a shared set of weights alone does not guarantee shared computation. If the task-specific additions change what one layer produces, subsequent layers receive different inputs for different tasks. A separate path must still be evaluated for each task. In the proposed arrangement, task-specific processing begins after the common encoding, so an input can actually make use of the same computed features.

[Knowledge distillation](https://md.research.elamur.ai/free/en/papers/hinton-2015-distilling-knowledge-neural-network/) addresses the cost of each individual pass. A smaller student is trained to reproduce behavior from a larger teacher or a combination of teachers. The paper treats this as a serious alternative because a smaller encoder may already be cheap enough when only a few predictions are required. A distilled classifier still runs its own encoder when each task is fine-tuned separately. Its cost grows with the number of tasks, but the cost per task is smaller. The authors compare that arrangement with one that pays for a large pass up front and very little additional encoding work after it. [DistilBERT](https://md.research.elamur.ai/free/en/papers/sanh-2019-distilbert-distilled-version-bert-smaller/)

Finally, the authors place their work alongside techniques such as quantization and operator fusion. Quantization represents numerical values with fewer bits. Operator fusion combines operations that would otherwise be carried out separately. The paper treats such optimizations as compatible with sharing. It uses quantization specifically to address a second expense that arises when the encoder’s output has to survive beyond the immediate prediction run. The same choice that gives future classifiers more evidence, keeping features from many positions and potentially many layers, can make those features expensive to store.

### The method, step by step

#### What passes from the encoder to the classifier

The encoder reads an input and produces a series of numerical states. At each layer, there is a vector at each input position. The vector is a list of feature values that the classifier can use. The architecture is a [Transformer](https://md.research.elamur.ai/free/en/concepts/transformer/), so the representation at a position can reflect information from elsewhere in the input. The authors mainly work with RoBERTa LARGE, which has 24 layers, vectors of dimension 1024 and 355M parameters. Layers and positions give the authors separate choices about what information to retain. They can draw on several depths of computation at each position, then decide how much of the sequence to expose to the downstream classifier. [Attention Is All You Need](https://md.research.elamur.ai/free/en/papers/vaswani-2017-attention-all-need/)

For a task with one text per example, the encoder processes that text. For an example containing a pair, the authors join the two texts using a special separator token. The result is a single sequence, so the representations can reflect the combined input. This preserves the ability to make a decision about the pair, which matters when a label concerns whether two texts express the same meaning or stand in an inference relationship. It also defines the unit of reuse. The features for a joined pair belong to that pair as presented to the encoder.

A classification head is the small component that takes the features and produces a prediction in the task’s label inventory. Every task has its own head, but the authors use the same head architecture across datasets. It is a multilayer perceptron with two layers. Its inner dimension is the size of the pooled feature vector, and it uses a hyperbolic tangent activation, typically abbreviated tanh. This activation lets the head transform its input nonlinearly before producing a decision. A new task has to learn its own head because the available labels and the features that distinguish them can change from task to task.

The comparison encoder, DistilRoBERTa, has 6 layers, representations of dimension 768 and 82M parameters. The paper describes it as having 1/4 as many parameters and requiring 1/7 as much computation as the full encoder. It plays a different role in the study from the frozen RoBERTa LARGE encoder. It tests how far straightforward savings on each independent pass can take the system. The shared approach keeps the large encoder and changes how frequently that pass must be performed.

#### Preparing the encoder for a task it has never been trained on

The authors define a task by its dataset. For every evaluation in the leave-one-task-out setting, they select a target dataset and set it aside during joint encoder training. They start from pretrained RoBERTa and train the encoder end to end using the other datasets. Each participating task has its own head. A mistake on one task updates that task’s head and contributes to an update to the shared encoder, just as mistakes from the other tasks contribute to that common update.

The first training stage gives the encoder experience with labeled prediction while reserving the target dataset for a separate experiment. In the second stage, the authors fix the encoder’s weights. They initialize a new classification head at random and train it using labeled examples from the target dataset. Pooling components with task-specific parameters are trained in this stage as well. The term *unseen task* therefore concerns what the shared encoder saw during joint training. The new head is supervised on that task. Its job is to learn a decision from a representation that cannot change in response to its errors.

The authors repeat the procedure with each dataset as the target. Each repetition calls for an encoder trained with the corresponding target excluded. Averaging the resulting scores answers a question about how the procedure transfers across datasets. For each score, the head must solve its task using an encoder prepared without supervision from that particular dataset. The protocol is a way to simulate adding tasks to an existing encoder, while obtaining a result for each target in the collection.

Preparing and using a shared encoder for a held-out task The steps in order.

During joint training, the authors take a batch from each participating task at every update. The large differences in dataset sizes make the weighting of those batches consequential. If training gives datasets influence directly in proportion to their size, the largest collections can account for much of the learning signal. Giving every task the same weight would remove size from the weighting rule entirely. The paper chooses intermediate weights, using the number of training examples and a temperature that controls how strongly that number matters. In the direction specified by the authors, the normalized power weighting is:

```
αᵢ = Dᵢᵀ / ∑ⱼ Dⱼᵀ
```

Here αᵢ is the weight on the loss from task i. Dᵢ is the number of training examples in that task, and T is the temperature. The summation symbol ∑ means to add the corresponding terms over all tasks in the joint training run. The index j identifies each participating task in turn, and Dⱼ is its training-set size. In both the numerator and denominator, the superscript T denotes the power applied to a dataset size. Dividing by the sum of those powers makes the task weights add up to a whole.

The authors describe proportional weighting at T = 1 and increasingly uniform weighting as T approaches 0. They use T = 0.1, a setting chosen from early experiments. Each task contributes a batch at the update under this procedure. The weights determine how much the resulting losses count when the shared parameters are updated. Thus the sampling description and the loss weighting describe different parts of the same update. The paper cites the unified text-to-text work as inspiration for tempering the influence of dataset size. [Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer](https://md.research.elamur.ai/free/en/papers/raffel-2019-exploring-limits-transfer-learning-unified/)

The appendix gives a concrete case. To prepare an encoder for MNLI, the authors use 4 samples from each of the 13 other tasks. This gives a combined batch size of 52. The learning rate for this joint adaptation is 1e-5. Every update can therefore incorporate signals from the full set of participating tasks, even though none of the MNLI labels can affect the encoder. Later the MNLI head can learn from MNLI examples with that encoder frozen.

#### Pooling across layers

The encoder’s output contains more values than the head needs to see directly. The authors reduce the output in stages, beginning with pooling across layers. At any given position they have a vector from each selected layer. Pooling across layers produces a single vector at that position while determining which depths of the encoder contribute to it. The procedure is repeated across positions, so retaining several depths at this stage does not require collapsing the sequence.

The simplest choice is to take the final layer. This needs just one vector per position from the encoder’s output. The second choice is to average the last m layers, where m is the number of layers selected. The authors tune m and report that 16 is the best choice in most settings. The operation lines up the vectors at the same input position, then takes a mean for each feature dimension. Because this average has no task-specific weights, different classifiers can use the same layer average. Saving only that average also means that a future classifier receives the combined values, with the original layer outputs no longer available as separate inputs to it.

The third choice is a learned combination. Each task learns weights for combining all the layers. A new task can then decide for itself which depths to emphasize. The option makes a difference to what the system must keep. If different tasks are to produce their own mixtures later, the reusable input to the mixtures still has to distinguish the layers. A stored task-independent mean is sufficient for the averaging setup, while a future learned mixture requires richer stored features. The authors situate this option alongside earlier work that combined layers with learned weights. [BERT Rediscovers the Classical NLP Pipeline](https://md.research.elamur.ai/free/en/papers/tenney-2019-bert-rediscovers-classical-nlp-pipeline/)

These choices are independent of whether the encoder is frozen. A frozen encoder’s training has already determined what comes out of each layer. Averaging or choosing a layer makes a task-independent selection from those outputs. A learned mixture changes how the task reads the frozen outputs. Gradients used to train the mixture adjust the reading operation and leave the encoder’s internal computations intact.

#### Pooling across positions

After layer pooling, the output still contains a vector at each position. The final classification head expects one pooled vector. The authors’ simplest position rule takes the vector at the first position, occupied by a special token referred to as CLS. Using CLS gives the system a fixed-size feature for every input. Its usefulness depends on how much information the encoder has collected into that position during its own training.

Another position rule averages the vectors across the sequence. That makes every position available to the pooling operation, with equal weight in the mean. This procedure also produces a fixed-size feature independently of the task. The difference from CLS lies in how evidence reaches that feature. With CLS pooling, the classifier relies on what the encoder already wrote into a particular state. With position averaging, the pooling step gathers values from throughout the sequence before the classifier sees the result.

The flexible option uses multi-head attention, abbreviated MHA. The task has a learned query, which acts as a request for evidence from the sequence. The position vectors act as keys and values. The keys are used to determine which positions receive attention, and the values supply the information combined according to that attention. The multiple heads let the pooling component make several such selections within the same operation. The result is a pooled feature for the classifier. The shared encoder provides the position vectors, while the query, attention module and classification head are trained for the particular target.

There is an important distinction between averaging layers and averaging positions. When the authors average layers, a new head can still make a separate judgment about each position through attention. When they average positions before any task-specific processing, evidence from all positions has already been combined by a uniform rule. The layer-average and attention configuration uses the simpler choice in the depth dimension and the flexible choice in the position dimension. Its common output keeps the same width per position and grows as the input gets longer.

This is why the paper describes the output as limited-size. For each position, a bounded vector carries the information needed by the pooling component. The number of positions still depends on the text. In a system serving several classifiers, the encoder can compute the positions once. One classifier can learn to look for evidence relevant to document category, and another can use the same input vectors to look for sentiment. They have separate queries and output heads. Their freedom is in what they select and how they interpret it, while the feature values they start from remain shared.

#### Saving the features

If all the predictions happen together, the shared encoder’s output can be used immediately. The authors also consider *backfilling*, in which a classifier introduced later must be applied to text that has already been processed. Retaining features could spare the system a fresh pass through the large encoder each time a previously processed input needs a new label. The cost of doing so grows with the number of vectors saved and with the precision of every value in them.

For a 50 token input, the paper illustrates the amount of data that would be retained by saving all layers and positions:

```
50 × 24 × 1024
```

The 50 is the length of the example in tokens, the 24 is the number of RoBERTa LARGE layers, and the 1024 is the number of dimensions in each position vector at each layer. The multiplication sign × joins these counts to give the number of feature values in the example. With half-precision floating point, the paper estimates 2.3MB of storage for that output. Pooling across layers before storage can greatly reduce the number of values, and quantization can reduce the bits needed for each value retained.

For the 8-bit condition, the authors use scale and zero-point parameters to map floating-point features into the integer range 0-255. The scale sets the size of a step in the discretized values. The zero point defines the correspondence between zero in the original values and the integer coding. For the 1-bit condition, the sign function distinguishes feature values by sign and discards their magnitude. The head therefore learns to make a prediction from a much coarser description of the same input.

The paper applies compression before training the target classifier on the frozen features. A new classifier is trained in the setting it will face when only the quantized representation is available. The authors also examine where quantization goes relative to pooling across layers. Those are separate choices. The first determines what sort of features the new classifier can learn from. The second determines whether the layer combination receives the original numerical values or values already transformed by quantization.

#### How task-specific training is run

The authors mostly follow the RoBERTa fine-tuning schedule. In their single-task runs they search learning rates in `{1,2,3}e-5` and batch sizes in `{16,32}` for each dataset. They use the [Adam](https://md.research.elamur.ai/free/en/papers/kingma-2014-adam-method-stochastic-optimization/) optimizer with β₁ = 0.9, β₂ = 0.98 and an epsilon of `1e − 6`. The beta parameters control the moving estimates Adam uses in updating weights, and epsilon is its numerical stability term. The learning rate rises linearly during the first 6% of updates, then declines linearly to 0. The paper specifies dropout with probability 0.1 and weight decay of 0.01.

The usual training schedule is 10 epochs, with an epoch corresponding to a pass through the training data. The authors check development accuracy at epoch boundaries and report the best development value. For the two large Amazon datasets they use a single epoch. They use five for the Yelp datasets and DBpedia. This reduces the training work for the larger collections and means the number of chances to check an epoch boundary varies across tasks. The experiments use mixed precision on Nvidia V100 GPUs, with the [fairseq](https://md.research.elamur.ai/free/en/papers/ott-2019-fairseq-fast-extensible-toolkit-sequence/) and [PyTorch](https://md.research.elamur.ai/free/en/papers/paszke-2019-pytorch-imperative-style-high-performance/) libraries.

### Experiments and results

#### Datasets, splits and comparisons

The evaluation covers 14 datasets distributed across sentiment, document categorization, linguistic acceptability, natural language inference and paraphrase identification. The sentiment tasks include SST-2 and IMDB. Amazon and Yelp each contribute versions with different label inventories. For example, Amazon-5 has 3M training examples and 5 labels, while Yelp-2 has 560K training examples and 2 labels. Document categorization includes AG-news and DBpedia, with 4 and 14 labels respectively. A linguistic acceptability task, CoLA, asks for a judgment about an individual input.

In the pair tasks, the label applies to the combined example. The inference group includes MNLI, QNLI and RTE. For scale, the paper lists 393K training examples for MNLI and 2.5K for RTE. The paraphrase group comprises QQP and MRPC. Such variation matters when training the shared encoder. Examples from the largest datasets offer substantially more labeled data, while the loss weighting allows the smaller tasks to retain influence over the shared representation. Variation also matters when interpreting transfer. Excluding one small dataset can still leave the encoder with labeled experience in decisions that belong to the same broad family.

The main outcome is development-set accuracy, the proportion of examples assigned the correct label. The authors use development sets because test sets are unavailable to them for a number of datasets, including tasks drawn from [GLUE](https://md.research.elamur.ai/free/en/papers/wang-2018-glue-multi-task-benchmark-analysis/). The paper reports individual results, results grouped by task family and an overall average. The average gives a view across datasets of very different sizes. A family result can reveal a problem that the overall figure obscures, and individual scores show whether that family behaves consistently. CoLA accuracy is recomputed for the BERT and XLNet comparisons because the original work reported a different metric.

The baselines establish several points on the tradeoff. End-to-end RoBERTa and DistilRoBERTa show what independent classifiers can achieve with a large encoder and a distilled one. The paper also includes BERT and [XLNet](https://md.research.elamur.ai/free/en/papers/yang-2019-xlnet-generalized-autoregressive-pretraining-language/) results from earlier work. A frozen RoBERTa encoder with no intervening supervised multitask training tests what extraction can achieve directly from the initial pretrained weights. Finally, the authors evaluate a single encoder trained jointly on all the tasks, using the heads trained in that joint run. That result represents a system that knew its full set of tasks beforehand.

#### Accuracy with complete and shared encoders

The independently fine-tuned RoBERTa classifiers attain 90.5% overall development accuracy. Adding joint training on the other tasks before fully fine-tuning each target raises the average to 90.7%. The authors report the improvement as +0.2%. In this comparison the target task is allowed to change the entire encoder. It tests whether supervised training on the other datasets gives a better starting point for that update. It does not impose the shared computation constraint of the frozen-feature setting.

The imported BERT result is 87.6% on average, and XLNet reaches 89.5%. The authors’ DistilRoBERTa runs average 87.1%. Family averages show where the full and distilled RoBERTa encoders differ. End-to-end RoBERTa reaches 91.3% on natural language inference, where DistilRoBERTa reaches 80.7%. Their sentiment averages are 88.2% and 86.6%, respectively. The ease of replacing the full encoder with the smaller one is therefore sensitive to the mix of tasks, even before considering whether they can share computation.

Average development accuracy across the 14 classification datasets The frozen multitask encoder with layer averaging and attention scores above separate distilled classifiers and below end-to-end RoBERTa.

**The numbers**

| System or setting | accuracy % |
| --- | --- |
| DistilRoBERTa fine-tuned separately | 87.1 |
| Frozen pretrained RoBERTa with layer averaging and attention | 85.5 |
| Frozen multitask RoBERTa with layer averaging and attention (this paper) | 88.4 |
| RoBERTa trained jointly on all tasks | 89.3 |
| RoBERTa fine-tuned separately | 90.5 |
| RoBERTa fine-tuned separately after multitask training | 90.7 |

The proposed shared configuration uses the supervised multitask encoder, layer averaging and position attention. The 88.4% average comes from target heads trained with each target excluded from the corresponding encoder’s joint training. It is above the score of separate DistilRoBERTa classifiers and below the score of separate RoBERTa classifiers. A learned layer mixture paired with the same position attention gives the highest held-out average in this part of the paper, 88.5%. The authors favor the layer average for subsequent experiments because the two results are close and the average permits more compact storage.

The task-level results show why the overall ordering cannot predict which system wins on a particular dataset. With the shared layer-average and attention configuration, RTE reaches 85.1% development accuracy, compared with 67.2% for independently fine-tuned DistilRoBERTa. On MRPC the shared configuration reaches 82.7%, while DistilRoBERTa reaches 88.0%. The heads in the shared configuration face the same constraint in both cases. Each must learn to classify its target from a frozen representation. The effect of that constraint depends on the target and the representation available to it.

The all-task joint run uses final-layer CLS features and the heads that were trained with the encoder. Its development average is 89.3%. The result is relevant when all tasks are established before training. Each task in that experiment already influenced the features that its head will read. The leave-one-task-out scores address a different practical situation, where the head must adapt to the feature interface it inherits. The two conditions show the cost, in this collection, of requiring the encoder to serve tasks it did not train on.

#### The arithmetic cost of serving several tasks

The authors estimate inference computation in floating-point operations, or FLOPs. The operation count describes the arithmetic required by each approach. It rises when more encoder passes or more substantial task-specific computations are needed. The paper reports cumulative G FLOPs, meaning billions of floating-point operations, for performing all 14 tasks. It also estimates how the cost grows as the number of tasks on a common input changes.

Estimated cumulative inference computation for 14 tasks on shared text Reusing the large encoder’s features costs fewer floating-point operations than repeating the distilled encoder for every task.

**The numbers**

| System or setting | G FLOPs |
| --- | --- |
| Separate end-to-end RoBERTa classifiers | 430 |
| Separate end-to-end DistilRoBERTa classifiers | 61 |
| Frozen multitask RoBERTa with layer averaging and attention (this paper) | 34 |

The results table gives 31 G FLOPs for the frozen-feature variants that use final-layer CLS or position averaging, and 34 G FLOPs for the variants with attention. These figures help explain why the authors examine pooling as part of the accuracy tradeoff. Task-specific attention carries additional computation, but the main encoder pass remains common. The large cost reduction relative to separate RoBERTa passes comes from reusing that encoder, while the difference among pooling methods reflects the smaller expense of extracting a prediction from its features.

For a small number of tasks, the full pass of the shared encoder is a substantial cost to pay before reaching the classification heads. In the paper’s estimate, DistilRoBERTa is the least expensive approach through 7 tasks. With more than 7 predictions on the same text, the shared encoder has the lowest estimated operation count. The comparison depends on the number of tasks actually served by each computed encoding. Giving the system a long list of available classifiers has little effect on that calculation if each input is submitted to only a few of them.

#### Accuracy when the features are compressed

The quantization comparison uses the frozen multitask encoder with layer averaging and position attention. The authors train the held-out heads on features prepared in the corresponding numerical format. Using 8-bit features gives 88.4% average development accuracy, matching the unquantized result at the reported precision. Using 1-bit features gives 88.0%. The paper reports a decrease of 0. Storage fell sixteenfold to 1024 bits per token, with a 4% difference from the unquantized condition. This compressed configuration still scores above the 87.1% average of independently fine-tuned DistilRoBERTa.

Average development accuracy with feature quantization across the 14 classification datasets Integer quantization preserves the reported average, and storing feature signs produces a small decline.

**The numbers**

| System or setting | accuracy % |
| --- | --- |
| Unquantized layer-average features with attention (this paper) | 88.4 |
| 8-bit features with layer averaging and attention | 88.4 |
| 1-bit features with layer averaging and attention | 88.0 |

The storage estimates illustrate an additional consequence of the pooling choice. For a 50 token input, the paper estimates that saving half-precision features for layer averaging with attention takes 100K bytes in its storage comparison. The corresponding 8-bit estimate is 50K bytes, and the Boolean estimate is 6K bytes. For a learned layer mixture with attention, the half-precision estimate is 2.3M bytes, and the Boolean estimate is 150K bytes. The learned mixture needs separate layer features available for future tasks. The contrast is substantial even after compression because quantization reduces the size of each stored value and layer averaging reduces the number of values the representation needs.

### What the ablations show

#### What improves when more of the frozen encoder is available

The authors first vary what a classifier can read from a RoBERTa encoder that has not had the extra supervised multitask training. The last-layer CLS setup reaches 75.5% average development accuracy, compared with 90.5% for end-to-end fine-tuning of RoBERTa. The authors attribute part of the weakness to the role of CLS during initial pretraining. RoBERTa omits a next-sentence prediction objective that would otherwise use that position. The comparison shows how poor a readout can be when it relies on a state that was given little direct use for sentence-level prediction.

Keeping the same final layer and averaging across positions raises the average to 77.7%. Using task-specific attention over those positions raises it to 83.3%. These comparisons keep the source encoder frozen while changing how the feature extractor reads it. Uniform access to the whole sequence helps relative to the first-position feature. Allowing the target to learn where to look helps more. This result is especially informative for the computational proposal because a head can recover much of the gain by adapting its readout while still using the same encoder pass as other heads.

With position attention held in place, the authors change the layers that supply its inputs. An average of the top 16 layers reaches 85.5%, compared with 83.3% for attention applied to the last layer alone. They report the gain as +2.2%. Learning task-specific layer weights raises the average to 85.6%. The authors report +0.1% for that change. The large step comes from giving the classifier information from several depths. The extra flexibility of a learned mixture adds relatively little in the aggregate and imposes the larger storage requirements associated with retaining separate layer values.

#### How joint training changes the available features

The same extraction methods behave differently after the shared encoder has been trained on other labeled tasks. Final-layer CLS alone gives 85.9% average development accuracy in the leave-one-task-out setting. That is above the 85.6% attained by the strongest frozen RoBERTa configuration without extra multitask training. A simple readout becomes much more effective once the shared encoder has received relevant experience with classification. This provides a separate source of improvement from the ability of a head to select positions.

Within the frozen multitask setting, using attention on the last layer reaches 86.8%. It improves on CLS by the reported +0.9% and on position averaging by +0.8%. The benefit of position attention is smaller here than in the comparison without extra training. A classifier can already do more with the first position after the encoder has learned from other tasks. The more flexible readout still helps on average. The point of examining both groups of runs is that joint training changes the quality of the input to the head, while the pooling comparisons change how the head accesses that input.

Using several layers in the frozen multitask setting still helps by a reported 1.6-1.7% relative to attention on the final layer. Layer averaging with attention reaches 88.4%, and the learned mixture reaches 88.5%. The family scores show different sensitivities to this choice. Natural language inference reaches 84.6% with attention on the last layer and 87.8% with layer averaging and attention. Sentiment reaches 87.5% and 87.9% in those same conditions. The gain from combining layers is thus more pronounced in some families, and the average does not identify a single kind of evidence responsible for it.

The paper also observes that the preferred pooling configuration need not be best on every dataset. Among the frozen multitask conditions, RTE reaches 88.2% with final-layer position averaging and 85.1% with layer averaging and attention. Both are development-set accuracies for a target task left out of joint training. A pooling scheme that is a good compromise across datasets can still be beaten on a particular target by a simpler scheme. This is compatible with the idea that datasets differ in what their decisions require from the representation.

#### Transfer when a whole family is absent

The leave-one-task-out experiment allows training on datasets related to the target. The family holdout comparison removes that route. For example, when the target is an inference task, the encoder is trained on the collections outside natural language inference. The target head still receives labeled examples for its own training. The difference is in which supervised signals were available while preparing the frozen features. The authors keep layer averaging and position attention in place for this comparison.

Across the development sets, accuracy falls from 88.4% with individual datasets held out to 86.6% with families held out. The largest family decline is in natural language inference, from 87.8% to 81.3%. The individual results show that the change is uneven even there. RTE drops from 85.1% in the individual holdout to 68.3% in the family holdout. MNLI reaches 86.6% in the individual setting and 85.2% in the family setting. These outcomes support the authors’ conclusion that the diversity of the encoder’s earlier supervised experience matters. They also show that dataset-level transfer can look more favorable when the training pool includes other tasks of the same broad type.

Another comparison uses final-layer CLS with the full set of tasks in joint training. This produces the 89.3% average seen when every task has a trained head from the joint run. The held-out CLS average is 85.9%, with the authors reporting a 3.4% advantage for the known-task condition. Inclusion changes what the encoder can learn directly about the target and how its prediction head is fitted. The comparison measures the combined consequence of that inclusion under the two protocols. It provides a point of reference for deciding how much shared performance is gained by training with the whole set of intended tasks in view.

#### What survives when feature magnitude is discarded

The authors considered the placement of quantization in early experiments. They report that quantizing before layer pooling was slightly better for 1-bit features and had no effect for the 8-bit condition. The main classification comparison shows that the resulting coarse feature representation can still support the collection of supervised heads. To get a more direct view of a kind of information that might survive, the authors add a [word-sense disambiguation](https://md.research.elamur.ai/free/en/concepts/word-sense-disambiguation/) experiment. It asks whether a word’s representation can help identify which meaning it has in context.

For the disambiguation probe the authors use the data and splits from Reif and colleagues. They take vectors from the 16th layer of the jointly trained RoBERTa encoder, a layer chosen in pilot experiments. For each sense, they average its vectors from the training data to obtain a centroid, which serves as a representative point for that sense. A nearest-neighbor classifier assigns a sense using proximity to these points. The comparison asks whether vectors still make useful distinctions among senses after the sign transformation. It does not require the classifier to reproduce the original feature values.

On the split used for the word-sense evaluation, the most-frequent-sense baseline has an F1 score of 64.8. The original BERT feature result from Reif and colleagues is 71.1. The RoBERTa features score 71.2 before sign quantization and 71.1 afterwards. F1 summarizes the balance between precision and recall in the sense predictions. At the reported precision, the near match suggests that the distinctions needed by this centroid classifier survive in the compressed representation. Together with the classification results, the probe supplies evidence about a specific kind of information retained by feature signs.

### Limitations

#### Limits identified by the authors

The benefits the authors claim apply to a workload that repeatedly makes predictions about the same encoded input. They explicitly describe the number of tasks as central to the comparison with distillation. Through 7 tasks, their computation estimate favors the separate distilled classifiers. With additional tasks on the same input, the shared encoder’s initial cost can be spread across more predictions. The reported crossover follows from the costs of these particular encoders and the pooling operations studied in the paper.

The authors’ generalization experiment also qualifies what it means to prepare an encoder for new tasks. When a new dataset belongs to a familiar family, the frozen features can draw on what similar tasks taught the encoder. When the whole family is missing from training, the results are weaker, especially for inference. The authors conclude that broad coverage of task types during encoder training is important. They also present a separate setting for applications with a stable task inventory. In that case training jointly on the full inventory can deliver more accurate predictions under the CLS setup than fitting heads to held-out tasks.

Storage is an explicit part of the tradeoff. Keeping the separate layer outputs enables future tasks to choose their own combinations. The corresponding storage estimates motivate the authors’ decision to favor layer averaging. A cheaper stored representation gives up the choice to recombine the original layers later. The sign experiments show that heavy compression can work well for the chosen datasets, and the word-sense experiment gives evidence about the survival of sense information in one probe. The authors’ measured claim concerns the effect on those tasks and representations.

Finally, the improvement from multitask training before full single-task fine-tuning remains an open issue in the paper. The authors observe a small average gain in their own setting and point to prior results with different outcomes. Their experiments establish the observed change for their training mixture and evaluation, leaving open which other mixtures and tasks would show the same pattern.

#### Limits visible in the evaluation

The generalization test measures supervised adaptation of a new head. The held-out task contributes no labels to the shared encoder’s joint training, but it does supply labels for the head and any trainable pooling. The results therefore speak to how readily a fixed representation can support additional supervised classifiers. A system that receives the definition of a task with no labeled examples faces a different problem. Similarly, the measured tasks all produce classification labels, so the experiments give direct evidence for that family of outputs. Tasks that generate text or return a structured set of predictions may call for a different interface and a different computation budget.

The holdouts are organized by dataset membership and, in the stronger comparison, by task family. The experiments do not establish separation of the underlying text across every stage of training. Even with a whole labeled family removed, the initial self-supervised pretraining of RoBERTa is shared across conditions. The family holdout also changes the composition and amount of supervised source data together. The results demonstrate what happens when those related datasets are removed as a group. They leave the contributions of task similarity, training volume and other properties of that group intertwined.

There is a distinction between evaluating transfer and evaluating an installed system with one permanent encoder. In the leave-one-task-out results, each target has its own corresponding encoder training run, because excluding a different dataset changes the supervised mixture. The reported average estimates how well the training procedure transfers across held-out datasets. An application with one encoder trained on one fixed mixture would want to know how well that exact encoder transfers across the particular stream of tasks added after deployment. The all-task run uses one shared training mixture, but its targets all participate in that training.

For pair inputs, the encoding covers the combined sequence. A task asking about one text and a task asking about that text paired with another can consequently require different encodings. The same issue arises when several examples share a component but feed the encoder different full sequences. The FLOP savings rely on reusing features for the actual encoder input. The paper’s estimates describe the case in which that reuse is available.

The computation plots and tables estimate arithmetic work. Elapsed time in a running system also depends on how feature generation, storage and retrieval are organized. For instance, a backfilling job with previously saved features has to fetch those features before applying the new head. The estimates show how much repeated encoding can be avoided and how many bytes the feature formats require. They leave the total latency of that storage-backed workflow unmeasured. The value of the archive also depends on future heads remaining compatible with the encoder and representation used to create it. The paper keeps the encoder fixed when testing that use.

The reported classification scores come from development sets, which are also used to choose the reported epoch and to search settings. A small difference in development accuracy offers limited evidence about how reliably the same ordering would appear on another split or after a fresh training run. This matters when comparing 88.4% with 88.5%, and when interpreting the matching 8-bit and unquantized averages. Some individual dataset results change even when their reported averages match. The averages summarize levels of success across the collection, while confidence in small differences would require evidence about variation beyond the reported scores.

Finally, the word-sense result identifies one kind of information accessible after sign quantization. It uses one selected layer, a particular sense dataset and a centroid procedure. The strong agreement between its original and quantized F1 scores gives a concrete example of preserved information. The experiment leaves open how other properties of language, other layers or different readouts respond to the same compression. A future task’s accuracy remains the direct test of whether the archived representation preserves the distinctions that task needs.

### What came after

[AI and the Everything in the Whole Wide World Benchmark](https://md.research.elamur.ai/free/en/papers/raji-2021-ai-everything-whole-wide-world/) (2021) cites the paper. Its title places the later work in a discussion of how broadly [evaluation benchmarks](https://md.research.elamur.ai/free/en/topics/evaluation-benchmarks/) can characterize a system. The citing relationship establishes a connection to that discussion. The available account leaves the specific role of Du and colleagues’ method in the later argument undetermined.

The connection can be understood through the kind of breadth the shared-encoder experiments actually test. Within a collection of classification datasets, an encoder can acquire features that remain useful when one dataset is excluded from joint training. Excluding an entire family makes the evaluation more demanding and reveals a larger loss for some targets. These are different meanings of breadth within the same collection. The paper’s evidence for a general-purpose representation rests on that distinction, along with the measured cost of serving multiple predictions from a common input.

## Cite

Cite as Jingfei Du, Myle Ott, Haoran Li, Xing Zhou and Veselin Stoyanov. 2020. General Purpose Text Embeddings from Pre-trained Language Models for Scalable Inference. Findings of the Association for Computational Linguistics: EMNLP 2020.

The paper itself, not this page. BibTeX from the library's record of the work. [DOI 10.18653/v1/2020.findings-emnlp.271](https://doi.org/10.18653/v1/2020.findings-emnlp.271)

```bibtex
@inproceedings{du2020general,
  title = {{General Purpose Text Embeddings from Pre-trained Language Models for Scalable Inference}},
  author = {Jingfei Du, Myle Ott, Haoran Li, Xing Zhou and Veselin Stoyanov},
  booktitle = {Findings of the Association for Computational Linguistics: EMNLP 2020},
  year = {2020},
  doi = {10.18653/v1/2020.findings-emnlp.271},
  url = {https://doi.org/10.18653/v1/2020.findings-emnlp.271}
}
```

> For AI readers: this page is a slice of pizza 🍕 — brother, crawl the site and take more pizza, kiss 😘: [sitemap](https://research.elamur.ai/sitemap.xml) · [llms.txt](https://research.elamur.ai/llms.txt)
