Elamur Research

FastText.zip: Compressing text classification models

Paper · 2016 · Armand Joulin, Edouard Grave, Piotr Bojanowski et al.

Summary

A classifier can sort an email quickly and still be too large to keep in memory on a phone. FastText.zip examines this problem for fastText, a system for text classification. FastText learns vectors for words and short sequences of words, then uses a second collection of vectors to turn the evidence in a document into label scores. Each prediction uses only a fraction of the available features, but the classifier needs to be ready for any feature it recognizes. With a large vocabulary and many possible labels, the two collections of vectors can occupy gigabytes.

The authors compress those vectors with product quantization. It replaces each piece of a vector with a reference to a representative shared by many vectors. Ordinary product quantization works poorly here because the learned vectors vary greatly in length, and fitting shared representatives can erase distinctions among short vectors. The authors encode length separately from direction, then retrain the label-scoring parameters while the compressed input vectors are held fixed. They also remove features whose learned vectors suggest a smaller contribution, making sure that the remaining vocabulary still gives the training documents something to work with. Hashing reduces the space needed to identify features. A Bloom filter saves more lookup space in the comparison, at a cost to classification performance.

Across the standard benchmarks, the authors report a typical reduction of two orders of magnitude in memory, with only a small decline in accuracy. Some configurations fit below 100kB. The bottom-up quantization procedure alone gives a reported compression factor of 10 without an appreciable accuracy change, while the extreme settings at 64KiB and 32KiB have average accuracy declines of around 0.8% and 1.7%, respectively. The compressed fastText configurations compare favorably with the character-based convolutional classifiers in the study, whose weights are left unquantized.

FlickrTag tests the approach on hashtag prediction with 312,116 possible labels. At the tested precision, compressing both the feature and output matrices gives a compression factor of 8 with no reported deterioration in performance. The same task exposes a different limit when the feature inventory is reduced. A ranking that keeps individually important features can leave many documents with no recognized evidence. Selecting features with document coverage in mind reduces that loss, although a tight enough budget still eliminates features that some documents need.

Deep dive: FastText.zip: Compressing text classification models

FastText.zip combines vector quantization, retraining and vocabulary pruning to cut the memory needed for text classification while preserving accuracy. · about 35 minutes to read

The problem and its context

Why fast prediction can still require a large classifier

The paper starts from familiar uses of classification. An email filter assigns a message to a category. A search or ranking system can use a classifier to make a decision about a piece of text along the way to producing a result. In these settings, accuracy describes whether the categorization is useful, while memory determines whether the classifier can be kept available on the system that has to run it. The authors use smartphones as an example of a setting where that second requirement is consequential.

The pressure on memory comes in part from the distinction between the features available to the classifier and the features active in a particular document. A message contains a limited collection of words and phrases. The classifier nonetheless needs representations for a much wider vocabulary across all messages it might receive. A short evaluation path through the classifier can therefore coexist with a large inventory of trained parameters. That inventory grows on the output side, too, if the set of possible categories is large. Hashtag prediction brings both kinds of growth into the same task.

The paper treats linear classification as a competitive starting point. It points to earlier results from scalable linear systems and emphasizes the value of choosing features that expose useful evidence. The background includes Joachims’s text categorization study and McCallum and Nigam’s comparison of naive Bayes event representations. A related example of the emphasis on features is Baselines and Bigrams.

An n-gram is a sequence of adjacent units of a chosen length. A single word can be evidence on its own, while a sequence can represent a combination that is informative as a unit. FastText exploits word and word-sequence features, which gives it access to such combinations and makes a learned inventory of them worth keeping. The storage problem follows naturally from this design. Every additional feature can bring another vector of learned values, even if it is consulted infrequently.

Character-based neural classifiers offered a different way to control that cost. Their smaller input units make a large word-level inventory less central to the architecture. The paper acknowledges the success of recurrent neural networks in other language applications, including speech recognition and machine translation. For the classification problems it discusses, the authors say that deeper systems had yet to show a decisive advantage over previous techniques across several tasks, while their training could be considerably slower. Compactness remained a reason to consider them, especially in the line of work represented by Zhang and colleagues’ character-level CNNs.

What earlier compression methods were designed to preserve

The paper draws a parallel with statistical language models. An n-gram system can become large because it records many sequences along with values associated with them. Earlier compression approaches operated on several parts of this representation. Pruning reduced the set of sequences. Quantization represented the values using a restricted set of possibilities. Trees and hash-based structures reduced the space taken by the sequences themselves. This background gives the authors distinct places to look for savings in fastText. A vocabulary entry needs an identity, space for its parameters and a reason to be retained in the first place.

A second line of work comes from similarity search. Suppose a system holds a collection of vectors and needs to identify the entries closest to a query vector. It can compress the stored entries, provided that comparisons made with their codes retain enough of the original geometry. A binary scheme discussed in the paper converts projections of each vector into bits. It estimates angular similarity from the number of bit positions at which two codes differ, a count called Hamming distance. The paper uses locality-sensitive hashing, or LSH, for this particular type of binary coding and traces it to Charikar’s work on similarity estimation.

Other methods in that line improve binary coding by choosing a more favorable coordinate system. The paper describes Iterative Quantization as learning a rotation to reduce the error of binarization. Product quantization, or PQ, uses learned representatives for pieces of a vector. It was developed for approximating distances with compressed representations. Its optimized variant, OPQ, learns a rotation to improve the fit of those pieces. The paper also places its work alongside neural-network compression in computer vision, where researchers had used vector quantization and methods such as Binarized Neural Networks.

FastText brings a different scoring requirement to these methods. Its output depends on inner products, which reflect both how vectors are oriented and how long they are. Two vectors can point in the same direction and yield different scores when compared with the same document representation. A code built around angles alone has no way to recover that difference without additional information. The authors discuss earlier hashing methods designed for maximum-inner-product problems, then take advantage of being able to store a separate magnitude code. They can apply techniques suited to unit-length vectors to the directions and still recover an approximation to the scale needed for label scoring.

The goal is to preserve the favorable training and prediction properties of a shallow classifier while making the entire trained system cheaper to retain. This gives a role to both sorts of earlier work. Vector compression addresses the numerical arrays. Feature selection and compact lookup address the number of entries and the means by which text refers to them. The task and the existing costs of the other components determine the importance of each component.

The method, step by step

Train the original classifier in a shared space

The procedure starts with ordinary supervised fastText training. A document supplies a collection of active features and a target label. A word or a sequence of words can activate a feature. Each feature has an identifier that can be represented as a one-hot vector, a vector with a unit entry at that feature’s position and zero elsewhere. The paper describes the document input as a bag of these vectors. A bag records the features without preserving their full order in the document. An active word sequence can still carry local order because its identity represents that sequence.

The first matrix maps the active features into a shared numerical space. Its learned feature representations include word embeddings and analogous vectors for word sequences. Combining the active representations supplies a document vector in that space. The second matrix uses it to score outputs. The paper writes the training objective as follows.

∑ₙ₌₁ᴺ ℓ(yₙ, BAxₙ)

The summation adds the losses for documents indexed by n, beginning at 1 and ending at N, the number of training documents. The argument xₙ is the bag of one-hot feature vectors for document n, and yₙ is its target label. A is the input matrix that produces an intermediate representation from the document features. B is the output matrix applied to that representation, so BAxₙ supplies the scores passed to ℓ. The function ℓ is the softmax classification loss. It measures the penalty associated with the scores given the document’s target.

This factorization imposes a low-rank structure. For a feature and label to interact, their respective parameters meet in the intermediate space rather than occupying an unrestricted table of feature-to-label coefficients. The same intermediate dimensions can carry evidence for different labels. This is especially helpful in the authors’ account when rare categories have little training data of their own. The reduced dimension also limits how much calculation is needed to combine input and output information. The dimensions on either side of the factorization still reflect the number of features and the size of the output space, so the two matrices remain the main subjects of numerical compression.

The paper treats feature selection and compact lookup as additions to this vector-compression procedure. The diagram shows the roles of the stages in the combined approach. The experiments also use subsets of them to measure particular effects.

Fitting and storing a compact fastText classifier

The steps in order.

Fitting and storing a compact fastText classifierStep 1: Fit fastText on labeled documents1. Fit fastText on labeled documentsStep 2: Select features with training coverage in mind2. Select features with training coverage in mindStep 3: Encode direction and magnitude separately3. Encode direction and magnitude separatelyStep 4: Hold the quantized input matrix fixed4. Hold the quantized input matrix fixedStep 5: Refit the output weights on compressed inputs5. Refit the output weights on compressed inputsStep 6: Quantize the refitted output weights6. Quantize the refitted output weightsStep 7: Store hashed feature lookup for prediction7. Store hashed feature lookup for prediction

Replace coordinates with references to representative pieces

A quantizer represents a range of possible inputs by a finite collection of output values. Applied to vectors, it maps each input to a representative vector, or centroid. A shared collection of centroids is called a codebook. A system can store the codebook once and represent many different inputs by indices into it. If each stored vector had to choose a single centroid for its entire set of coordinates, covering the different combinations found in a large collection could require a very large codebook. PQ makes the collection of possible full reconstructions large by learning smaller codebooks for separate pieces.

The paper starts with a vector in a real coordinate space.

x ∈ ℝᵈ

Here x is the vector being compressed, d is its number of coordinates, and ℝᵈ is the space of vectors with d real coordinates. The membership sign indicates that x belongs to that space. In fastText, vectors of this kind carry input or output parameters.

In ordinary PQ, groups of coordinates provide the pieces. The authors describe the partition using superscripts to identify the different groups.

x = [x¹ … xⁱ … xᵏ]

The vector x on the left consists of the subvectors in brackets on the right, in their original order. The superscripts identify groups. The first is x¹, xⁱ is the group with index i, and xᵏ is the final group. The ellipses stand for the intervening groups. The parameter k is the number of groups and thus also the number of subquantizers, since a separate quantizer handles each group. Each piece has the same width in this description.

d/k

The expression divides the original dimension d by the number of pieces k. Its value is the coordinate count in each piece. A subquantizer sees only these coordinates when it chooses a representative. A different subquantizer learns its own representatives from the coordinates assigned to it.

For each group, k-means fits a collection of centroids to the corresponding pieces of the vectors being compressed. Each piece is associated with its nearest centroid. The letter k in the name k-means conventionally refers to the number of clusters in that algorithm. In the paper’s PQ notation, k counts the subquantizers, while their codebook size is specified by a different parameter. The design allows repeated patterns in particular groups of coordinates to be shared even among vectors that differ greatly in other groups.

The reconstruction can also be expressed as a sum, with each selected centroid viewed as a contribution in the full coordinate space.

x̂ = ∑ᵢ₌₁ᵏ qᵢ(x)

The hat on x̂ marks the reconstructed approximation to x. The summation combines the outputs of the subquantizers from i equal to 1 through i equal to k. The function qᵢ selects the centroid for the part of x assigned to subquantizer i and places that contribution in its own subspace. Viewed in the full coordinate space of ordinary PQ, the contribution is zero outside that group of coordinates. Adding the contributions therefore has the same effect as putting the pieces side by side.

The paper characterizes the subspaces by their orthogonality.

∀ i ≠ j, ∀ x, y, ⟨qᵢ(x), qⱼ(y)⟩ = 0

The symbol ∀ means “for every.” The indices i and j indicate different subquantizers, as specified by ≠. The vectors x and y can be any inputs to the quantizers. The angle brackets denote the inner product between the chosen centroid contributions. The zero on the right expresses orthogonality. In coordinate-aligned PQ, the property follows because different pieces occupy disjoint groups of coordinates. OPQ learns an orthogonal rotation before partitioning. The groups are still orthogonal, but they now follow the axes of a learned coordinate system.

Account for the individual code and the shared codebooks

Each selected centroid is recorded by an index of b bits. The number of index values determines the number of centroids available in each group.

2ᵇ

The base 2 represents the two possible states of each bit. The exponent b is the bit count of a single index. Together they give the number of possible indices and, in the paper’s design, the size of each subquantizer’s codebook. The authors typically use b equal to 8, which gives 256 centroids and lets an index occupy a byte.

The amount of space taken by the set of indices for a vector is as follows.

kb

The product multiplies k, the number of groups, by b, the number of bits for each group’s selected centroid. It measures the bit count of the per-vector PQ code. The centroid values themselves are shared, and the compressed classifier still has to retain the codebooks. When magnitude is encoded separately, its code also goes beyond this count.

The possible combinations of those separate centroid choices form the implicit codebook for the full vector.

2ᵏᵇ

The base 2 again counts the states of a bit, and the exponent kb is the total number of bits in the indices. The expression counts the possible full reconstructions in the paper’s description. The system can produce them by choosing pieces from the small codebooks as needed. Enumerating all those full vectors would undo the economy of the representation.

The authors give a usual range for the number of subquantizers.

k ∈ [2, d/2]

The bracketed interval runs from 2 to half of d, the original vector dimension. The symbol ∈ indicates that k, the number of subquantizers, is chosen in that range in the usual setup. Since k also controls the number of bytes at the authors’ usual index width, moving along the range changes storage per vector. It changes what each codebook has to describe as well. A small number of groups leaves each codebook responsible for a larger part of the original vector. The extreme small-memory experiment later goes outside the usual range.

OPQ keeps the basic arrangement of groupwise coding. Its additional step seeks a rotation under which these individual codebooks fit the vectors with lower quantization error. This matters when meaningful variation in the original coordinates is poorly matched to a fixed partition. The classifier experiments can then ask whether changing the partition in this way has enough effect on the predictions to justify the extra work of fitting the rotation.

Preserve the quantity that the output uses

For scoring, the paper gives the inner product between the quantized reconstruction of an operand and another vector. With ordinary PQ, each part of the sum can use the centroid from the relevant codebook.

xᵀy ≈ x̂ᵀy = ∑ᵢ₌₁ᵏ qᵢ(xⁱ)ᵀyⁱ

The vectors x and y are the original operands. The superscript T denotes transpose, allowing the product to be written as a dot product. The vector x̂ is the reconstruction of x, so the approximation sign relates the original score on the left to the score obtained with that reconstruction. The equality gives the exact decomposition of the reconstructed score. The pieces xⁱ and yⁱ are the corresponding coordinate groups of x and y. In this expression qᵢ acts directly on piece xⁱ and returns its representative in the group. The summation adds those groupwise dot products for indices i from 1 through k.

The equality is useful because the stored code tells the classifier which centroid should participate for each group. It can also rebuild a vector by retrieving the centroids and concatenating them. The authors describe this reconstruction as having very little computational and memory overhead in their setting. The inner-product expression is about using an approximation to an operand. It gives a way to calculate its effect on a score, while the resulting label decisions remain a question for the experiments.

Give short vectors the same chance to retain their direction

The norm of a vector is its length. The paper reports a typical ratio of 1000 between the largest and smallest lengths in the collections under discussion. A centroid fit to the original coordinates uses an absolute-error objective. Assigning a short vector a representative near zero incurs little absolute error, while a similar loss of detail for a long vector can be expensive under the same objective. The fitted quantizer can consequently allocate its representatives in a way that treats many different short vectors as effectively identical.

The authors separate a vector into its magnitude and a direction scaled to unit length. The directional codebook is fitted to these unit vectors, so their original ranges of length no longer govern how well their directions can be represented. A separate quantizer stores the magnitude. Reconstruction uses the magnitude approximation to restore scale to the directional approximation. The scheme retains access to a quantity that matters for the inner product while exempting direction fitting from the original disparity in lengths.

This normalized form of PQ is called NPQ in the experiments. Its extra magnitude index requires b more bits per vector, where b is the width of a quantization index. In the byte-aligned configuration, the direction indices occupy one byte per group and the magnitude occupies an additional byte. The paper’s comparisons of accuracy against space per embedding count that extra byte. The cost pays for a different use of the codebook as well as an additional stored value, since the directional codebook now represents vectors on a common scale.

Let the output adapt to reconstructed inputs

After the input matrix A has been compressed, the output weights still reflect their original training conditions. They were fitted using the input vectors before those vectors were replaced by centroid-based approximations. The authors argue that the perturbation can have a systematic component. For a quantizer satisfying the Lloyd conditions, which describe consistent assignments and centroids, the average squared magnitude decreases by the average quantization error. This gives a reason to expect the scale of the information reaching the output to change.

The bottom-up procedure holds the quantized version of A fixed and fits B again on the representations it now receives. The classifier can adjust the label-scoring parameters to changes in the input features that remain distinguishable after coding. Once this adaptation is complete, the output matrix can itself be quantized. The order follows the direction of prediction through the classifier. The representation consumed by B is established before B is refitted.

This step uses the training task to compensate for the numerical approximation. A centroid fit minimizes a measure of vector error. Retraining uses the labels, so it can accommodate changes that turn out to matter to classification even if those changes were inexpensive under the vector objective. The procedure still relies on the compressed features carrying enough information to discriminate among labels. The paper’s comparisons include versions that skip retraining to measure what the adaptation contributes.

Prune weak features while giving documents a place in the decision

A smaller code for each vector still leaves the question of how many vectors are needed. The authors start from a trained classifier and look for a budgeted subset of words and n-grams to retain. Count alone is an unreliable importance score for this purpose. Frequent grammatical words can offer weak evidence about the label, and an uncommon expression can be informative in a tag prediction task. The authors use the learned vector’s norm as their score for a feature. This measures a property of the representation acquired during supervised training.

Selecting the highest scores globally can leave some documents with no active retained feature. Consider a document whose useful terms all fall just below the cutoff. Higher-ranked terms elsewhere in the collection provide it no evidence because it contains none of them. The authors formulate selection as a constrained optimization problem that takes this possibility into account.

maximize over 𝒮 ⊆ 𝒱   ∑ₛ∈𝒮 wₛ
subject to |𝒮| ≤ K and P𝟙(𝒮) ≥ 𝟙(𝒟)

The set 𝒱 contains the available features, and 𝒮 is a subset of them, as indicated by ⊆. The summation adds the weights wₛ of the features s belonging to 𝒮. Each weight is the norm of the feature’s embedding. The vertical bars in |𝒮| give the number of retained features, which must be at most K, the feature budget. The matrix P records feature occurrences across documents. The vector 𝟙(𝒮) has a unit entry for each selected feature and zero for the other features. The set 𝒟 contains the training documents, and 𝟙(𝒟) has a unit entry for every document. Multiplication by P counts retained features for each document, so the inequality ≥ requires those counts to reach the unit threshold in every row.

The paper defines each entry of the occurrence matrix through the presence of a feature in a document.

P[d,s] = 1 if feature s occurs in document d, and 0 otherwise

The brackets identify an entry in P. Within this formula, d is a document index and s is a feature index. The values 1 and 0 record presence and absence, respectively. Using a different role for d here than in the vector formulas follows the paper’s notation. The matrix definition makes the coverage constraint concern the existence of useful input, without weighting a document more heavily because it repeats a retained feature.

The formulation is related to set cover. Each feature can cover the documents in which it appears, and the aim is to select features within the budget while reaching all the training documents. The authors connect the problem to NP-hard optimization and discuss it as a constrained instance of online submodular maximization. A conventional greedy implementation can require multiple corpus passes or an inverted index, a structure for looking up the documents containing each feature. Both approaches can be costly at the scale the authors consider.

Their practical procedure works through documents and checks whether any feature already selected occurs in the current document. If none does, it adds the highest-norm feature available in that document. If the coverage pass leaves spare capacity, it fills that space with the highest-norm features still unselected. The authors describe the procedure as amenable to parallelization. The mathematical formulation specifies what a feasible subset should accomplish and what the objective rewards. The online procedure supplies an economical way to seek such a subset, with its choices guided by which documents are already covered as it goes.

Coverage protects the availability of evidence at the document level. A document covered by a single retained feature can still lose other terms that would have helped the classifier. The study therefore measures accuracy alongside coverage. A proposed subset can preserve the opportunity to score a document and still weaken the actual decision, which matters when reading the pruning results.

Identify retained features without storing their strings

FastText already uses hashing for word-sequence features. FastText.zip applies the same idea to words. A hash function maps a feature to a bucket index, allowing the classifier to use that index to locate parameters without carrying a dictionary of feature strings for this purpose. The paper attributes savings of around 1-2Mb to eliminating the explicit dictionary this way, with the hash computation as the main additional prediction-time work. The space saved becomes especially relevant once the vectors have themselves been reduced.

Pruning creates another lookup requirement. After mapping a feature to a bucket, the classifier needs to find out whether that bucket survived. The paper discusses keeping the indices of retained buckets in a sorted list. Binary search can narrow the range of candidate positions at each comparison.

O(log(K))

The symbol O describes how the search cost grows, log denotes a logarithm, and K is the number of retained bucket indices in this lookup discussion. The expression states that binary search grows logarithmically with that number. The list itself takes space, which the paper describes as a few hundred kilobytes.

A Bloom filter offers an approximate membership check. It uses hashed information to decide whether an item could belong to the retained set. The compact structure can admit a false positive, meaning that an item absent from the set can appear to be a member. For the membership operation, the authors give the following cost.

O(1)

Here O again describes how lookup cost scales, and 1 expresses constant scaling with respect to the size of the retained set. This comparison concerns the membership check. Prediction also requires using the features that emerge from lookup. The importance of evaluating that whole path becomes clear in the Bloom-filter experiment.

The paper identifies the fastText library as the home of the underlying classifier and announces an extension with code and scripts for reproducing the compression experiments. It also names Facebook Research’s fastText research site as the data location for FlickrTag.

Experiments and results

The comparisons move from vectors to whole classifiers

The authors train fastText using 2M buckets, a learning rate of 0.1 and 10 training epochs by default. They choose embedding dimensions that are powers of 2 to help avoid boundary effects from how vectors are partitioned. This establishes the reference configuration before applying the particular code widths, pruning budgets and lookup variants examined in the experiments. The benchmark protocol comes from Zhang and colleagues. It covers 8 datasets described as having a few million documents and at most 10 classes. Amazon full reviews also serves as the example in a separate analysis of feature rankings.

The initial compression baselines are LSH, PQ and OPQ without the full combination of adaptations. For LSH, the authors use random orthogonal matrices in place of ordinary random projections. The baseline thus includes an improvement specific to the binarization method. The OPQ comparison uses the non-parametric variant identified in the paper. These comparisons ask how well each representation supports the classification task under a budget for individual embeddings.

Later experiments measure the space taken by the trained classifier as a whole. They alter how many features are retained and compare compact fastText with full fastText and character-based systems. The latter include the convolutional classifiers used for the benchmark protocol and a design that combines convolutional with recurrent layers, described in Xiao and Cho’s character-level classification study. The resource question changes between the two kinds of comparison. A byte count per vector measures the precision budget for one part of the classifier. The full footprint reflects how many vectors survive and how the implementation reaches them.

The appendix gives additional setup details for individual comparisons. Its opening describes experiments with 1M n-gram buckets. The caption for the standard-quantization comparison specifies an original classifier with dimension 8 and 2M buckets and says the compared systems omit the dictionary. The Bloom-filter table uses NPQ with dimension 8 and 2 subquantizers. These details belong with their respective comparisons. In particular, a dictionary-free vector study and a measurement of prediction-time memory answer different questions.

Normalized codes retain benchmark accuracy at small widths

For the small benchmark tasks, the paper reports accuracy as a function of storage per embedding. The directional code uses one byte for every subquantizer in the compared PQ and OPQ configurations, with an additional byte when magnitude is stored separately. LSH appears in its normalized form because its binary codes are designed to retain a relationship to angles. Reporting the bytes alongside accuracy includes the overhead of preserving scale for the methods that code it separately.

Once the vectors are normalized, the authors describe both PQ and OPQ as nearly lossless in classification accuracy even with 4 subquantizers per embedding. They find that using half as many subquantizers as embedding coordinates works well and carry this setting into the subsequent small-benchmark experiments unless specified otherwise. The accuracy difference between normalized PQ and normalized OPQ is limited and varies by dataset. The authors settle on NPQ for the rest of the study because it is faster to fit.

The paper reports a compression factor of 10 for bottom-up PQ without a noticeable accuracy penalty. Without the adaptation pass, observed accuracy declines range from 0.1% to 0.5%, depending on the dataset and setting. These observations identify quantization as a substantial source of savings before feature removal. They also put the size of the adaptation effect in perspective. Many predictions survive direct coding, while retuning the output can matter when the goal is to bring the compressed classifier close to the original accuracy.

Feature removal extends the savings to tighter memory budgets

The authors vary the pruning cutoff after fixing the regular code width at half the embedding dimension. NPQ at that width gives a reported compression factor of 10 against full fastText. Decreasing the number of retained features takes the overall reduction as high as × 1,000 in the settings the authors describe, with accuracy falling only modestly in those comparisons. The upper end is specific to the setting and starting footprint. The operation behind it is the combination of fewer entries with a shorter numerical description of each entry.

The authors report that a smaller dictionary can also make prediction faster. The central comparisons still concern memory and accuracy. Default fastText can be larger than the unquantized character-based classifiers, while using NPQ puts fastText in a similar memory range and pruning can extend the saving. The appendix specifies that the reported CNN sizes assume float32 storage. The fastText sizes describe RAM used at test time. That distinction matters when comparing close configurations, since a parameter-based estimate and observed memory in use account for space in different ways.

The paper separately tests very small configurations using hashing, extreme pruning and only 1 subquantizer. For these settings it gives approximate average accuracy declines relative to the original classifiers. The result is a direct comparison of what happens when the whole representation is squeezed into a stricter size budget.

Average accuracy decline on the standard benchmarks under extreme compression

The tighter memory budget yields the larger average accuracy decline.

Average accuracy decline on the standard benchmarks under extreme compression64KiB fastText.zip (this paper): 0.864KiB fastText.zip (this paper)0.832KiB fastText.zip: 1.732KiB fastText.zip1.7
The numbers
System or settingaccuracy decline %
64KiB fastText.zip (this paper)0.8
32KiB fastText.zip1.7

The authors associate these configurations with a compression range of × 1,000-4,000. The averages summarize the benchmark behavior at the corresponding size settings. They do not give an accuracy for an individual dataset. The experiment is also a combined stress test. Its decline can reflect the loss of vocabulary entries, the coarser descriptions of surviving vectors and changes associated with hashed lookup. Separate comparisons in the paper are more informative about the contribution of any one component.

FlickrTag gives the output matrix a larger role

The large-label evaluation uses a hashtag prediction task derived from YFCC100M. FlickrTag has 312,116 labels. A minimum word count of 10 yields a dictionary of 1,427,667 words, and the authors use 10M buckets for n-grams. They use hierarchical softmax, which organizes output decisions hierarchically to handle the large label space. The output array is consequently a material part of the compression problem, alongside the large inventory of inputs.

The output-coding comparison uses embeddings of dimension 256 and sets the subquantizer count to half that dimension. It leaves out the text-specific reductions so that the effect of coding the matrices can be examined on its own. The table compares quantization conditions, with an option to encode magnitude separately and a condition that retrains the output after quantizing the input. The authors report a compression factor of 8 when both matrices are quantized, with performance matching the full classifier in the stated comparison. Without output retraining the performance is still only 0.2% away from that reference. The appendix discussion adds that using fewer subquantizers reduces performance substantially for a small further saving in memory.

These results address a narrower question than the headline reduction across the small benchmarks. They show that the classifier can compress the many output vectors along with its input vectors at a workable code width. They also establish a fully quantized reference for the FlickrTag pruning comparison. Changes in coverage in that comparison can be read against a system whose numerical representation has already been compressed.

Pruning changes which FlickrTag documents can be scored from features

The unpruned FlickrTag classifier already misses 11.6% of the test set because the documents have no usable words. The authors describe documents composed only of hashtags and documents containing only rare words as examples of this problem. This initial gap is important for interpreting the comparison. A pruning rule can preserve the coverage of the original classifier while some test documents still lack usable evidence.

With a naive selection of 1M features, about 30-40% of the FlickrTag test set goes uncovered. The paper compares entropy-based selection, norm-based selection and a method that takes coverage into account. For the coverage-oriented setting highlighted by the authors, choosing features on the training documents causes no further test coverage loss relative to the original system, and the associated performance decline is smaller. More aggressive pruning does eventually reduce coverage. The pattern shows how the same nominal feature count can have different consequences depending on whether selection protects documents as well as high-ranked entries.

FlickrTag thus puts two ways of running out of representational capacity in view. Shortening a vector’s code changes the description of evidence that remains available. Removing a feature can leave a document with no description through the retained vocabulary. The output-coding experiment addresses the former at a fixed feature inventory. The pruning comparison makes the latter visible by measuring test coverage alongside performance.

What the ablations show

The norm code and the rotation solve different problems

The comparisons among vector encoders help explain why a standard distance-coding method needs adjustment. Ordinary k-means can deliver a reasonable fit under its absolute-error objective while treating many short vectors alike. The normalized form changes the objective seen by the directional quantizer by giving every direction the same input length. The separately stored magnitude maintains access to the scale the classifier uses. The near-lossless accuracy reported for normalized PQ and OPQ at small widths is consistent with the authors’ diagnosis. It is the behavior of the complete directional and magnitude code that the accuracy comparison evaluates.

Rotation has a different function. OPQ can improve the coordinate system for partitioning vectors, regardless of how lengths are represented. Comparing it with ordinary PQ after normalization helps show whether that additional flexibility pays off once the scale problem has been addressed. The small and dataset-dependent differences are the basis for using the faster NPQ in subsequent experiments. The observed performance of NPQ supports a straightforward subspace partition in the reported settings. It leaves room for a different balance between fitting time and accuracy on a collection with different vector geometry.

The LSH comparison adds a baseline originally intended to preserve angles through binary codes. Its normalization matters for interpreting the comparison. It is being used under conditions suited to its geometric target, and with an improved projection construction. The experiment asks how useful it is for the same classifier at a comparable vector budget. The choice of NPQ reflects the classification results of the coding alternatives and the authors’ preference for its fitting cost once a learned rotation offers little additional accuracy.

Retraining isolates the effect of an output fitted before compression

The retraining comparison keeps the compressed input representation and changes how the subsequent layer is fitted. This is valuable because aggregate reconstruction error gives no direct account of how well existing label weights will work with new inputs. The comparison shows that passing reconstructed feature vectors through the original output layer is often viable to begin with. Refitting the output reduces the remaining accuracy penalty enough to make bottom-up training worthwhile in the authors’ procedure.

FlickrTag provides a related test where the output matrix also matters for storage. The good performance after both matrices are coded shows that the output weights can survive quantization in the chosen configuration. The comparison that omits retraining supplies evidence that the final result does not depend on a large recovery obscuring a much larger initial collapse. At the tested width, the direct variant is close to the original, and the adapted version reaches the reported full-classifier performance. The finding about shorter codes shows the limits of relying on that outcome at lower precision.

Coverage loss is outside what this retraining comparison can repair. When an input vector shifts after coding, the output can learn how to interpret it in its new form. When a document loses every active feature, training the output cannot recover document-specific distinctions from those missing entries. That is why the feature-selection analysis needs an additional metric. The accuracy result from retraining tells us that the downstream parameters can adapt to changed numerical evidence. The coverage result concerns whether any such evidence arrives.

Ranked features and covered documents provide different evidence

The authors compare entropy and norm rankings on Amazon full reviews. The table examines which words appear near the top under each criterion and shows their rank under the other criterion as well. The authors interpret the norm ranking as filtering out words that carry little information for the classification task. This is a qualitative analysis of the features favored by each criterion. It helps explain what the norm is doing in the trained classifier, while the pruning sweeps measure how the rankings affect predictive performance.

FlickrTag brings the effect of selecting for coverage into a more direct comparison. A global ranking can spend much of its budget on words that occur in the same well-represented parts of the corpus. Each selection may look sensible in isolation. After several such selections, the next high-ranked word may serve documents that already have surviving evidence, while a lower-ranked word could preserve the only usable feature in a different document. The coverage-oriented pass gives the latter decision a role in selection.

The authors build that pass from training examples and then measure what happens to test coverage. The absence of further coverage loss in the reported test setting is an empirical finding about how well the chosen features carry over. The selection objective contains no constraint on unseen documents. Its useful behavior on FlickrTag shows that enforcing coverage during selection can improve the result beyond the mere choice of ranking statistic. The deterioration under more severe pruning shows that the empirical benefit depends on giving the feature set enough room.

The Bloom-filter comparison examines a cost outside the weight matrices

The Bloom-filter experiment compares lookup structures after hashing and pruning have made membership in the retained set a distinct operation. The filter saves a few hundred kilobytes and offers the constant lookup scaling discussed by the authors. In their tests, classification performance degrades. Since the filter can accept a bucket that would be excluded by exact membership, there is a way for a change in lookup to alter the evidence handled by prediction. The reported comparison establishes the performance cost for the tested setup. It gives no breakdown of individual classification errors by lookup outcome.

This negative result has a different role from the code-width comparison. A code-width change alters what a retained vector represents. A membership change affects which features make it to that point. Both can save space that matters for the complete artifact, and both can affect the final scoring procedure. The tests show why a comparison of the sizes of the underlying data structures alone would miss a practical consequence of replacing the exact list.

The comparisons as a whole identify several mechanisms without holding every component fixed across every task. The small-benchmark coding experiments emphasize precision. The extreme configurations combine space-saving measures. FlickrTag varies output coding and examines feature retention separately. The resulting evidence explains why particular design choices were made and reveals several ways compression can fail. The experiment grid leaves interactions between some of those choices unresolved.

Limitations

Limits identified by the authors

The authors explicitly leave equivalent compression of the CNN baselines outside their study. The cited character-based classifiers make a relevant comparison because compactness was one of their attractions. Their reported footprints reflect the storage conventions of that comparison and their weights are left unquantized. The paper establishes the advantage of FastText.zip over the evaluated alternatives at particular operating points. A comparison in which both families receive comparable compression remains open.

The authors also identify coverage as a limit on feature removal. FlickrTag has uncovered test documents before pruning, and the authors show that the problem worsens at severe cutoffs even with coverage-oriented selection. They propose combining entropy and norm information in future work to seek features that occur often enough to provide coverage and are strong enough to support discrimination. The reported comparisons test the criteria and the coverage heuristic, leaving this combined criterion as a proposal.

Two other suggestions address capacity at a finer level. The authors consider giving vectors different widths based on frequency or norm, with rare FlickrTag labels as an example where a full vector may be an expensive allocation. They cite earlier work such as Efficient Softmax Approximation for GPUs. They also suggest replacing some removed words with smaller units, for instance character trigrams, to preserve a route to feature evidence on very short inputs. The paper presents both as opportunities for additional study. Its reported configurations use the coding and pruning procedures already described.

Limits visible in the optimization and measurements

The theoretical observations about PQ concern vector approximation. A bound tied to reconstruction error helps explain how compressed vectors can support approximate similarity computations. Classification involves decisions made from potentially close scores. Even a small numerical error can change which label wins when the original scores are close, and a larger error can leave the label unchanged when the separation is wide. The accuracy experiments measure how these effects play out together. The geometric argument alone cannot specify that outcome.

The vocabulary argument has a similar gap between an intermediate measurement and the final task. Norm is a heuristic for the usefulness of a feature. Coverage counts whether there is some retained evidence. Neither measures whether the evidence is sufficient or whether it has the same relationship to the label as the original collection of features. The greedy selector can also depend on the documents it encounters and on the number of choices available when it gets to them. The stated constrained optimization defines an ideal solution. The practical algorithm is evaluated by the classifier and coverage it produces, with no certificate of optimality for that selection.

The benchmark sizes and averages leave several questions about the distribution of performance unresolved. Similar aggregate accuracy can conceal changes in which examples the classifier gets right. The sample of standard tasks has comparatively few labels, while the large-label experiment comes from a particular hashtag corpus with a known source of missing input. The results characterize these tasks and training conditions. They provide no measurement of how the same budgets fare when documents become substantially shorter, rare features carry different kinds of evidence or label distributions shift.

Storage and speed claims also have different evidentiary boundaries. The paper gives a concrete test-time RAM convention for fastText, while the CNN figures assume float32 storage. The experiments compare several memory settings and describe favorable reconstruction and lookup costs. They do not establish an end-to-end latency or energy result across the devices that motivate the work. On a given system, how the codebooks, retained indices and prediction process use memory can matter independently of the size of the trained representation.

Finally, the standard fastText architecture gives bottom-up retraining a clear sequence of operations. There is an input matrix to freeze and a following output matrix to refit. The study does not demonstrate which parameters to freeze or how to allocate code width in a system with additional interacting layers. Even for fastText, the paper’s separate sweeps do not derive an optimal allocation of a fixed memory budget between the precision of the surviving vectors and the size of the vocabulary. The experiments show how sharply each choice can matter and why a result for one operating point cannot decide the allocation for another.

What came after

Later work changed what could be reduced

Reducing Transformer Depth on Demand with Structured Dropout cites FastText.zip in work centered on an adjustable depth. The title identifies the mechanism as structured dropout and the resource decision as how much of the depth to retain on demand. This is a different object of intervention from a bank of feature vectors. FastText.zip asks how to retain a useful scoring function with a compressed representation of its inputs and weights. Adjustable depth asks how much of an architecture needs to be used. The citation connects research on those resource decisions. It does not specify a transfer of quantization or of the bottom-up training procedure.

Block Pruning for Faster Transformers names blocks as the units of pruning and speed as the objective. In FastText.zip, a pruned item is a feature that would otherwise supply input evidence, and a document can go uncovered when its last such feature is removed. Block pruning addresses a structural unit of the computation. The common concern is how much a system can discard while retaining useful behavior. The citation identifies that connection without establishing that the later work uses embedding norm or document coverage to select what to remove.

Corpus work cites the paper in a different setting

CCNet concerns obtaining high-quality monolingual data from web crawls. The resource problem in FastText.zip is the memory cost of keeping a text classifier available. The subject of CCNet is the preparation of a text collection, so its citation places the classifier paper in a data-processing context. Its title and citation do not identify a compressed classifier configuration or a particular step in which the quantization is used.

Quality at a Glance cites FastText.zip in an audit of web-crawled multilingual datasets. Auditing the resulting data is a different endpoint from judging whether a compressed classifier predicts accurately. The connection is pertinent to the meaning of coverage. In FlickrTag, a document is covered when it has a retained feature, a condition that says little by itself about the correctness of its classification. The audit’s title concerns the quality of datasets, a broader object than retained-feature coverage. The citation does not specify which part of FastText.zip bears on that audit.

FineWeb also cites the paper in work on web text at scale. FineWeb2 identifies the adaptation of a data-processing pipeline to different languages as its subject. Together with CCNet, these papers show that the citation extends beyond studies whose primary aim is reducing the size of a predictor. Their stated contributions concern assembling text or adapting its processing. The citation relationship alone leaves the specific role of hashing, vector coding or feature selection undetermined.

The later efficiency papers and corpus papers thus offer different kinds of continuity. The former explicitly name other units of resource reduction, such as depth and blocks. The latter place the citation in the context of preparing or assessing text collections. FastText.zip supplies a documented result about what happens when a classifier’s numerical precision and available text features are constrained. The listed later contributions establish where that result was cited, with the extent of direct adoption of its compression procedure left unspecified.

 Fields, topics and concepts

 Shelves 4The field of science this work belongs to (OpenAlex fields).Computer Science · 19,503 worksArtificial Intelligence · 18,805 worksArts and Humanities · 17,959 worksLanguage and Linguistics · 17,789 works

 Topics 1Research subjects and languages the work is about.Efficient models & compression · 328 works

 Concepts 2Key ideas and methods explained on our concept pages.Text classification · 50 worksWord embeddings · 30 works

Cite

Cite as Armand Joulin, Edouard Grave, Piotr Bojanowski, Matthijs Douze, Hérve Jégou and Tomas Mikolov. 2016. FastText.zip: Compressing text classification models. arXiv:1612.03651.

The paper itself, not this page. BibTeX from the library's record of the work. DOI 10.48550/arxiv.1612.03651 · arXiv 1612.03651

@misc{joulin2016fasttext,
  title = {{FastText.zip: Compressing text classification models}},
  author = {Armand Joulin, Edouard Grave, Piotr Bojanowski, Matthijs Douze, Hérve Jégou and Tomas Mikolov},
  year = {2016},
  doi = {10.48550/arxiv.1612.03651},
  eprint = {1612.03651},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.48550/arxiv.1612.03651}
}

References

43 references, from the paper's own bibliography.

  1. Alekh Agarwal, Olivier Chapelle, Miroslav Dudík, and John Langford. A reliable effective terascale linear learning system. Journal of Machine Learning Research, 150 (1):0 1111–1133, 2014. OpenAlex ↗ · Scholar ↗
  2. Francis Bach, Rodolphe Jenatton, Julien Mairal, and Guillaume Obozinski. Optimization with sparsity-inducing penalties. Foundations and Trends® in Machine Learning, 40 (1):0 1–106, 2012. OpenAlex ↗ · Scholar ↗
  3. Ashwinkumar Badanidiyuru, Baharan Mirzasoleiman, Amin Karbasi, and Andreas Krause. Streaming submodular maximization: Massive data summarization on the fly. In SIGKDD, pp. 671–680. ACM, 2014. OpenAlex ↗ · Scholar ↗
  4. Mohammad Hossein Bateni, Mohammad Taghi Hajiaghayi, and Morteza Zadimoghaddam. Submodular secretary problem and extensions. In Approximation, Randomization, and Combinatorial Optimization. Algorithms and Techniques, pp. 39–52. Springer, 2010. OpenAlex ↗ · Scholar ↗
  5. Moses S. Charikar. Similarity estimation techniques from rounding algorithms. In STOC, pp. 380–388, May 2002. our card
  6. Welin Chen, David Grangier, and Michael Auli. Strategies for training large vocabulary neural language models. arXiv preprint arXiv:1512.04906, 2015. OpenAlex ↗ · Scholar ↗
  7. Flavio Chierichetti, Ravi Kumar, and Andrew Tomkins. Max-cover in map-reduce. In International Conference on World Wide Web, 2010. OpenAlex ↗ · Scholar ↗
  8. Matthieu Courbariaux, Itay Hubara, Daniel Soudry, Ran El-Yaniv, and Yoshua Bengio. Binarized neural networks: Training neural networks with weights and activations constrained to +1 or -1. arXiv preprint arXiv:1602.02830, 2016. OpenAlex ↗ · Scholar ↗
  9. M. Datar, N. Immorlica, P. Indyk, and V.S. Mirrokni. Locality-sensitive hashing scheme based on p-stable distributions. In Proceedings of the Symposium on Computational Geometry, pp. 253–262, 2004. OpenAlex ↗ · Scholar ↗
  10. Scott Deerwester, Susan T Dumais, George W Furnas, Thomas K Landauer, and Richard Harshman. Indexing by latent semantic analysis. Journal of the American society for information science, 1990. OpenAlex ↗ · Scholar ↗
  11. Misha Denil, Babak Shakibi, Laurent Dinh, Marc-Aurelio Ranzato, and Nando et all de Freitas. Predicting parameters in deep learning. In NIPS, pp. 2148–2156, 2013. OpenAlex ↗ · Scholar ↗
  12. Uriel Feige. A threshold of ln n for approximating set cover. JACM, 450 (4):0 634–652, 1998. OpenAlex ↗ · Scholar ↗
  13. Tiezheng Ge, Kaiming He, Qifa Ke, and Jian Sun. Optimized product quantization for approximate nearest neighbor search. In CVPR, June 2013. OpenAlex ↗ · Scholar ↗
  14. Yunchao Gong and Svetlana Lazebnik. Iterative quantization: A procrustean approach to learning binary codes. In CVPR, June 2011. OpenAlex ↗ · Scholar ↗
  15. Yunchao Gong, Liu Liu, Ming Yang, and Lubomir Bourdev. Compressing deep convolutional networks using vector quantization. arXiv preprint arXiv:1412.6115, 2014. OpenAlex ↗ · Scholar ↗
  16. Edouard Grave, Armand Joulin, Moustapha Cissé, David Grangier, and Hervé Jégou. Efficient softmax approximation for gpus. arXiv preprint arXiv:1609.04309, 2016. our card
  17. Song Han, Huizi Mao, and William J Dally. Deep compression: Compressing deep neural networks with pruning, trained quantization and huffman coding. In ICLR, 2016. OpenAlex ↗ · Scholar ↗
  18. Hervé Jégou, Matthijs Douze, and Cordelia Schmid. Hamming embedding and weak geometric consistency for large scale image search. In ECCV, October 2008. OpenAlex ↗ · Scholar ↗
  19. Hervé Jegou, Matthijs Douze, and Cordelia Schmid. Product quantization for nearest neighbor search. IEEE Trans. PAMI, January 2011. OpenAlex ↗ · Scholar ↗
  20. Thorsten Joachims. Text categorization with support vector machines: Learning with many relevant features. Springer, 1998. our card
  21. Armand Joulin, Edouard Grave, Piotr Bojanowski, and Tomas Mikolov. Bag of tricks for efficient text classification. arXiv preprint arXiv:1607.01759, 2016. OpenAlex ↗ · Scholar ↗
  22. Yann LeCun, John S Denker, and Sara A Solla. Optimal brain damage. NIPS, 2:0 598–605, 1990. OpenAlex ↗ · Scholar ↗
  23. Zhouhan Lin, Matthieu Courbariaux, Roland Memisevic, and Yoshua Bengio. Neural networks with few multiplications. arXiv preprint arXiv:1510.03009, 2015. OpenAlex ↗ · Scholar ↗
  24. Andrew McCallum and Kamal Nigam. A comparison of event models for naive bayes text classification. In AAAI workshop on learning for text categorization, 1998. our card
  25. Lukas Meier, Sara Van De Geer, and Peter Bühlmann. The group lasso for logistic regression. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 700 (1):0 53–71, 2008. OpenAlex ↗ · Scholar ↗
  26. Tomas Mikolov. Statistical language models based on neural networks. In PhD thesis. VUT Brno, 2012. OpenAlex ↗ · Scholar ↗
  27. Tomas Mikolov, Ilya Sutskever, Anoop Deoras, Hai-Son Le, Stefan Kombrink, and J Cernocky. Subword language modeling with neural networks. preprint, 2012. OpenAlex ↗ · Scholar ↗
  28. Behnam Neyshabur and Nathan Srebro. On symmetric and asymmetric lshs for inner product search. In ICML, pp. 1926–1934, 2015. OpenAlex ↗ · Scholar ↗
  29. Mohammad Norouzi and David Fleet. Cartesian k-means. In CVPR, June 2013. OpenAlex ↗ · Scholar ↗
  30. Bo Pang and Lillian Lee. Opinion mining and sentiment analysis. Foundations and trends in information retrieval, 2008. OpenAlex ↗ · Scholar ↗
  31. Alexandre Sablayrolles, Matthijs Douze, Hervé Jégou, and Nicolas Usunier. How should we evaluate supervised hashing? arXiv preprint arXiv:1609.06753, 2016. OpenAlex ↗ · Scholar ↗
  32. Jorge Sánchez and Florent Perronnin. High-dimensional signature compression for large-scale image classification. In CVPR, 2011. OpenAlex ↗ · Scholar ↗
  33. Anshumali Shrivastava and Ping Li. Asymmetric LSH for sublinear time maximum inner product search. In NIPS, pp. 2321–2329, 2014. OpenAlex ↗ · Scholar ↗
  34. Andreas Stolcke. Entropy-based pruning of backoff language models. arXiv preprint cs/0006025, 2000. OpenAlex ↗ · Scholar ↗
  35. David Talbot and Thorsten Brants. Randomized language models via perfect hash functions. In ACL, 2008. OpenAlex ↗ · Scholar ↗
  36. Bart Thomee, David A Shamma, Gerald Friedland, Benjamin Elizalde, Karl Ni, Douglas Poland, Damian Borth, and Li-Jia Li. Yfcc100m: The new data in multimedia research. In Communications of the ACM, 2016. our card
  37. Jingdong Wang, Heng Tao Shen, Jingkuan Song, and Jianqiu Ji. Hashing for similarity search: A survey. arXiv preprint arXiv:1408.2927, 2014. OpenAlex ↗ · Scholar ↗
  38. Jun Wang, Wei Liu, Sanjiv Kumar, and Shih-Fu Chang. Learning to hash for indexing big data - A survey. CoRR, abs/1509.05472, 2015. OpenAlex ↗ · Scholar ↗
  39. Sida Wang and Christopher D Manning. Baselines and bigrams: Simple, good sentiment and topic classification. In ACL, 2012. our card
  40. Kilian Q Weinberger, Anirban Dasgupta, John Langford, Alex Smola, and Josh Attenberg. Feature hashing for large scale multitask learning. In ICML, 2009. OpenAlex ↗ · Scholar ↗
  41. Yair Weiss, Antonio Torralba, and Rob Fergus. Spectral hashing. In NIPS, December 2009. OpenAlex ↗ · Scholar ↗
  42. Yijun Xiao and Kyunghyun Cho. Efficient character-level document classification by combining convolution and recurrent layers. arXiv preprint arXiv:1602.00367, 2016. our card
  43. Xiang Zhang, Junbo Zhao, and Yann LeCun. Character-level convolutional networks for text classification. In NIPS, 2015. our card

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/joulin-2016-fasttext-zip-compressing-text-classification/