Module contents
Lesson 6 of 24Core 115 min

Word2Vec: skip-gram, CBOW and negative sampling

Study Word2Vec skip-gram and CBOW, hierarchical softmax, negative sampling and their evaluation protocols.

After this lesson you can

  • Construct context pairs with explicit window and subsampling rules.
  • Derive softmax and negative-sampling gradients, including repeated indices.
  • Explain hierarchical softmax, noise distributions and collision policies.
  • Evaluate embeddings with coverage and training settings documented.

Before you start

Learning words by predicting neighbors

When you read “the cat sleeps on the sofa,” each word occurs alongside others. If “dog” and “cat” appear in similar contexts, a prediction task may encourage their representations to share information. That similarity is a possibility to measure, not a guaranteed consequence of training. Static vectors also mix all uses of a word.

In the previous Neural probabilistic language model, an ordered window predicted the next token via a normalized distribution. Here the objective changes: for each center word we predict neighboring words, or vice versa. The objective produces useful embeddings for some tasks, but a pair score is not necessarily a next-word probability in text.

Mikolov and colleagues proposed log-bilinear architectures capable of training representations on large corpora. In their Table 5, with 783 million news words, three epochs and 300-dimensional vectors, CBOW achieved 36.1% total accuracy on their analogy test and skip-gram 53.3%. Their times were one and three days respectively under that protocol. These are results of that experiment, not a prediction for every corpus, machine or task.

From one sentence to many examples

The sentence “el gato duerme” with radius one produces directed pairs (el, gato), (gato, el), (gato, duerme) and (duerme, gato), without crossing sentence boundaries. Each pair has a center and a context. Repetitions can occur: “gato gato” contributes two directed occurrences, not one pair type.

A fixed window of maximum radius WW permits distances from 1 to WW. If radius is sampled uniformly from {1,…,W}\{1,\ldots,W\} for each center, a position at distance d≤Wd\leq W survives with probability (W−d+1)/W(W-d+1)/W, before boundaries or discarded words. Thus closer words participate more often. If words are removed before windows are built, distance is measured in the surviving sequence, not the original.

InteractiveThe pair factory

Fixed sentence: el gato mira el gato y el perro mira el mar. This is a toy experiment, not a measurement of Word2Vec training.

1 · centerel2 · contextgato3 · contextmira4el5gato6y7el8perro9mira10el11mar
Center 1 of 11

Center: el, original position 1; radius 2. Pairs: (el, gato), (el, mira).

Distance histogram of processed pairs

Distance 11
Distance 21

Distance is measured in the surviving sequence, not original positions. Each directed pair contributes one count. A pair counts as «with el or y» if at least one endpoint is «el» or «y»; this list is fixed only for the example. Bars use all processed pairs as denominator.

Frequencies and theoretical retention
TokenCountFrequencyP(retain)
el436.4 %52.4 %
gato218.2 %74.2 %
mira218.2 %74.2 %
y19.1 %100.0 %
perro19.1 %100.0 %
mar19.1 %100.0 %

The table shows sentence frequencies before discarding. The paper’s formula retains with probability min(1, √(t/f)); the original C implementation uses a different formula. The table presents that theoretical probability even when subsampling is disabled. The seed determines reproducible draws; window and discard use separate pseudorandom streams derived from the same seed. Expected rates need not match this small sample.

2
42
Retained tokens11 / 11
Processed pairs2 / 38
Pairs with el or y100.0 %
Step through a toy sentence, change the window and observe how discarding alters the sequence and distances.

Skip-gram and full softmax

Let vocabulary size be VV words and dimension dd. Each word ww has an input vector vwv_w and output vector uwu_w; these are two learned tables, not two names for one matrix. In skip-gram, the center selects vwv_w and softmax scores possible contexts:

p(c∣w)=exp⁡(uc⊤vw)∑j=1Vexp⁡(uj⊤vw),ℓsoft(w,c)=−log⁡p(c∣w).p(c\mid w)=\frac{\exp(u_c^\top v_w)} {\sum_{j=1}^{V}\exp(u_j^\top v_w)},\qquad \ell_{\rm soft}(w,c)=-\log p(c\mid w).

For several observed contexts you can sum or average losses, always stating the convention. First differentiate one pair; write pj=p(j∣w)p_j=p(j\mid w). The identity ∂log⁡∑iesi/∂sj=pj\partial\log\sum_i e^{s_i}/\partial s_j=p_j gives

∂ℓsoft∂vw=∑jpjuj−uc,∂ℓsoft∂uj=(pj−1[j=c])vw.\frac{\partial\ell_{\rm soft}}{\partial v_w} =\sum_j p_j u_j-u_c,\qquad \frac{\partial\ell_{\rm soft}}{\partial u_j} =(p_j-\mathbf1[j=c])v_w.

The observed-context error subtracts its vector; all output vectors participate in the sum. A direct implementation therefore needs VV dot products of dimension dd per pair, plus normalization. No output row becomes sparse for free merely because there is one positive label.

CBOW: a prediction from the set

CBOW reverses the task. Given nonempty context c1,…,cmc_1,\ldots,c_m, it averages h=m−1∑ivcih=m^{-1}\sum_i v_{c_i} and predicts the center with p(w∣c1:m)=softmax⁡(Uh)wp(w\mid c_{1:m})=\operatorname{softmax}(Uh)_w. Context order is lost in this operation. With g=∂ℓ/∂h=∑jpjuj−uwg=\partial\ell/\partial h=\sum_j p_j u_j-u_w, each context occurrence contributes g/mg/m to the row it looked up. If a word occurs several times, the chain rule sums those contributions. For the output table, ∂ℓ/∂uj=(pj−1[j=w])h\partial\ell/\partial u_j=(p_j-\mathbf1[j=w])h.

Using a sum instead of a mean changes forward and gradient scale. State this in comparisons, along with treatment of boundaries and empty contexts. Quality differences between CBOW and skip-gram depend on corpus, implementation and evaluation, not an architectural theorem.

A tree of normalized decisions

Hierarchical softmax places one word at each leaf of a binary tree. Each internal node nn has vector ana_n and, for center ww, assigns probability σ(an⊤vw)\sigma(a_n^\top v_w) to one branch and 1−σ(an⊤vw)1-\sigma(a_n^\top v_w) to the other. If bn(c)b_n(c) is 1 for the branch receiving the sigmoid and 0 for its complement, the product along cc‘s path is

p(c∣w)=∏n∈camino⁡(c)σ ⁣((2bn(c)−1)an⊤vw).p(c\mid w)=\prod_{n\in\operatorname{camino}(c)} \sigma\!\left((2b_n(c)-1)a_n^\top v_w\right).

At a leaf, incoming mass is its probability. At each node the two branch masses sum to incoming mass; by induction all leaves sum to one. For a visited node, if sn=an⊤vws_n=a_n^\top v_w, that step’s loss has derivative σ(sn)−bn(c)\sigma(s_n)-b_n(c) with respect to sns_n. Thus the ana_n gradient multiplies that scalar by vwv_w, and the vwv_w gradient sums scalars multiplied by the path’s ana_n vectors.

A Huffman code minimizes frequency-weighted mean length among binary prefix codes. This favors short paths for frequent words, but does not guarantee all have length O(log⁡V)O(\log V): a highly unbalanced tree can reach depth O(V)O(V). Actual cost per word is proportional to dd times path length. In a balanced tree it is O(dlog⁡V)O(d\log V).

InteractiveA path among all words

Toy frequencies: sol 45 · luna 25 · mar 15 · viento 8 · nube 7. Each merge takes the two lowest weights; ties favor the subtree whose first leaf appears earlier in the order sol, luna, mar, viento, nube. The first goes left. The weights are not predicted probabilities. Click a leaf or use the selector to change paths.

sol45luna25mar15nube7viento8n1n2n3n4

Internal nodes n1 to n4 are numbered in merge order. Their toy vectors are n1=(0.7, −0.3) · n2=(−0.5, 0.8) · n3=(0.3, 0.5) · n4=(−0.6, −0.4). The center vector is (1.00, 0.50); s = a_n · v. The left branch uses σ(s) and the right σ(−s).

Path to nube
NodeLogit sBranchProbability
n4−0.800right0.68997
n30.550right0.36586
n2−0.100right0.52498
n10.550left0.63414

Path product: 0.68997 × 0.36586 × 0.52498 × 0.63414 ≈ 0.08404. The calculation retains full precision even though factors are rounded here.

All leaves
WordFrequencyStepsP(hoja)
sol4510.31003
luna2520.43754
mar1530.11991
nube740.08404
viento840.04849

Each split distributes all its mass between two branches, so all leaf probabilities sum to one. Huffman minimizes weighted average length for these frequencies; leaf length is not guaranteed by log₂ V in an arbitrary tree. Vectors and logits are an explicit untrained model, not measured results.

Construction frequencies
1.00
0.50
Path length4
log₂ V, V = 52.322
Leaf probability0.08404
Sum of probabilities1.00000
Weighted average length2.000
Build the Huffman tree and multiply decisions toward a leaf.

Negative sampling: another classification problem

Instead of normalizing over the full vocabulary, SGNS trains a binary classifier: observed pair (w,c)(w,c) has label one and each noise pair (w,ni)(w,n_i) has label zero. With kk samples and softplus⁡(x)=log⁡(1+ex)\operatorname{softplus}(x)=\log(1+e^x), loss is

ℓneg=softplus⁡(−uc⊤vw)+∑i=1ksoftplus⁡(uni⊤vw).\ell_{\rm neg}=\operatorname{softplus}(-u_c^\top v_w) +\sum_{i=1}^{k}\operatorname{softplus}(u_{n_i}^\top v_w).

Define sc=uc⊤vws_c=u_c^\top v_w and si=uni⊤vws_i=u_{n_i}^\top v_w. The chain rule gives

∇vwℓneg=(σ(sc)−1)uc+∑iσ(si)uni,(∇ucℓneg)positivo=(σ(sc)−1)vw,(∇uniℓneg)negativo,i=σ(si)vw.\begin{aligned} \nabla_{v_w}\ell_{\rm neg}&=(\sigma(s_c)-1)u_c+ \sum_i\sigma(s_i)u_{n_i},\\ (\nabla_{u_c}\ell_{\rm neg})_{\rm positivo}&=(\sigma(s_c)-1)v_w,\qquad (\nabla_{u_{n_i}}\ell_{\rm neg})_{{\rm negativo},i}=\sigma(s_i)v_w. \end{aligned}

The last two expressions are individual-path contributions, not necessarily the full gradient of those rows. If two samples share an index, their contributions sum in the same row. If the positive word can also appear as a negative, both paths accumulate. The formulas describe the derivative of a scalar loss using the same pre-step parameters; updating a row midway through calculation changes the algorithm.

For each negative logit, ∂ℓ/∂si=σ(si)>0\partial\ell/\partial s_i=\sigma(s_i)>0 when sis_i is finite: a small step on that isolated logit reduces it. In a simultaneous vector update, other interactions also change dot products; “attract” and “repel” are local intuitions, not guarantees that each Euclidean distance decreases or increases at every step.

InteractiveOne loss, multiple paths

Untrained toy model: the center is (1.000, 0.500) and the positive context is sol. The fixed output vectors are sol (1.000, 0.500), luna (−1.000, 1.000) and mar (0.500, −1.000). All terms use those same values before any update.

For each logit s = u · v, the coefficient is σ(s) − 1 for the positive and σ(s) for a negative. Multiplying that coefficient by u gives the contribution to the gradient of v.

Terms and derivative with respect to the center
TermLogitCoefficientContribution
Positive · sol1.250−0.223(−0.223, −0.111)
Negative 1 · luna−0.5000.378(−0.378, 0.378)
Negative 2 · luna−0.5000.378(−0.378, 0.378)
Accumulated gradient of each output vector
VectorNumber of pathsGradient
sol1(−0.223, −0.111)
luna2(0.755, 0.378)
mar0(0.000, 0.000)

The loss sums softplus(−s) for the positive and softplus(s) for each negative. An output row gradient sums coefficient × v for each path using it, even when it coincides with the positive.

Illustrative distribution q ∝ frequency0,75 with explicit counts [4, 2, 1]: sol 51.33 % · luna 30.52 % · mar 18.15 %. Samples are chosen manually and are not draws from q; changing the exponent does not change the loss of already selected samples.

The visualization calculates derivatives, not a measurement or training trajectory. Stable softplus is used; coefficients indicate the derivative with respect to the logit. Simultaneous vector updates can affect several logits at once, so they do not guarantee that each distance changes in a particular direction.

1.0
0.5
2
Illustrative distribution exponent
SGNS loss, sum1.2001
Center gradient(−0.978, 0.644)
Effective negatives2
Inspect derivatives of an explicit example and repeat indices to see gradient accumulation.

The next simulation applies those derivatives to a reproducible sequence of toy pairs. Compare several values of kk, noise power and learning rate: every configuration starts from the same vectors, but changing kk also changes later draws. Plotted distances do not replace the dot product optimized by SGNS.

InteractiveSGNS trajectories in two dimensions

There are two input and three output vectors. The four possible positive pairs are (gato, pelaje), (perro, pelaje), (gato, maúlla) and (perro, ladra), chosen uniformly. This is an explicit toy model, not a corpus or measurement of Word2Vec.

xy
Current coordinates: filled circles are centers; empty circles are contexts
VectorTablexy
gatocenter−0.8390.379
perrocenter−0.481−0.355
pelajecontext0.2330.190
maúllacontext0.5430.614
ladracontext0.718−0.695

Last example: (gato, pelaje); negatives: maúlla, ladra.

Noise counts are pelaje: 4, maúlla: 1 and ladra: 1. For each positive q ∝ frequency raised to the exponent is renormalized, excluding that positive; negatives may repeat. Loss sums one positive and k negative terms; repeated contributions accumulate and all rows update simultaneously. The seed is 17061. The chart scale fits every position along the trajectory. Changing k also changes the sequence of subsequent draws. The dot product drives loss, so distances between points or the appearance of clusters have no guaranteed direction.

20
2
0.15
Noise exponent
Steps20
Last pair loss before the step1.780
Observe input and output vectors and their trajectories, calculated with the negative-sampling objective.

NCE also distinguishes data and noise, but explicitly uses noise-distribution values in its objective. NEG uses samples and is not equivalent to exactly maximizing softmax, nor does it alone produce a normalized context distribution. The 2013 paper, sections 2.1 and 2.2, distinguishes both objectives.

To see where classification comes from, fix center ww and suppose positives are drawn from pdatos(c∣w)p_{\rm datos}(c\mid w) (“datos” means data) and, per positive, kk independent negatives are drawn from q(c)q(c) without rejecting collisions. Among all examples in that mixture, the probability that a pair with context cc comes from data is

P(D=1∣w,c)=pdatos(c∣w)pdatos(c∣w)+kq(c).P(D=1\mid w,c)=\frac{p_{\rm datos}(c\mid w)}{p_{\rm datos}(c\mid w)+kq(c)}.

Logistic loss is cross-entropy of those labels. If pdatos(c∣w)>0p_{\rm datos}(c\mid w)>0, q(c)>0q(c)>0 and each logit can be chosen independently, its optimum satisfies swc∗=log⁡[pdatos(c∣w)/(kq(c))]s^*_{wc}=\log[p_{\rm datos}(c\mid w)/(kq(c))]. This identity describes an idealized population problem: products of two finite-dimensional tables couple logits and need not reach every optimum. If either mass is zero, the corresponding optimum may be at an infinite limit. Rejecting positive context changes the joint negative distribution, so this formula cannot be applied without rederiving it. Goldberg and Levy develop this objective interpretation.

Noise, collisions and frequent words

For count fj>0f_j>0 of each included word, a common empirical choice is

q(j)=fj3/4∑ℓfℓ3/4.q(j)=\frac{f_j^{3/4}}{\sum_\ell f_\ell^{3/4}}.

The exponent compresses relative differences compared with the raw unigram but does not make the distribution uniform. The paper tested that power against unigram and uniform and observed better results on its tasks; it does not prove 3/4 is optimal for every corpus.

There are several legitimate policies for a negative sample equal to the positive. With replacement until kk negatives distinct from the positive are obtained, each independent draw has distribution q(n)/(1−q(c))q(n)/(1-q(c)) for n≠cn\ne c, provided q(c)<1q(c)<1. Negatives may repeat each other. By contrast, the original code skips a collision without replacing it, so it can use fewer than kk effective negatives. The resulting objective and distributions differ: record the variant.

Frequency and effective window also change examples. For relative frequency f(w)>0f(w)>0 and threshold t>0t>0, the paper gives discard probability max⁡(0,1−t/f(w))\max(0,1-\sqrt{t/f(w)}). The C code instead calculates retention min⁡(1,t/f(w)+t/f(w))\min(1,\sqrt{t/f(w)}+t/f(w)). The difference affects pair count; a comparison must state the version used. Decreasing learning rate during training is another recipe choice, not an objective property.

Two tables initialized entirely to zero produce zero gradients for these bilinear products. If input is random and output starts at zero, output can receive gradients from the first step; input starts receiving them once output is nonzero.

Evaluation has its own protocol

You can query cosine neighbors in the input table, output table or their sum, but state which you use. Avoid division by zero norms. For a:b::c:?a:b::c:?, a common rule finds the vector closest to vb−va+vcv_b-v_a+v_c and excludes question words. Reporting only percentage on answerable questions is insufficient: also count the total, questions with out-of-vocabulary terms and number actually evaluated.

In Table 1 of Mikolov and colleagues, 2013, NEG-5 obtains 59% total analogy accuracy without subsampling and 60% with threshold 10−510^{-5}; HS-Huffman obtains 47% and 55%, respectively. They used 300-dimensional vectors and one billion words of internal Google news. Those numbers are not results of the labs below and do not establish which method wins on a small corpus.

Labs

SGNS from scratch

The lab builds pairs, noise and accumulated gradients with repeated indices. A small sample checks the pipeline in Pyodide; training on millions of tokens must be local if it exceeds the browser time limit. Neighbors and analogies can only be cited when produced by an actual run with vocabulary and coverage declared.

The cell starts from real excerpts of two chapters of part one of Don Quixote from Project Gutenberg, without network access. Vocabulary comes from the first; the second only checks coverage and known pairs. Rejecting identical excerpts does not detect partial matches. Vectors from this sample test the pipeline, not semantic evaluation.

[ ]SGNS from scratch in NumPyBrowser
"""SGNS en NumPy: muestra real muy pequeña, no una evaluación semántica.

Fragmentos de la primera parte de Don Quijote, capítulos I y II, Project
Gutenberg 2000: https://www.gutenberg.org/files/2000/2000-0.txt .
Dominio público declarado en EE. UU.; consulta la ley local y las condiciones
de uso de la marca https://www.gutenberg.org/policy/license.html .
La celda predeterminada usa únicamente estos fragmentos y no accede a red.
Para corpus grandes usa un proceso local y comprueba sus derechos.
"""
import math
import re
import unicodedata
from collections import Counter

import numpy as np

TRAIN = 'En un lugar de la Mancha, de cuyo nombre no quiero acordarme'
VALID = 'Hechas, pues, estas prevenciones, no quiso aguardar más tiempo'
TOKEN = re.compile(r'\w+', re.UNICODE)
SEED = 17060


def tokenize(text):
    return TOKEN.findall(unicodedata.normalize('NFC', text).lower())


def vocabulary(sentences, minimum=1):
    counts = Counter(word for sentence in sentences for word in sentence)
    words = sorted((w for w, n in counts.items() if n >= minimum),
                   key=lambda w: (-counts[w], w))
    if len(words) < 2:
        raise ValueError('El vocabulario necesita al menos dos palabras')
    index = {word: i for i, word in enumerate(words)}
    return words, index, np.array([counts[word] for word in words], dtype=float)


def noise_distribution(counts, power=.75):
    counts = np.asarray(counts, dtype=float)
    if (counts.ndim != 1 or not np.isfinite(counts).all() or
            np.any(counts < 0) or not np.any(counts > 0) or
            not math.isfinite(power) or power <= 0):
        raise ValueError('Recuentos o exponente inválidos')
    weights = np.zeros_like(counts)
    mask = counts > 0
    logs = np.log(counts[mask])
    weights[mask] = np.exp(power * (logs - logs.max()))
    return weights / weights.sum()


def sampled_contexts(sentences, index, counts, window, subsample, rng):
    """Filtra por el paper y después elige un radio por centro superviviente."""
    total = counts.sum()
    frequency = counts / total
    if window < 1 or subsample < 0:
        raise ValueError('Ventana o submuestreo inválido')
    for sentence in sentences:
        ids = [index[w] for w in sentence if w in index]
        if subsample:
            ids = [i for i in ids if rng.random() < min(1., math.sqrt(subsample / frequency[i]))]
        for pos, center in enumerate(ids):
            radius = int(rng.integers(1, window + 1))
            for j in range(max(0, pos - radius), min(len(ids), pos + radius + 1)):
                if j != pos:
                    yield center, ids[j]


def negatives(q, positives, k, rng, cdf=None):
    """Muestras independientes por par, condicionales a no ser el positivo."""
    if k < 1:
        raise ValueError('k debe ser positivo')
    if np.any(q[positives] >= 1.):
        raise ValueError('No hay masa de ruido fuera del positivo')
    if cdf is None:
        cdf = np.cumsum(q)
        cdf[-1] = 1.
    result = np.searchsorted(cdf, rng.random((len(positives), k)), side='right')
    rejected = result == positives[:, None]
    while np.any(rejected):
        result[rejected] = np.searchsorted(cdf, rng.random(int(rejected.sum())), side='right')
        rejected = result == positives[:, None]
    return result


def sigmoid(x):
    # Válido para números finitos de cualquier signo sin overflow.
    out = np.empty_like(x)
    mask = x >= 0
    out[mask] = 1. / (1. + np.exp(-x[mask]))
    exp_x = np.exp(x[~mask])
    out[~mask] = exp_x / (1. + exp_x)
    return out


def batch_loss_grad(E, U, centers, positives, negative_ids):
    """Media por par y acumulación exacta cuando se repiten índices."""
    v = E[centers]
    u_pos = U[positives]
    u_neg = U[negative_ids]
    positive_scores = np.sum(v * u_pos, axis=1)
    negative_scores = np.einsum('bd,bkd->bk', v, u_neg)
    n = len(centers)
    loss = (np.logaddexp(0., -positive_scores).sum() +
            np.logaddexp(0., negative_scores).sum()) / n
    gp = (sigmoid(positive_scores) - 1.) / n
    gn = sigmoid(negative_scores) / n
    grad_E = np.zeros_like(E)
    grad_U = np.zeros_like(U)
    grad_v = gp[:, None] * u_pos + np.einsum('bk,bkd->bd', gn, u_neg)
    np.add.at(grad_E, centers, grad_v)
    np.add.at(grad_U, positives, gp[:, None] * v)
    np.add.at(grad_U, negative_ids, gn[:, :, None] * v[:, None, :])
    return float(loss), grad_E, grad_U


def gradcheck():
    rng = np.random.default_rng(SEED)
    E = rng.normal(0, .2, (4, 3))
    U = rng.normal(0, .2, (4, 3))
    # Repite centros y negativos, y comparte una fila positiva con otra negativa.
    centers = np.array([0, 0, 2])
    pos = np.array([1, 1, 3])
    neg = np.array([[2, 2], [3, 2], [1, 1]])
    _, dE, dU = batch_loss_grad(E, U, centers, pos, neg)
    errors = {}
    for name, table, grad in [('E', E, dE), ('U', U, dU)]:
        maximum = 0.
        for idx in np.ndindex(table.shape):
            before = table[idx]
            table[idx] = before + 1e-6
            plus = batch_loss_grad(E, U, centers, pos, neg)[0]
            table[idx] = before - 1e-6
            minus = batch_loss_grad(E, U, centers, pos, neg)[0]
            table[idx] = before
            maximum = max(maximum, abs((plus - minus) / 2e-6 - grad[idx]))
        assert maximum < 1e-7, (name, maximum)
        errors[name] = maximum
    return errors


def fit_sgns(sentences, words, index, counts, epochs, dim, window, k, rate,
             seed, subsample=0., batch_size=32):
    rng = np.random.default_rng(seed)
    q = noise_distribution(counts)
    cdf = np.cumsum(q)
    cdf[-1] = 1.
    E = rng.normal(0., .1, (len(words), dim))
    U = np.zeros((len(words), dim))
    history = []
    for epoch in range(epochs):
        pending, total_loss, number = [], 0., 0
        def update(pairs):
            centers = np.array([p[0] for p in pairs], dtype=np.int64)
            positives = np.array([p[1] for p in pairs], dtype=np.int64)
            neg = negatives(q, positives, k, rng, cdf)
            # Solo materializar gradientes de filas presentes, acumulando los
            # índices repetidos antes de escribir cada fila una sola vez.
            e_rows, local_centers = np.unique(centers, return_inverse=True)
            u_rows, local_outputs = np.unique(np.concatenate([positives, neg.ravel()]),
                                              return_inverse=True)
            local_pos = local_outputs[:len(positives)]
            local_neg = local_outputs[len(positives):].reshape(neg.shape)
            loss, dE, dU = batch_loss_grad(E[e_rows], U[u_rows], local_centers,
                                          local_pos, local_neg)
            if not np.isfinite(loss) or not np.isfinite(dE).all() or not np.isfinite(dU).all():
                raise ValueError('Pérdida o gradiente no finito')
            E[e_rows] -= rate * dE
            U[u_rows] -= rate * dU
            return loss * len(pairs), len(pairs)
        for pair in sampled_contexts(sentences, index, counts, window, subsample, rng):
            pending.append(pair)
            if len(pending) == batch_size:
                value, size = update(pending)
                total_loss += value
                number += size
                pending = []
        if pending:
            value, size = update(pending)
            total_loss += value
            number += size
        history.append({'epoch': epoch + 1, 'pairs': number,
                        'mean_loss': total_loss / number if number else None})
    return E, U, history


def neighbors(word, words, E, count=5):
    if word not in words:
        return []
    norms = np.linalg.norm(E, axis=1)
    index = words.index(word)
    if norms[index] <= 1e-12:
        return []
    similarities = np.full(len(words), -np.inf)
    valid = norms > 1e-12
    similarities[valid] = (E[valid] @ E[index]) / (norms[valid] * norms[index])
    similarities[index] = -np.inf
    order = np.argsort(-similarities, kind='stable')
    return [(words[i], float(similarities[i])) for i in order[:count] if np.isfinite(similarities[i])]


def main_small():
    train, valid = tokenize(TRAIN), tokenize(VALID)
    if train == valid:
        raise ValueError('Fragmentos idénticos')
    words, index, counts = vocabulary([train])
    E, _, history = fit_sgns([train], words, index, counts, epochs=8,
                             dim=6, window=2, k=2, rate=.1, seed=SEED,
                             subsample=.01)
    known = [w for w in valid if w in index]
    pairs = list(sampled_contexts([valid], index, counts, 2, 0.,
                                  np.random.default_rng(SEED + 1)))
    print('Gradcheck error absoluto máximo:', gradcheck())
    print('Tokens train/valid:', len(train), len(valid), '| OOV valid:', len(valid) - len(known))
    print('Pares valid con palabras conocidas:', len(pairs),
          '| se filtran OOV antes de crear la ventana')
    print('Historial train:', history)
    print('Vecinos de entrada de', words[0], ':', neighbors(words[0], words, E))
    print('La pérdida de entrenamiento es exploratoria y cambia con los pares y negativos sorteados.')
    print('Los fragmentos son demasiado pequeños para conclusiones semánticas; no hay test.')


if __name__ == '__main__':
    main_small()

Compare with Gensim

The reader can train skip-gram, CBOW, hierarchical softmax and negative sampling on text8. For comparison, fix corpus, splits, vocabulary, dimensions, seed and options, and explain differences in subsampling and collisions. Gensim documentation states that reproducibility across processes requires controlling the hash and using one worker; multiple workers for performance measurement change that condition. The text8 catalog does not confirm a license: check provenance and terms before redistribution.

The local cell requires NumPy, Gensim and compatible dependencies. It downloads text8 to a configurable cache, verifies published size and MD5 and records calculated SHA-256. The Gensim catalog says it found no text8 license: check provenance and usage terms before redistribution. Contiguous blocks of 2000 words are split into training, validation and test; these are artificial cuts and do not guarantee document separation or absence of duplicates. Vocabulary is built only from training.

The analogy benchmark loads from a pinned revision and its repository includes Apache 2.0; check terms applicable to the file. SHA-256 of received bytes is calculated, but checked against an external source only if you supply a reliable value in ORYON_ANALOGIES_SHA256. Analogies and text test are exploratory because several models are examined. Coverage and invalid norms are counted separately.

With ORYON_VERIFY_SHORT=1, 20,000 tokens, one epoch and 128 evenly spaced questions are used: this checks the pipeline, not a conclusive comparison. In that short run all 128 questions were out of vocabulary, so no analogy could be evaluated. Normal mode provides training on text8 and the full benchmark. ORYON_WORKERS chooses Gensim workers, initially 1; SHORT requires 1. Subsampling is disabled to align that decision, but batch updates, learning rate and collisions still differ between implementations.

[ ]Word2Vec and analogies on text8Local GPU
"""SGNS en NumPy: muestra real muy pequeña, no una evaluación semántica.

Fragmentos de la primera parte de Don Quijote, capítulos I y II, Project
Gutenberg 2000: https://www.gutenberg.org/files/2000/2000-0.txt .
Dominio público declarado en EE. UU.; consulta la ley local y las condiciones
de uso de la marca https://www.gutenberg.org/policy/license.html .
La celda predeterminada usa únicamente estos fragmentos y no accede a red.
Para corpus grandes usa un proceso local y comprueba sus derechos.
"""
import math
import re
import unicodedata
from collections import Counter

import numpy as np

TRAIN = 'En un lugar de la Mancha, de cuyo nombre no quiero acordarme'
VALID = 'Hechas, pues, estas prevenciones, no quiso aguardar más tiempo'
TOKEN = re.compile(r'\w+', re.UNICODE)
SEED = 17060


def tokenize(text):
    return TOKEN.findall(unicodedata.normalize('NFC', text).lower())


def vocabulary(sentences, minimum=1):
    counts = Counter(word for sentence in sentences for word in sentence)
    words = sorted((w for w, n in counts.items() if n >= minimum),
                   key=lambda w: (-counts[w], w))
    if len(words) < 2:
        raise ValueError('El vocabulario necesita al menos dos palabras')
    index = {word: i for i, word in enumerate(words)}
    return words, index, np.array([counts[word] for word in words], dtype=float)


def noise_distribution(counts, power=.75):
    counts = np.asarray(counts, dtype=float)
    if (counts.ndim != 1 or not np.isfinite(counts).all() or
            np.any(counts < 0) or not np.any(counts > 0) or
            not math.isfinite(power) or power <= 0):
        raise ValueError('Recuentos o exponente inválidos')
    weights = np.zeros_like(counts)
    mask = counts > 0
    logs = np.log(counts[mask])
    weights[mask] = np.exp(power * (logs - logs.max()))
    return weights / weights.sum()


def sampled_contexts(sentences, index, counts, window, subsample, rng):
    """Filtra por el paper y después elige un radio por centro superviviente."""
    total = counts.sum()
    frequency = counts / total
    if window < 1 or subsample < 0:
        raise ValueError('Ventana o submuestreo inválido')
    for sentence in sentences:
        ids = [index[w] for w in sentence if w in index]
        if subsample:
            ids = [i for i in ids if rng.random() < min(1., math.sqrt(subsample / frequency[i]))]
        for pos, center in enumerate(ids):
            radius = int(rng.integers(1, window + 1))
            for j in range(max(0, pos - radius), min(len(ids), pos + radius + 1)):
                if j != pos:
                    yield center, ids[j]


def negatives(q, positives, k, rng, cdf=None):
    """Muestras independientes por par, condicionales a no ser el positivo."""
    if k < 1:
        raise ValueError('k debe ser positivo')
    if np.any(q[positives] >= 1.):
        raise ValueError('No hay masa de ruido fuera del positivo')
    if cdf is None:
        cdf = np.cumsum(q)
        cdf[-1] = 1.
    result = np.searchsorted(cdf, rng.random((len(positives), k)), side='right')
    rejected = result == positives[:, None]
    while np.any(rejected):
        result[rejected] = np.searchsorted(cdf, rng.random(int(rejected.sum())), side='right')
        rejected = result == positives[:, None]
    return result


def sigmoid(x):
    # Válido para números finitos de cualquier signo sin overflow.
    out = np.empty_like(x)
    mask = x >= 0
    out[mask] = 1. / (1. + np.exp(-x[mask]))
    exp_x = np.exp(x[~mask])
    out[~mask] = exp_x / (1. + exp_x)
    return out


def batch_loss_grad(E, U, centers, positives, negative_ids):
    """Media por par y acumulación exacta cuando se repiten índices."""
    v = E[centers]
    u_pos = U[positives]
    u_neg = U[negative_ids]
    positive_scores = np.sum(v * u_pos, axis=1)
    negative_scores = np.einsum('bd,bkd->bk', v, u_neg)
    n = len(centers)
    loss = (np.logaddexp(0., -positive_scores).sum() +
            np.logaddexp(0., negative_scores).sum()) / n
    gp = (sigmoid(positive_scores) - 1.) / n
    gn = sigmoid(negative_scores) / n
    grad_E = np.zeros_like(E)
    grad_U = np.zeros_like(U)
    grad_v = gp[:, None] * u_pos + np.einsum('bk,bkd->bd', gn, u_neg)
    np.add.at(grad_E, centers, grad_v)
    np.add.at(grad_U, positives, gp[:, None] * v)
    np.add.at(grad_U, negative_ids, gn[:, :, None] * v[:, None, :])
    return float(loss), grad_E, grad_U


def gradcheck():
    rng = np.random.default_rng(SEED)
    E = rng.normal(0, .2, (4, 3))
    U = rng.normal(0, .2, (4, 3))
    # Repite centros y negativos, y comparte una fila positiva con otra negativa.
    centers = np.array([0, 0, 2])
    pos = np.array([1, 1, 3])
    neg = np.array([[2, 2], [3, 2], [1, 1]])
    _, dE, dU = batch_loss_grad(E, U, centers, pos, neg)
    errors = {}
    for name, table, grad in [('E', E, dE), ('U', U, dU)]:
        maximum = 0.
        for idx in np.ndindex(table.shape):
            before = table[idx]
            table[idx] = before + 1e-6
            plus = batch_loss_grad(E, U, centers, pos, neg)[0]
            table[idx] = before - 1e-6
            minus = batch_loss_grad(E, U, centers, pos, neg)[0]
            table[idx] = before
            maximum = max(maximum, abs((plus - minus) / 2e-6 - grad[idx]))
        assert maximum < 1e-7, (name, maximum)
        errors[name] = maximum
    return errors


def fit_sgns(sentences, words, index, counts, epochs, dim, window, k, rate,
             seed, subsample=0., batch_size=32):
    rng = np.random.default_rng(seed)
    q = noise_distribution(counts)
    cdf = np.cumsum(q)
    cdf[-1] = 1.
    E = rng.normal(0., .1, (len(words), dim))
    U = np.zeros((len(words), dim))
    history = []
    for epoch in range(epochs):
        pending, total_loss, number = [], 0., 0
        def update(pairs):
            centers = np.array([p[0] for p in pairs], dtype=np.int64)
            positives = np.array([p[1] for p in pairs], dtype=np.int64)
            neg = negatives(q, positives, k, rng, cdf)
            # Solo materializar gradientes de filas presentes, acumulando los
            # índices repetidos antes de escribir cada fila una sola vez.
            e_rows, local_centers = np.unique(centers, return_inverse=True)
            u_rows, local_outputs = np.unique(np.concatenate([positives, neg.ravel()]),
                                              return_inverse=True)
            local_pos = local_outputs[:len(positives)]
            local_neg = local_outputs[len(positives):].reshape(neg.shape)
            loss, dE, dU = batch_loss_grad(E[e_rows], U[u_rows], local_centers,
                                          local_pos, local_neg)
            if not np.isfinite(loss) or not np.isfinite(dE).all() or not np.isfinite(dU).all():
                raise ValueError('Pérdida o gradiente no finito')
            E[e_rows] -= rate * dE
            U[u_rows] -= rate * dU
            return loss * len(pairs), len(pairs)
        for pair in sampled_contexts(sentences, index, counts, window, subsample, rng):
            pending.append(pair)
            if len(pending) == batch_size:
                value, size = update(pending)
                total_loss += value
                number += size
                pending = []
        if pending:
            value, size = update(pending)
            total_loss += value
            number += size
        history.append({'epoch': epoch + 1, 'pairs': number,
                        'mean_loss': total_loss / number if number else None})
    return E, U, history


def neighbors(word, words, E, count=5):
    if word not in words:
        return []
    norms = np.linalg.norm(E, axis=1)
    index = words.index(word)
    if norms[index] <= 1e-12:
        return []
    similarities = np.full(len(words), -np.inf)
    valid = norms > 1e-12
    similarities[valid] = (E[valid] @ E[index]) / (norms[valid] * norms[index])
    similarities[index] = -np.inf
    order = np.argsort(-similarities, kind='stable')
    return [(words[i], float(similarities[i])) for i in order[:count] if np.isfinite(similarities[i])]


def main_small():
    train, valid = tokenize(TRAIN), tokenize(VALID)
    if train == valid:
        raise ValueError('Fragmentos idénticos')
    words, index, counts = vocabulary([train])
    E, _, history = fit_sgns([train], words, index, counts, epochs=8,
                             dim=6, window=2, k=2, rate=.1, seed=SEED,
                             subsample=.01)
    known = [w for w in valid if w in index]
    pairs = list(sampled_contexts([valid], index, counts, 2, 0.,
                                  np.random.default_rng(SEED + 1)))
    print('Gradcheck error absoluto máximo:', gradcheck())
    print('Tokens train/valid:', len(train), len(valid), '| OOV valid:', len(valid) - len(known))
    print('Pares valid con palabras conocidas:', len(pairs),
          '| se filtran OOV antes de crear la ventana')
    print('Historial train:', history)
    print('Vecinos de entrada de', words[0], ':', neighbors(words[0], words, E))
    print('La pérdida de entrenamiento es exploratoria y cambia con los pares y negativos sorteados.')
    print('Los fragmentos son demasiado pequeños para conclusiones semánticas; no hay test.')

# Esta segunda celda es autocontenida: las funciones anteriores no dependen
# de un archivo externo.
import gzip
import hashlib
import json
import os
import time
import urllib.request
from pathlib import Path

import gensim
from gensim.models import Word2Vec

URL = 'https://github.com/RaRe-Technologies/gensim-data/releases/download/text8/text8.gz'
MD5 = '68799af40b6bda07dfa47a32612e5364'
SIZE = 33182058
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
CACHE = Path(os.environ.get('ORYON_TEXT8_CACHE', str(Path.home() / '.cache' / 'oryon-text8')))
OUTPUT = Path(os.environ.get('ORYON_OUTPUT', 'word2vec_text8_output'))
DIM = 30 if SHORT else 100
EPOCHS = 1 if SHORT else 5
MAX_WORDS = 20000 if SHORT else None
WINDOW, NEGATIVE, MIN_COUNT = 2, 5, 2
WORKERS = int(os.environ.get('ORYON_WORKERS', '1'))
if WORKERS < 1 or (SHORT and WORKERS != 1):
    raise ValueError('ORYON_WORKERS debe ser positivo; SHORT exige un trabajador')
ANALOGY_REV = '20c129af10659f7c50e86e3be406df663beff438'
ANALOGY_URL = ('https://raw.githubusercontent.com/tmikolov/word2vec/' +
               ANALOGY_REV + '/questions-words.txt')


def get_text8():
    CACHE.mkdir(parents=True, exist_ok=True)
    path = CACHE / 'text8.gz'
    if not path.exists():
        part = CACHE / 'text8.gz.part'
        try:
            with urllib.request.urlopen(URL, timeout=60) as response, part.open('wb') as out:
                total = 0
                while True:
                    block = response.read(1024 * 1024)
                    if not block:
                        break
                    total += len(block)
                    if total > SIZE:
                        raise ValueError('text8.gz excede el tamaño publicado')
                    out.write(block)
            if part.stat().st_size != SIZE:
                raise ValueError('Tamaño de text8.gz incorrecto')
            md5 = hashlib.md5()
            with part.open('rb') as stream:
                for block in iter(lambda: stream.read(1024 * 1024), b''):
                    md5.update(block)
            if md5.hexdigest() != MD5:
                raise ValueError('MD5 de text8.gz no coincide')
            os.replace(part, path)
        finally:
            if part.exists():
                part.unlink()
    md5, sha = hashlib.md5(), hashlib.sha256()
    with path.open('rb') as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b''):
            md5.update(block)
            sha.update(block)
    if path.stat().st_size != SIZE or md5.hexdigest() != MD5:
        raise ValueError('La copia de text8 no coincide con el catálogo de Gensim')
    return path, sha.hexdigest()


def get_analogies():
    # Fuente versionada, no se ejecuta código remoto. El digest calculado
    # identifica los bytes recibidos; sin un hash externo no los autentica.
    with urllib.request.urlopen(ANALOGY_URL, timeout=60) as response:
        raw = response.read(2_000_001)
    if len(raw) > 2_000_000:
        raise ValueError('Fichero de analogías demasiado grande')
    sha = hashlib.sha256(raw).hexdigest()
    expected = os.environ.get('ORYON_ANALOGIES_SHA256')
    if expected is not None:
        if not re.fullmatch(r'[0-9a-fA-F]{64}', expected):
            raise ValueError('ORYON_ANALOGIES_SHA256 debe tener 64 dígitos hexadecimales')
        if sha != expected.lower():
            raise ValueError('SHA-256 de analogías diferente del esperado')
    questions, section = [], None
    for line in raw.decode('utf-8').splitlines():
        if line.startswith(': '):
            section = line[2:].strip()
        elif line.strip():
            fields = tuple(line.lower().split())
            if section is None or len(fields) != 4:
                raise ValueError('Formato inesperado del benchmark')
            questions.append((section, fields))
    if len(questions) != 19544:
        raise ValueError('Número inesperado de preguntas')
    if SHORT:
        # Selección equiespaciada y determinista en todas las categorías.
        chosen = [questions[i] for i in np.linspace(0, len(questions) - 1, 128, dtype=int)]
    else:
        chosen = questions
    return chosen, {'url': ANALOGY_URL, 'revision': ANALOGY_REV, 'sha256_calculado': sha,
                    'hash_externo_comprobado': expected is not None,
                    'total_fuente': len(questions), 'seleccionadas': len(chosen),
                    'seleccion': '128 índices equiespaciados' if SHORT else 'todas',
                    'licencia_repositorio': 'Apache 2.0; comprobar condiciones para el archivo y su uso',
                    'split': 'benchmark externo de test exploratorio, sin usar para selección'}


def read_sentences(path, limit):
    # Cortes artificiales de 2000 tokens, iguales para ambas implementaciones.
    # No se trata de fronteras de documentos de Wikipedia.
    sentences, sentence, carry, count = [], [], '', 0
    def consume(word):
        nonlocal count, sentence
        if limit is not None and count >= limit:
            return
        if not word.isalpha() or not word.isascii() or word != word.lower():
            raise ValueError('text8 tiene formato inesperado')
        sentence.append(word)
        count += 1
        if len(sentence) == 2000:
            sentences.append(sentence)
            sentence = []
    with gzip.open(path, 'rt', encoding='ascii') as stream:
        while limit is None or count < limit:
            chunk = stream.read(65536)
            if not chunk:
                if carry:
                    consume(carry)
                break
            parts = (carry + chunk).split()
            if chunk[-1].isspace():
                carry = ''
            else:
                carry = parts.pop() if parts else carry + chunk
            for word in parts:
                if limit is not None and count >= limit:
                    break
                consume(word)
    if sentence:
        sentences.append(sentence)
    if len(sentences) < 10:
        raise ValueError('Faltan bloques para separar entrenamiento, validación y test')
    return sentences


def split_sentences(sentences):
    # Contiguos y sin cruzar bloques ni construir vocabulario con validación/test.
    first = int(len(sentences) * .8)
    second = int(len(sentences) * .9)
    return sentences[:first], sentences[first:second], sentences[second:]


def context_metrics(sentences, index, E, chunk_size=4096):
    # Pares originales adyacentes; no crear puentes al descartar OOV.
    # La suma por bloques evita guardar millones de tuplas o puntuaciones.
    norms = np.linalg.norm(E, axis=1)
    left, right = [], []
    candidates, covered, valid_count, total = 0, 0, 0, 0.

    def flush():
        nonlocal valid_count, total
        if not left:
            return
        a, b = np.asarray(left), np.asarray(right)
        valid = (norms[a] > 1e-12) & (norms[b] > 1e-12)
        a, b = a[valid], b[valid]
        if len(a):
            scores = np.einsum('ij,ij->i', E[a], E[b]) / (norms[a] * norms[b])
            total += float(np.sum(scores, dtype=np.float64))
            valid_count += len(a)
        left.clear()
        right.clear()

    for sentence in sentences:
        for a, b in zip(sentence, sentence[1:]):
            candidates += 1
            if a in index and b in index:
                covered += 1
                left.append(index[a])
                right.append(index[b])
                if len(left) >= chunk_size:
                    flush()
    flush()
    return {'candidate_pairs': candidates, 'covered_pairs': covered,
            'cosine_pairs': valid_count,
            'mean_pair_cosine': total / valid_count if valid_count else None}


def analogies(words, E, questions):
    index = {word: i for i, word in enumerate(words)}
    norms = np.linalg.norm(E, axis=1)
    valid_vectors = norms > 1e-12
    unit = np.zeros_like(E)
    unit[valid_vectors] = E[valid_vectors] / norms[valid_vectors, None]
    groups = {}
    pending = []

    def flush():
        if not pending:
            return
        targets = np.stack([item[1] for item in pending])
        scores = targets @ unit.T
        scores[:, ~valid_vectors] = -np.inf
        for i, (group, _, rows, expected) in enumerate(pending):
            scores[i, rows[:3]] = -np.inf
            if not np.isfinite(scores[i]).any():
                group['invalid'] += 1
                continue
            predicted = words[int(np.argmax(scores[i]))]
            group['evaluated'] += 1
            group['correct'] += int(predicted == expected)
        pending.clear()

    for section, question in questions:
        a, b, c, expected = question
        group = groups.setdefault(section, {'total': 0, 'oov': 0, 'invalid': 0,
                                            'evaluated': 0, 'correct': 0})
        group['total'] += 1
        if any(word not in index for word in question):
            group['oov'] += 1
            continue
        rows = [index[w] for w in question]
        if any(not valid_vectors[i] for i in rows):
            group['invalid'] += 1
            continue
        # Suma de vectores unitarios, como 3CosAdd de Gensim.
        target = unit[rows[1]] - unit[rows[0]] + unit[rows[2]]
        if np.linalg.norm(target) <= 1e-12:
            group['invalid'] += 1
            continue
        pending.append((group, target, rows, expected))
        # Acota la matriz temporal de puntuaciones a 32 × vocabulario.
        if len(pending) >= 32:
            flush()
    flush()
    totals = {key: sum(group[key] for group in groups.values())
              for key in ('total', 'oov', 'invalid', 'evaluated', 'correct')}
    for group in list(groups.values()) + [totals]:
        group['accuracy'] = group['correct'] / group['evaluated'] if group['evaluated'] else None
    return {'total': totals, 'categories': groups}


def report_vectors(words, E, validation, test, questions):
    index = {w: i for i, w in enumerate(words)}
    queries = ['king', 'queen', 'computer', 'language']
    return {'table': 'entrada',
            'neighbors': {w: neighbors(w, words, E) for w in queries},
            'analogies': analogies(words, E, questions),
            'validation': context_metrics(validation, index, E),
            'test': context_metrics(test, index, E)}


def main_text8():
    path, sha = get_text8()
    questions, benchmark = get_analogies()
    sentences = read_sentences(path, MAX_WORDS)
    train, validation, test = split_sentences(sentences)
    words, index, counts = vocabulary(train, minimum=MIN_COUNT)
    protocol = {'short': SHORT, 'url': URL, 'compressed_md5': MD5,
                'compressed_sha256_measured': sha, 'seed': SEED,
                'split': 'bloques contiguos 80/10/10; cortes artificiales de 2000 palabras',
                'tokens': {name: sum(map(len, part)) for name, part in
                           [('train', train), ('validation', validation), ('test', test)]},
                'vocabulary': len(words), 'minimum_count': MIN_COUNT, 'dimension': DIM,
                'epochs': EPOCHS, 'window': WINDOW, 'negative': NEGATIVE,
                'subsampling': 'desactivado en ambos para alinear', 'noise_power': .75,
                'license': 'El catálogo de gensim-data indica license: not found; verificar derechos.',
                'workers': WORKERS, 'analogies': benchmark,
                'reproducibility': 'workers=1 y PYTHONHASHSEED fijo favorecen reproducibilidad; '
                                   'varios trabajadores introducen variación de orden.',
                'limitations': 'Split por bloques no garantiza separación por documento ni ausencia de duplicados; '
                               'test se consulta para varios modelos y se considera exploratorio. '
                               'Analogías consultadas para varios modelos: test exploratorio. '
                               'Las duraciones de NumPy incluyen inicialización; las de Gensim excluyen '
                               'creación de vocabulario y modelo. Evaluación no incluida en ninguna.'}
    results = {'protocol': protocol, 'gensim_version': gensim.__version__,
               'numpy_version': np.__version__, 'models': {}}
    print('Protocolo:', protocol)
    print('Gradcheck NumPy:', gradcheck())
    started = time.perf_counter()
    E, U, history = fit_sgns(train, words, index, counts, EPOCHS, DIM, WINDOW,
                             NEGATIVE, .025, SEED, subsample=0., batch_size=128)
    results['models']['numpy_sgns'] = {'training_seconds': time.perf_counter() - started,
                                       'history': history, **report_vectors(words, E, validation, test, questions)}
    del E, U
    for sg in (1, 0):
        for objective in ('negative', 'hs'):
            model = Word2Vec(vector_size=DIM, window=WINDOW,
                             min_count=MIN_COUNT, sg=sg,
                             negative=NEGATIVE if objective == 'negative' else 0,
                             hs=int(objective == 'hs'), ns_exponent=.75,
                             sample=0., shrink_windows=True, workers=WORKERS,
                             seed=SEED, epochs=EPOCHS, alpha=.025, min_alpha=.0001)
            model.build_vocab(train)
            started = time.perf_counter()
            model.train(train, total_examples=model.corpus_count, epochs=EPOCHS)
            training_seconds = time.perf_counter() - started
            name = ('skipgram' if sg else 'cbow') + '_' + objective
            vector_words = list(model.wv.index_to_key)
            assert set(vector_words) == set(words), 'Vocabularios de entrenamiento diferentes'
            result = report_vectors(vector_words, model.wv.vectors, validation, test, questions)
            result['training_seconds'] = training_seconds
            results['models'][name] = result
            del model
    OUTPUT.mkdir(parents=True, exist_ok=True)
    (OUTPUT / 'metrics.json').write_text(json.dumps(results, ensure_ascii=False, indent=2),
                                         encoding='utf-8')
    print('Modelos:', results['models'])
    print('Salida:', OUTPUT / 'metrics.json')
    print('Los cosenos y el benchmark son exploratorios; SHORT solo verifica el recorrido.')
    print('El propio usa SGD por lotes, tasa constante y negativos condicionados; '
          'Gensim usa otra optimización, tasa decreciente y su implementación de colisiones.')


if __name__ == '__main__':
    main_text8()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofGradients with two paths
Prove: Derive SGNS gradients for one center, one positive context and k negatives. Explain a repeated negative index.
0
Vectors are finite and loss sums softplus of the negative positive logit and softplus of each negative logit. Take all vectors before any update.

Step 1 of 3. What is the derivative of softplus(-s) with respect to s?

NumericA very frequent word
With relative frequency f=0.02 and t=0.00001, what discard probability does the paper's formula give, clipped to [0,1]?
NumericThree outputs, three budgets
With V=2²⁰ and a perfectly balanced tree, how many dot products does HS calculate for one word?
QuizThe rare word
You need to represent rare words and choose between HS and SGNS. Which decision is justified by the sources and experiments?
CodeSample without collision
Implement build_noise_table(counts, power=0.75) and sample_negatives(q, positive, k, rng). counts is a finite nonnegative one-dimensional array with positive mass; power is finite and positive. q is a finite normalized probability distribution and positive a valid index. Return k independent integer samples with replacement, excluding positive and renormalizing. Explicitly reject zero remaining mass. Do not modify counts or q.
import numpy as np

def build_noise_table(counts, power=0.75):
  pass

def sample_negatives(q, positive, k, rng):
  pass
Shift+Enter to run

Further connections

Classification-based estimation relates to Noise-contrastive estimation and prefix codes to Huffman coding. The next lesson studies conditions connecting SGNS to a shifted PMI matrix and how those conditions change with the noise distribution.