Algorithmadvanced
Subword information skip-gram
Also called fastText embeddings, character n-gram embeddings.
Skip-gram in which a word vector is the sum of the vectors of its character n-grams, so rare and unseen words still get vectors.
- Time
- O(T N C (k + G) d) worst
- Space
- O((V + B) d) extra
- Where
- B = the number of hash buckets; C = the window radius; G = the largest number of n-grams of a word; N = the number of tokens in the corpus; T = the number of epochs; V = the vocabulary size, the number of types; d = the dimension of the vectors; k = the number of noise words per pair
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Piotr Bojanowski, Edouard Grave, Armand Joulin, Tomas Mikolov, 2017
The subword information skip-gram learns word vectors from the character n-grams inside each word. A word is the set of its character n-grams, for from 3 to 6, taken from the word with a boundary symbol added at each end, plus the word itself. Each n-gram has its own vector, and the vector of the word is the sum of the vectors of its n-grams. The model is then trained like the skip-gram model with negative sampling. Words that share pieces, such as "walk", "walked" and "walking", share parameters, so rare words get better vectors, and a word never seen in training still gets a vector from its n-grams. Bojanowski, Grave, Joulin and Mikolov (2017) proposed it and released it in the fastText library. To keep the memory fixed, the n-grams are hashed into a fixed number of rows.
In plain words
A normal word vector model learns one vector per word and knows nothing about a word it has never seen. It also learns "walking" and "walked" as two unrelated words.
This method looks inside the word. It cuts the word into short overlapping pieces of three to six letters, with a marker for the start and the end of the word, and it learns a vector for each piece. The vector of a word is the sum of the vectors of its pieces and of the word itself.
Training is the same game as in skip-gram: tell real neighbor words from random ones. Because related words share pieces, what the model learns from one helps the others. A new word, such as a misspelling or a rare form, gets a vector from the pieces it shares with known words.
The problem
The input is a corpus of tokens, the window radius , the number of noise words, the dimension , the n-gram lengths from to and the number of hash buckets. For a word , let be the list of the rows of the input matrix that belong to : the row of itself if is in the vocabulary, and the row of each character n-gram of the string "<" ">". The score of a word and a context word is
and the loss of an observed pair with noise words is the negative sampling loss . The output is , from which any word, seen or not, gets the vector .
The boundary symbols make prefixes and suffixes different from the same letters inside a word: the word "her" is the sequence <her>, which differs from the trigram "her" of "where". The paper uses from 3 to 6 and million, and hashes with the FNV-1a hash.
The algorithm
SUBWORD-SKIP-GRAM(corpus, C, k, d, T, η, n_min, n_max, B)- 1
for each word w: G_w ← its own row, then |V| + FNV-1a(g) mod B for each n-gram g of <w> - 2
Z ← small uniform random values, (|V| + B) rows; the context vectors v ← 0 - 3
for each epoch and each window pair (w, c) with noise words n_1..n_k do h ← Σ_{g ∈ G_w} z_g - 4
for each (x, y) in (c, 1), (n_1, 0), ..., (n_k, 0) do - 5
s ← h · v_x - 6
e ← σ(s) - y - 7
g_h ← g_h + e v_x; v_x ← v_x - η e h - 8
for each g in G_w do z_g ← z_g - η g_h ▷ every n-gram row gets the same step - 9
return the vector Σ_{g ∈ G_w} z_g for any word w
Line L1 builds the list of rows of each word once. Line L2 makes one row for each word of the vocabulary and one for each bucket; buckets that no n-gram reaches stay at their random start and are never used. Lines L3 to L7 are the negative sampling step with the sum in place of the word vector. Since depends on the rows of only through their sum, the gradient with respect to each of them is the same vector , and line L8 applies it to every row. A row that occurs twice in gets the step twice. Line L9 works for a word outside the vocabulary: its list has no own row, only the n-gram rows.
Example
The word "where" becomes <where>. Its 14 n-grams, by start position, are
<wh, <whe, <wher, <where, whe, wher, where, where>, her, here, here>, ere, ere>, re>
and with its own row, "where" has 15 rows. Its trigrams are <wh, whe, her, ere and re>, the example of Bojanowski et al. A word of characters has n-grams, so a long word has about .
The hash maps each n-gram to a bucket. With the sign quirk of the library described under Pitfalls, FNV-1a gives
| n-gram | FNV-1a (hex) | bucket for |
|---|---|---|
| <wh | 3e79c4e4 | 167652 |
| whe | 34f43a4d | 420941 |
| her | f4b48d8c | 1473420 |
| ere | 7b978ac9 | 1529033 |
| re> | 7af4dc2a | 867498 |
<her> |
65814d14 | 972692 |
The trigram "her" of "where" and the word "her" (the sequence <her>) get different rows. The word "her" also has the trigram "her" (from <her>), so the two words share that row.
On a planted corpus whose words in one group all start with "pak" and in the other with "zot", trained with n-grams of length 3 and 4, the unseen word "pakar" gets a vector closer to the mean of the "pak" group than to the mean of the "zot" group, through the shared n-grams "<pa", "<pak" and "pak".
Correctness
The claims are about what each line computes; the training itself has no guarantee of a global optimum. Line L1 lists exactly the substrings of "<" ">" of length to , one per start position and length, and maps each to a row in . Lines L5 to L8 compute the exact gradient of the negative sampling loss of the pair, because and is the identity for each occurrence of in . The vector of line L9 is defined for every word with at least one character, because "<" ">" then has length at least 3 and so at least one trigram. The full proof is in the proof file.
Proof: The subword skip-gram lists the right n-grams, takes exact gradient steps and gives every nonempty word a vectorfull
The training minimizes a nonconvex loss by stochastic gradient descent, so there is no claim of a global optimum. We prove what each line computes: the rows of a word (line L1), the gradient used in a training step (lines L3 to L8), and the existence of the output vector (line L9).
Notation. For a word of characters, let $s = $ "<" ">", a string of length . Let be the vocabulary, with words numbered to , and the number of buckets. The row list is the own row of if , followed by for each n-gram in the order of line L1, where is the hash. The vector of is , a sum over the list, so a row that occurs twice counts twice.
Claim 1. Line L1 lists each n-gram occurrence once and maps it to a bucket row.
The loop takes each start position and each length with , and emits . A substring occurrence of is fixed by its start and its length, so each occurrence of length to is emitted exactly once. For a fixed , the starts are , so there are of them, and the total is . For "where" () and from 3 to 6 this is .
The hash is a nonnegative integer, so , and the row lies in . These rows are disjoint from the own rows , so an n-gram never shares a row with a whole word.
Claim 2. Lines L3 to L8 take an exact gradient step of the pair loss.
Fix a pair with noise words , and write , , and , . The loss is
For one term with , the derivative of is and that of is . Both are , which line L6 computes. By the chain rule,
Line L7 accumulates from the values of before their own update, and moves by . A noise word that appears twice is moved twice, which matches the sum over with .
The loss depends on the rows only through . If row occurs times in the list, then , so . Line L8 runs over the list and subtracts once per occurrence, that is in total. All of , and are computed at the parameters before the step, so the step is in the context vectors and the rows of , and every other parameter has zero gradient and does not move.
For a small enough , such a step lowers unless , because for the differentiable .
Claim 3. Every word with at least one character has a vector, and the vector of a seen word includes its own row.
Assume , as in the paper. If , then has length at least 3, so the start with the length is emitted, and has at least one row whether or not. Line L9 returns the sum over a nonempty list. If , the list starts with its own row by definition, so the vector of a seen word is its own row plus its n-gram rows. For the string "<>" has length 2, and with it has no n-gram, so the empty word outside the vocabulary gets the zero vector.
With , Claim 1 gives no n-grams, the list of a vocabulary word is its own row, , and Claim 2 reduces to the negative sampling step of the skip-gram model.
Complexity
Line L1 costs per n-gram for the hash, so per word of length , once. Each window pair costs for the sum , for lines L4 to L7 and for line L8. A pass emits pairs, so the training costs , about times the cost of plain skip-gram with negative sampling. The memory is numbers for and for the context vectors; with million and , has at least 600 million numbers, whatever the vocabulary.
Properties
- Vectors for unseen words. Any word with at least one character has a vector, built from the hashed n-grams it shares with the training words.
- Fixed memory. The number of rows does not grow with the number of distinct n-grams. Different n-grams can share a bucket (hash collision), which adds noise but bounds the memory.
- Shared parameters. Words with common prefixes, suffixes or stems share rows, so frequent forms help rare ones. This matters most for languages with rich morphology.
- Randomized. The start, the noise words and the order of the data are random.
- Contains skip-gram. With no n-grams (), is the word's own row and the model is skip-gram with negative sampling.
Variants and improvements
- Mean instead of sum. The fastText library divides the sum by when it builds ; the paper defines the score with the plain sum. The mean keeps the scale of the same for short and long words.
- CBOW with n-grams. The library also trains a continuous bag-of-words model whose input is the n-gram rows of all the context words.
- Other units. The n-grams can be replaced by morphemes or by subword units from byte-pair encoding or other subword tokenizations.
- Bucket count and lengths. A smaller saves memory and adds collisions. Shorter n-gram ranges, such as 3 to 3, reduce the cost per word.
When to use it
Use it when the text has many rare words, many word forms or many words not seen in training: languages with rich morphology, social media text with misspellings, or technical text with compounds. On frequent words of English the gain over plain skip-gram is small, and the model is slower and needs memory for the buckets. When no vector is needed for unseen words and the vocabulary is small, plain skip-gram or GloVe is simpler.
Pitfalls
- Missing boundary symbols. Line L1 must take the n-grams of "<" ">", not of . Without the symbols, prefixes and suffixes are not marked, and a short word such as "a" has no n-gram at all.
- Signed bytes in the hash. The fastText library reads each byte as a signed char before the XOR, so bytes 128 to 255 (every non-ASCII character in UTF-8) are sign extended to 32 bits. Standard FNV-1a does not do this. For "é" the library gives 3cfa68c1 and standard FNV-1a gives 1e9de8c1, so a reimplementation that uses the standard hash cannot load vectors trained by the library for non-ASCII n-grams.
- Offset of the buckets. Line L1 adds to the bucket number. Without the offset, n-grams share rows with whole words.
- Updating each row with its own gradient. Line L8 must give every row of the same step , computed before any row changes. Computing again after each row update gives a different, wrong step.
- Sum against mean. Vectors from the library are means, not sums. Mixing the two conventions changes the norms of all vectors, which matters for dot products though not for cosines.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/subword-information-embeddings/. The authors are listed in prov/3998JC.jsonl.
"""Subword information skip-gram (Bojanowski, Grave, Joulin and Mikolov 2017).
A word w is the set G_w of its own entry and the character n-grams of <w>,
for n from minn to maxn. Each n-gram is hashed with 32-bit FNV-1a into one of
`buckets` rows. Rows 0 to nwords - 1 of the input matrix Z belong to the
words of the vocabulary, the rows after them to the buckets. The vector of a
word is the sum of its rows (the paper; the released library divides the sum
by |G_w|). The score of a word and a context word c is s(w, c) = sum over g
in G_w of z_g . v_c, trained with negative sampling.
fnv1a_32 has the sign extension of the released library by default: each
byte is read as a signed char before the XOR, which changes the hash of the
bytes 128 to 255 (non-ASCII text). signed_bytes=False gives standard FNV-1a.
"""
import bisect
import math
import random
from typing import Sequence
FNV_OFFSET = 2166136261
FNV_PRIME = 16777619
def fnv1a_32(text: str, signed_bytes: bool = True) -> int:
h = FNV_OFFSET
for b in text.encode("utf-8"):
if signed_bytes and b >= 128:
b |= 0xFFFFFF00
h = ((h ^ b) * FNV_PRIME) & 0xFFFFFFFF
return h
def char_ngrams(word: str, minn: int = 3, maxn: int = 6) -> list[str]:
"""The character n-grams of <word>, by start position and then by length."""
s = "<" + word + ">"
out = []
for i in range(len(s)):
for n in range(minn, maxn + 1):
if i + n > len(s):
break
out.append(s[i:i + n])
return out
def subword_rows(word: str, vocab: dict[str, int], buckets: int, minn: int = 3, maxn: int = 6) -> list[int]:
"""Rows of Z for the word: its own row if it is in the vocabulary, then the n-gram buckets."""
rows = [vocab[word]] if word in vocab else []
rows += [len(vocab) + fnv1a_32(g) % buckets for g in char_ngrams(word, minn, maxn)] # @line L1
return rows
def word_vector(z: Sequence[Sequence[float]], rows: Sequence[int], mean: bool = False) -> list[float]:
"""Sum (or mean) of the rows of the word. Works for words outside the vocabulary."""
d = len(z[0])
h = [0.0] * d
for r in rows:
for k in range(d):
h[k] += z[r][k]
if mean and rows:
h = [a / len(rows) for a in h]
return h # @line L9
def log_sigmoid(x: float) -> float:
return -math.log1p(math.exp(-x)) if x >= 0 else x - math.log1p(math.exp(x))
def sigmoid(x: float) -> float:
if x >= 0:
return 1.0 / (1.0 + math.exp(-x))
e = math.exp(x)
return e / (1.0 + e)
def pair_loss(z, v, rows, context: int, negatives: Sequence[int]) -> float:
"""-log sigma(s(w, c)) - sum over negatives n of log sigma(-s(w, n))."""
h = word_vector(z, rows)
score = lambda u: sum(a * b for a, b in zip(h, v[u])) # noqa: E731
return -log_sigmoid(score(context)) - sum(log_sigmoid(-score(u)) for u in negatives)
def pair_gradient(z, v, rows, context: int, negatives: Sequence[int]):
"""Gradients of pair_loss: a dict row -> vector for Z and a dict word -> vector for V."""
h = word_vector(z, rows)
d = len(h)
gh = [0.0] * d
gv: dict[int, list[float]] = {}
for u, label in [(context, 1.0)] + [(u, 0.0) for u in negatives]:
e = sigmoid(sum(a * b for a, b in zip(h, v[u]))) - label
gv.setdefault(u, [0.0] * d)
for k in range(d):
gv[u][k] += e * h[k]
gh[k] += e * v[u][k]
gz: dict[int, list[float]] = {}
for r in rows:
gz.setdefault(r, [0.0] * d)
for k in range(d):
gz[r][k] += gh[k]
return gz, gv
class NoiseSampler:
"""Draw words from the unigram distribution raised to the power 3/4."""
def __init__(self, counts: Sequence[int], power: float = 0.75):
acc, self.cdf = 0.0, []
for c in counts:
acc += c ** power
self.cdf.append(acc)
def draw(self, rng: random.Random) -> int:
return bisect.bisect_right(self.cdf, rng.random() * self.cdf[-1])
def train(corpus: Sequence[Sequence[str]], d: int = 8, epochs: int = 5, window: int = 2,
negatives: int = 3, lr: float = 0.05, buckets: int = 2000, minn: int = 3,
maxn: int = 6, seed: int = 0):
"""Plain SGD with a fixed step. Returns (vocab, Z, V)."""
rng = random.Random(seed)
counts: dict[str, int] = {}
for sent in corpus:
for w in sent:
counts[w] = counts.get(w, 0) + 1
words = sorted(counts, key=lambda w: (-counts[w], w))
vocab = {w: i for i, w in enumerate(words)}
rows = {w: subword_rows(w, vocab, buckets, minn, maxn) for w in words}
z = [[(rng.random() - 0.5) / d for _ in range(d)] for _ in range(len(words) + buckets)] # @line L2
v = [[0.0] * d for _ in words]
noise = NoiseSampler([counts[w] for w in words])
for _ in range(epochs): # @line L3
for sent in corpus:
for t, w in enumerate(sent):
for c in range(max(0, t - window), min(len(sent), t + window + 1)):
if c == t:
continue
ctx = vocab[sent[c]]
neg = [noise.draw(rng) for _ in range(negatives)]
neg = [u for u in neg if u != ctx]
h = word_vector(z, rows[w])
gh = [0.0] * d
for u, label in [(ctx, 1.0)] + [(u, 0.0) for u in neg]: # @line L4
s = sum(a * b for a, b in zip(h, v[u])) # @line L5
e = sigmoid(s) - label # @line L6
for k in range(d): # @line L7
gh[k] += e * v[u][k]
v[u][k] -= lr * e * h[k]
for r in rows[w]: # @line L8
for k in range(d):
z[r][k] -= lr * gh[k]
return vocab, z, v
def embed(word: str, vocab: dict[str, int], z, buckets: int = 2000, minn: int = 3, maxn: int = 6) -> list[float]:
"""The vector of any word, seen or not."""
return word_vector(z, subword_rows(word, vocab, buckets, minn, maxn))
test_subword_information_embeddings.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/subword-information-embeddings/. The authors are listed in prov/3998JC.jsonl.
import math
import random
from subword_information_embeddings import (
NoiseSampler,
char_ngrams,
embed,
fnv1a_32,
pair_gradient,
pair_loss,
subword_rows,
train,
word_vector,
)
def cos(u, v):
return sum(a * b for a, b in zip(u, v)) / math.sqrt(sum(a * a for a in u) * sum(b * b for b in v))
def test_ngrams_of_where():
assert char_ngrams("where", 3, 3) == ["<wh", "whe", "her", "ere", "re>"]
grams = char_ngrams("where")
assert len(grams) == 5 + 4 + 3 + 2
assert "<where" in grams and "where>" in grams and "<where>" not in grams
assert "her" in grams and "<her>" not in grams
def test_ngram_count_formula():
for word in ["a", "ab", "abc", "abcdefgh", "abcdefghijk"]:
m = len(word) + 2
expect = sum(max(0, m - n + 1) for n in range(3, 7))
assert len(char_ngrams(word)) == expect
def test_fnv1a_standard_vectors():
assert fnv1a_32("", signed_bytes=False) == 0x811C9DC5
assert fnv1a_32("a", signed_bytes=False) == 0xE40C292C
assert fnv1a_32("foobar", signed_bytes=False) == 0xBF9CF968
assert fnv1a_32("foobar") == 0xBF9CF968 # ASCII: no difference
def test_fnv1a_signed_byte_quirk():
plain, quirk = fnv1a_32("é", signed_bytes=False), fnv1a_32("é")
assert plain != quirk
h = 2166136261
for b in "é".encode("utf-8"):
h = ((h ^ (b - 256 + 2 ** 32)) * 16777619) % 2 ** 32
assert quirk == h
def test_rows_of_seen_and_unseen_words():
vocab = {"where": 0, "here": 1}
seen = subword_rows("where", vocab, 100)
unseen = subword_rows("wherever", vocab, 100)
assert seen[0] == 0 and len(seen) == 15
assert all(2 <= r < 102 for r in seen[1:]) and all(2 <= r < 102 for r in unseen)
assert len(unseen) == len(char_ngrams("wherever"))
def test_gradient_against_finite_differences():
rng = random.Random(1)
d, nrows, nwords = 4, 30, 6
z = [[rng.uniform(-0.5, 0.5) for _ in range(d)] for _ in range(nrows)]
v = [[rng.uniform(-0.5, 0.5) for _ in range(d)] for _ in range(nwords)]
rows, ctx, neg = [0, 7, 7, 12, 29], 2, [1, 4, 4]
gz, gv = pair_gradient(z, v, rows, ctx, neg)
h = 1e-6
for mat, grads in ((z, gz), (v, gv)):
for r in range(len(mat)):
for k in range(d):
old = mat[r][k]
mat[r][k] = old + h
up = pair_loss(z, v, rows, ctx, neg)
mat[r][k] = old - h
down = pair_loss(z, v, rows, ctx, neg)
mat[r][k] = old
num = (up - down) / (2 * h)
ana = grads.get(r, [0.0] * d)[k]
assert abs(num - ana) < 1e-5
def test_noise_distribution():
sampler = NoiseSampler([8, 4, 2, 1, 1])
z = sum(c ** 0.75 for c in [8, 4, 2, 1, 1])
exact = [c ** 0.75 / z for c in [8, 4, 2, 1, 1]]
rng = random.Random(2)
n = 20000
freq = [0] * 5
for _ in range(n):
freq[sampler.draw(rng)] += 1
assert all(abs(f / n - p) < 0.01 for f, p in zip(freq, exact))
def planted_corpus(seed=0, sentences=80, length=6):
"""Words of stem pak meet only contexts x*, words of stem zot meet only contexts y*."""
rng = random.Random(seed)
groups = [(["pakir", "pakor", "pakus", "pakel", "pakim"], ["xo", "xu", "xi"]),
(["zotir", "zotor", "zotus", "zotel", "zotim"], ["yo", "yu", "yi"])]
corpus = []
for _ in range(sentences):
words, ctx = groups[rng.randrange(2)]
corpus.append([rng.choice(words) if k % 2 == 0 else rng.choice(ctx) for k in range(length)])
return corpus, groups
def test_planted_clusters_and_unseen_word():
corpus, groups = planted_corpus(seed=3)
vocab, z, _ = train(corpus, d=8, epochs=4, window=2, negatives=3, lr=0.05,
buckets=500, minn=3, maxn=4, seed=3)
vec = {w: embed(w, vocab, z, 500, 3, 4) for w in vocab}
(a, _), (b, _) = groups
inside = [cos(vec[u], vec[v]) for g in (a, b) for k, u in enumerate(g) for v in g[k + 1:]]
across = [cos(vec[u], vec[v]) for u in a for v in b]
assert min(inside) > max(across)
new = embed("pakar", vocab, z, 500, 3, 4) # never seen in training
assert "pakar" not in vocab and any(abs(t) > 0 for t in new)
mean_a = [sum(c) / len(a) for c in zip(*(vec[w] for w in a))]
mean_b = [sum(c) / len(b) for c in zip(*(vec[w] for w in b))]
assert cos(new, mean_a) > cos(new, mean_b) + 0.3
def test_vector_is_sum_of_rows():
rng = random.Random(4)
z = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(10)]
rows = [2, 5, 5, 9]
got = word_vector(z, rows)
ref = [z[2][k] + 2 * z[5][k] + z[9][k] for k in range(3)]
assert max(abs(x - y) for x, y in zip(got, ref)) < 1e-15
mean = word_vector(z, rows, mean=True)
assert max(abs(x - y / 4) for x, y in zip(mean, ref)) < 1e-15
History
Character-level information had been added to word vectors before, for example through morphological segmentation, but Bojanowski, Grave, Joulin and Mikolov made it simple and fast: a bag of hashed character n-grams added to skip-gram. Their preprint appeared in 2016, the year the fastText library was released, and the TACL paper followed in 2017. Facebook later released pretrained fastText vectors for many languages.
References
- Bojanowski, Grave, Joulin and Mikolov 2017, Section 3 (the skip-gram model with negative sampling, and the subword model: the boundary symbols < and >, the n-grams for n from 3 to 6, the word itself in its set of n-grams, the score as a sum over the n-grams, and the FNV-1a hash into 2 million buckets), Section 4 (the training settings), and the experiments on words outside the vocabulary
- Mikolov, Sutskever, Chen, Corrado and Dean 2013, the skip-gram model with negative sampling that the subword model extends
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 3998JC Edit this page History Report an error Markdown