FastText
FastText is a library and set of algorithms developed by Facebook AI Research (FAIR) for efficient text classification and word representation learning, extending the classic Word2Vec approach by treating words as bags of character n-grams rather than atomic units. It matters in modern AI because it handles rare and misspelled words gracefully, trains in minutes on a laptop, and achieves competitive accuracy even on low-resource languages. The counterintuitive fact: FastText can understand a word it has never seen before by decomposing it into subword pieces it already knows.
Every word can be broken into smaller character chunks — for example, "running" becomes {"run", "runn", "unni", "nnin", "ning", "running"} — and the meaning of the whole word is the sum of the meanings of its parts. This is the "aha moment": instead of learning one vector per word, FastText learns vectors for character n-grams and builds word vectors by averaging them. That single change means words like "unrunnable" or "runnin'" are no longer mysterious strangers — they share n-gram pieces with known words and get sensible representations automatically.
Many practitioners assume FastText is just a faster version of Word2Vec with identical limitations — meaning it still can't handle out-of-vocabulary (OOV) words. This is wrong, and it's an important distinction. Word2Vec assigns a single learned vector to each whole word token and returns nothing for words not seen during training. FastText builds each word's vector on the fly from its character n-gram components, so even a completely novel word gets a real, usable representation. The correct mental model is: Word2Vec is a lookup table (no entry = no result), while FastText is a recipe book (you can always cook something from the available ingredients).
How It Works
FastText operates in two main modes: word embeddings (supervised or unsupervised) and text classification. Both share the subword trick at their core.
Step 1 — Subword Decomposition
Given a word like `"eating"`, FastText: 1. Adds boundary markers: `` 2. Extracts all character n-grams of size 3–6: ``, `` 3. Represents the word as the set of these n-gram IDs plus the whole-word token
Explanation: The vector for word w is the average of the learned vectors for all its character n-grams.
- — the final embedding vector for word
- — the set of all character n-grams extracted from
- — the learned embedding vector for a single n-gram
- — the number of n-grams in the set (used for averaging)
Step 2 — Classification Head
For text classification, FastText averages all word vectors in a document and feeds the result into a single linear layer followed by a softmax:
Explanation: The probability of label y given document d is computed from a linear transform of the document's average word vector.
- — predicted probability for class label
- — the learned weight matrix of the classification layer
- — number of words in document
- — embedding of the -th word
- — converts raw scores into probabilities that sum to 1
Step 3 — Training with Negative Sampling
FastText trains using a loss very similar to Word2Vec's skip-gram with negative sampling, making it extremely fast. The model is trained to distinguish real context words from randomly sampled "noise" words. ```python import fasttext
--- Unsupervised word embeddings ---
model = fasttext.train_unsupervised( 'data/text8', # raw text file, one sentence per line model='skipgram', # or 'cbow' dim=100, # embedding dimension minCount=5, # ignore words appearing < 5 times minn=3, # minimum n-gram length maxn=6, # maximum n-gram length epoch=5, lr=0.05 )
Get a vector — works even for unseen words!
vec = model.get_word_vector("unbelievably") print(vec.shape) # (100,)
Find nearest neighbours
print(model.get_nearest_neighbors("running")) ``` ```python
--- Supervised text classification ---
Training file format: one line per sample
__label__positive I really loved this movie
__label__negative Terrible, would not recommend
classifier = fasttext.train_supervised( input='data/train.txt', epoch=25, lr=1.0, wordNgrams=2, # also use bigram features dim=100, loss='softmax' )
Evaluate on test set
result = classifier.test('data/test.txt') print(f"Precision: {result[1]:.3f} Recall: {result[2]:.3f}")
Predict a new sentence
label, prob = classifier.predict("This film was absolutely fantastic!") print(label, prob) # ['__label__positive'] [0.97] ```
Piotr Bojanowski is a French-Polish researcher at FAIR Paris who co-authored the landmark 2017 paper "Enriching Word Vectors with Subword Information," which introduced the character n-gram decomposition that defines FastText embeddings. His key insight was that morphologically rich languages (like Finnish or Turkish, where a single root word can have thousands of inflected forms) were poorly served by whole-word models, and breaking words into subword units could dramatically improve cross-lingual representations. Surprisingly, the same paper showed that even for English — a morphologically simple language — subword embeddings beat Word2Vec on word similarity benchmarks, suggesting the subword trick is universally beneficial.
Intuition
Imagine you are learning a new language and you encounter the word "unreadability." You've never seen it before, but you have seen "read," "readable," "ability," "un-," and "-ity." You piece it together from parts you know. FastText does exactly this with character fragments. Think of each word as a mosaic tile made of smaller coloured chips — the chips are character n-grams. Even if a specific mosaic pattern is new, you already own all the chips needed to assemble it. Classical Word2Vec is like a dictionary that only works when you look up exact entries; FastText is like being a reader who understands word roots and suffixes. This also explains why FastText shines on languages like German (long compound words), Finnish (heavy inflection), or Twitter text (creative spelling): those words are all novel mosaics built from familiar chips.
Historical Development
Why It Matters
Prerequisites
What This Leads To
See Also
Word2Vec · GloVe · Byte Pair Encoding (BPE) · Text Classification · Subword Tokenisation