Algorithm Search⌘K

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
Properties
randomizednot exactofflineiterative
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 nn 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 NN tokens, the window radius CC, the number kk of noise words, the dimension dd, the n-gram lengths from nmin⁡n_{\min} to nmax⁡n_{\max} and the number BB of hash buckets. For a word ww, let Gw\mathcal{G}_w be the list of the rows of the input matrix ZZ that belong to ww: the row of ww itself if ww is in the vocabulary, and the row ∣V∣+(hash(g) mod B)|V| + (\mathrm{hash}(g) \bmod B) of each character n-gram gg of the string "<" ww ">". The score of a word ww and a context word cc is

s(w,c)=∑g∈Gwz⃗g⋅v⃗c=(∑g∈Gwz⃗g)⋅v⃗c,s(w, c) = \sum_{g \in \mathcal{G}_w} \vec z_g \cdot \vec v_c = \Big(\sum_{g \in \mathcal{G}_w} \vec z_g\Big) \cdot \vec v_c,

and the loss of an observed pair with noise words n1,…,nkn_1, \ldots, n_k is the negative sampling loss −log⁡σ(s(w,c))−∑ilog⁡σ(−s(w,ni))-\log\sigma(s(w, c)) - \sum_i \log\sigma(-s(w, n_i)). The output is ZZ, from which any word, seen or not, gets the vector ∑g∈Gwz⃗g\sum_{g \in \mathcal{G}_w} \vec z_g.

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 nn from 3 to 6 and B=2B = 2 million, and hashes with the FNV-1a hash.

The algorithm

  1. SUBWORD-SKIP-GRAM(corpus, C, k, d, T, η, n_min, n_max, B)
  2. 1for each word w: G_w ← its own row, then |V| + FNV-1a(g) mod B for each n-gram g of <w>
  3. 2Z ← small uniform random values, (|V| + B) rows; the context vectors v ← 0
  4. 3for each epoch and each window pair (w, c) with noise words n_1..n_k do h ← Σ_{g ∈ G_w} z_g
  5. 4for each (x, y) in (c, 1), (n_1, 0), ..., (n_k, 0) do
  6. 5s ← h · v_x
  7. 6e ← σ(s) - y
  8. 7g_h ← g_h + e v_x; v_x ← v_x - η e h
  9. 8for each g in G_w do z_g ← z_g - η g_h ▷ every n-gram row gets the same step
  10. 9return 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 h⃗\vec h in place of the word vector. Since ss depends on the rows of Gw\mathcal{G}_w only through their sum, the gradient with respect to each of them is the same vector g⃗h\vec g_h, and line L8 applies it to every row. A row that occurs twice in Gw\mathcal{G}_w 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 mm characters has ∑n=36max⁡(0,m+3−n)\sum_{n=3}^{6} \max(0, m + 3 - n) n-grams, so a long word has about 4m4m.

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 B=2,000,000B = 2{,}000{,}000
<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 "<" ww ">" of length nmin⁡n_{\min} to nmax⁡n_{\max}, one per start position and length, and maps each to a row in [∣V∣,∣V∣+B)[|V|, |V| + B). Lines L5 to L8 compute the exact gradient of the negative sampling loss of the pair, because s(w,x)=h⃗⋅v⃗xs(w, x) = \vec h \cdot \vec v_x and ∂h⃗/∂z⃗g\partial \vec h / \partial \vec z_g is the identity for each occurrence of gg in Gw\mathcal{G}_w. The vector of line L9 is defined for every word with at least one character, because "<" ww ">" 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 ww of m≥0m \ge 0 characters, let $s = $ "<" ww ">", a string of length m+2m + 2. Let VV be the vocabulary, with words numbered 00 to ∣V∣−1|V| - 1, and B≥1B \ge 1 the number of buckets. The row list Gw\mathcal{G}_w is the own row of ww if w∈Vw \in V, followed by ∣V∣+(h(g) mod B)|V| + (h(g) \bmod B) for each n-gram gg in the order of line L1, where hh is the hash. The vector of ww is h⃗w=∑r∈Gwz⃗r\vec h_w = \sum_{r \in \mathcal{G}_w} \vec z_r, 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 i=0,…,m+1i = 0, \ldots, m + 1 and each length n=nmin⁡,…,nmax⁡n = n_{\min}, \ldots, n_{\max} with i+n≤m+2i + n \le m + 2, and emits s[i,i+n)s[i, i + n). A substring occurrence of ss is fixed by its start and its length, so each occurrence of length nmin⁡n_{\min} to nmax⁡n_{\max} is emitted exactly once. For a fixed nn, the starts are 0,…,m+2−n0, \ldots, m + 2 - n, so there are max⁡(0,m+3−n)\max(0, m + 3 - n) of them, and the total is ∑n=nmin⁡nmax⁡max⁡(0,m+3−n)\sum_{n = n_{\min}}^{n_{\max}} \max(0, m + 3 - n). For "where" (m=5m = 5) and nn from 3 to 6 this is 5+4+3+2=145 + 4 + 3 + 2 = 14.

The hash h(g)h(g) is a nonnegative integer, so h(g) mod B∈{0,…,B−1}h(g) \bmod B \in \{0, \ldots, B - 1\}, and the row ∣V∣+(h(g) mod B)|V| + (h(g) \bmod B) lies in [∣V∣,∣V∣+B)[|V|, |V| + B). These rows are disjoint from the own rows 0,…,∣V∣−10, \ldots, |V| - 1, so an n-gram never shares a row with a whole word. □\square

Claim 2. Lines L3 to L8 take an exact gradient step of the pair loss.

Fix a pair (w,c)(w, c) with noise words n1,…,nkn_1, \ldots, n_k, and write x0=cx_0 = c, y0=1y_0 = 1, and xi=nix_i = n_i, yi=0y_i = 0. The loss is

ℓ=∑i=0k(−yilog⁡σ(h⃗w⋅v⃗xi)−(1−yi)log⁡σ(−h⃗w⋅v⃗xi)).\ell = \sum_{i=0}^{k} \Big(-y_i \log\sigma(\vec h_w \cdot \vec v_{x_i}) - (1 - y_i)\log\sigma(-\vec h_w \cdot \vec v_{x_i})\Big).

For one term with t=h⃗w⋅v⃗xt = \vec h_w \cdot \vec v_x, the derivative of −log⁡σ(t)-\log\sigma(t) is σ(t)−1\sigma(t) - 1 and that of −log⁡σ(−t)-\log\sigma(-t) is σ(t)\sigma(t). Both are e=σ(t)−ye = \sigma(t) - y, which line L6 computes. By the chain rule,

∂ℓ∂v⃗x=∑i:xi=xei h⃗w,∂ℓ∂h⃗w=∑i=0kei v⃗xi=g⃗h.\frac{\partial \ell}{\partial \vec v_x} = \sum_{i : x_i = x} e_i\, \vec h_w, \qquad \frac{\partial \ell}{\partial \vec h_w} = \sum_{i=0}^{k} e_i\, \vec v_{x_i} = \vec g_h.

Line L7 accumulates g⃗h\vec g_h from the values of v⃗xi\vec v_{x_i} before their own update, and moves v⃗xi\vec v_{x_i} by −ηeih⃗w-\eta e_i \vec h_w. A noise word that appears twice is moved twice, which matches the sum over ii with xi=xx_i = x.

The loss depends on the rows only through h⃗w=∑r∈Gwz⃗r\vec h_w = \sum_{r \in \mathcal{G}_w} \vec z_r. If row rr occurs μr\mu_r times in the list, then ∂h⃗w/∂z⃗r=μrI\partial \vec h_w / \partial \vec z_r = \mu_r I, so ∂ℓ/∂z⃗r=μrg⃗h\partial \ell / \partial \vec z_r = \mu_r \vec g_h. Line L8 runs over the list and subtracts ηg⃗h\eta \vec g_h once per occurrence, that is ημrg⃗h\eta \mu_r \vec g_h in total. All of g⃗h\vec g_h, eie_i and h⃗w\vec h_w are computed at the parameters before the step, so the step is −η∇ℓ-\eta \nabla \ell in the context vectors and the rows of ZZ, and every other parameter has zero gradient and does not move.

For a small enough η\eta, such a step lowers ℓ\ell unless ∇ℓ=0\nabla \ell = 0, because ℓ(θ−η∇ℓ)=ℓ(θ)−η∥∇ℓ∥2+o(η)\ell(\theta - \eta\nabla\ell) = \ell(\theta) - \eta\|\nabla\ell\|^2 + o(\eta) for the differentiable ℓ\ell. □\square

Claim 3. Every word with at least one character has a vector, and the vector of a seen word includes its own row.

Assume nmin⁡≤3≤nmax⁡n_{\min} \le 3 \le n_{\max}, as in the paper. If m≥1m \ge 1, then ss has length at least 3, so the start 00 with the length nmin⁡n_{\min} is emitted, and Gw\mathcal{G}_w has at least one row whether w∈Vw \in V or not. Line L9 returns the sum over a nonempty list. If w∈Vw \in V, 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 m=0m = 0 the string "<>" has length 2, and with nmin⁡=3n_{\min} = 3 it has no n-gram, so the empty word outside the vocabulary gets the zero vector. □\square

With nmin⁡>nmax⁡n_{\min} > n_{\max}, Claim 1 gives no n-grams, the list of a vocabulary word is its own row, h⃗w=z⃗w\vec h_w = \vec z_w, and Claim 2 reduces to the negative sampling step of the skip-gram model. ■\blacksquare

Complexity

Line L1 costs O(m)O(m) per n-gram for the hash, so O(Gm)O(G m) per word of length mm, once. Each window pair costs O(Gd)O(G d) for the sum h⃗\vec h, O((k+1)d)O((k + 1) d) for lines L4 to L7 and O(Gd)O(G d) for line L8. A pass emits O(NC)O(NC) pairs, so the training costs O(TNC(k+G)d)O(TNC(k + G)d), about (k+G)/(k+1)(k + G)/(k + 1) times the cost of plain skip-gram with negative sampling. The memory is (∣V∣+B) d(|V| + B)\,d numbers for ZZ and ∣V∣ d|V|\,d for the context vectors; with B=2B = 2 million and d=300d = 300, ZZ 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 (nmin⁡>nmax⁡n_{\min} > n_{\max}), Gw\mathcal{G}_w 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 ∣Gw∣|\mathcal{G}_w| when it builds h⃗\vec h; the paper defines the score with the plain sum. The mean keeps the scale of h⃗\vec h 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 BB 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 "<" ww ">", not of ww. 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 ∣V∣|V| 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 Gw\mathcal{G}_w the same step ηg⃗h\eta \vec g_h, computed before any row changes. Computing h⃗\vec h 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.

subword_information_embeddings.pyI0RawGitHub
# 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

  1. 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
  2. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example