fastText: shared subwords, separate evidence
fastText
Trace character features, hashing and OOV contributions; derive repeated-row gradients and distinguish subword vectors from text classification.
fasttextA new spelling can share pieces without sharing a known word entry
Imagine a tiny training vocabulary containing cat, cats, dog, dogs, play, plays and walk. A lookup-table model has no whole-word row for the invented query catlike. Character fragments such as <ca, <cat and cat are available from words already in the vocabulary. Sharing parameters for those fragments gives a way to construct a vector for the new spelling.
The fastText subword model associates vectors with character n-grams and combines them when scoring a word’s contexts. It also keeps a separate whole-word representation for known words. This shares some parameters across spellings while retaining word-specific information. Subword paper, §3.2
A computable vector is not a certificate of meaning. Some fragments may be unseen; hashing can map different fragments to one row; unused rows can still contain their random initialization. Our experiment makes each of those cases visible rather than labeling every nonzero out-of-vocabulary vector a success.
The same fastText library also provides supervised text classification. That is a different task and training objective, discussed below; it should not be confused with learning unsupervised character-subword vectors merely because both use the same tool name. Classification paper, §2
Track feature occurrences, their rows and their training roles
Add boundaries before extracting character n-grams
The subword paper adds < and > around a word so prefixes and suffixes can have different features. This does not require a morphological dictionary: a character n-gram may cross a linguistic morpheme boundary. The paper describes n from 3 through 6; our small default uses 3 through 4. Subword paper, §3.2
For cats, the framed string <cats> gives these seven default character features:
<ca <cat cat cats ats ats> ts>
A known cats additionally gets its whole-word row, for eight feature occurrences in total. Whole-word rows and hash-bucket rows occupy separate regions of the input table. If a framed whole string also falls within the allowed n-gram lengths, its hashed feature remains separate from the known word’s own row.
The implementation operates on Unicode scalar values in a valid Python string. é is one code point, while the canonically related e plus combining acute accent is two; the program does not normalize them automatically. A multi-code-point displayed symbol likewise need not be one unit in this feature extraction. It rejects raw whitespace, literal boundary markers and surrogate code points in a supplied word, keeping the teaching domain explicit. See tokenization and text normalization.
Repeated substrings remain repeated occurrences. For example, aaaa has the trigram aaa at two positions. Replacing the occurrence list with a set would change its contribution. The pinned dictionary code appends subword hashes without deduplicating these occurrences. Dictionary implementation, lines 160–210
Hashing saves table space by accepting collisions
Let V be the known-word vocabulary size and B the bucket count. Known word rows have indices 0,…,V−1. A character feature g uses:
The input table has V+B rows rather than one new row for every distinct character string. Distinct n-grams can collide, and one word can contain several occurrences mapping to the same row. Both affect the sum and its gradient. This is parameter sharing caused by a hash policy, not proof that the strings are linguistically related.
The pinned fastText implementation uses a compatibility variant of FNV-1a on UTF-8 bytes. Its 32-bit recurrence is:
Here ⊕ is bitwise exclusive OR. For a byte b below 128, v=b. For a byte b≥128, the legacy signed-byte conversion makes v=2³²+b−256 before the XOR. Ordinary unsigned-byte FNV-1a uses v=b throughout. This difference preserves compatibility with the released fastText hash convention; substituting a generic hash implementation can change bucket assignments for non-ASCII strings. Dictionary implementation, hash function
The program prints a check: ASCII a hashes to 3826002220 under either convention. For é, whose UTF-8 bytes are C3 A9, the signed-byte result is 1023043777 while the unsigned result is 513665217. For 研究, they are 10380332 and 2284355628. Character boundaries and hash-byte arithmetic are separate decisions.
The paper’s sum and an exported mean are different operations
Let the feature occurrence list be f_1,…,f_m, including the whole-word row when present. With an input vector z_f for each row, define:
The subword paper writes a sum-based context score. The pinned library’s exported word-vector method averages its rows; its hidden-vector helper also averages, as confirmed in both ordinary and SIMD dense-matrix paths. These facts should be described by operation and version, not combined into one unspecified “fastText vector.” Subword paper Export and mode code Dense averaging code
For the same nonzero row sum, sum and mean have the same direction. Their logits against an output vector v differ by m:
where the cosine statement requires both vectors to be nonzero. A positive rescaling cancels in cosine but not inside a sigmoid or softmax. Therefore changing aggregation can change training losses and gradients even when a later cosine query sees the same direction.
A binary objective with shared input rows
For positive context o and supplied noise draws n_1,…,n_K, the lab uses output vectors v_j and the SGNS loss:
Here softplus(s)=log(1+exp(s)) and σ(s)=1/(1+exp(−s)). The paper derives a binary context objective of this form. Our main training uses its sum-style h. The optional mean mode differentiates its own declared average exactly; this allows a gradient check without pretending the two objectives are identical. Subword paper, §3.1
For target occurrences t_r with binary labels y_r, define . If α is 1 for sum or 1/m for mean, and a_g is the multiplicity of input row g:
This accumulates both repeated input buckets and repeated output noise targets. It does not overwrite a shared row’s earlier contribution. The tests compare every parameter derivative against central differences for both aggregation modes.
The pinned library has another update convention to keep visible: a flag controls whether the hidden gradient is divided by the number of input rows, and that flag is enabled for supervised mode. Its unsupervised input-row updates therefore must not be assumed to match this lab’s strict mean chain rule. This article compares the defined operations; it does not declare the original optimizer wrong or claim to reproduce its updates. Model update code Mode flag
The noise distribution belongs to the experiment
The subword paper’s reported setup uses noise proportional to the square root of unigram frequency. The pinned loss code likewise uses power 0.5 and resamples when the draw equals the positive target. This differs from the power 0.75 choice discussed in Word2vec. Subword paper, §4.3 Negative-sampling code
Our fixed-event generator samples with replacement from the explicitly conditioned distribution:
The denominator must be positive when negative draws are requested. With no negative draws, the positive-only objective is supported even for a one-word vocabulary. The code uses exact normalized floating-point weights rather than the author’s finite sampling table, so the distribution and random stream are not claimed to be bit-for-bit library replicas.
Supervised fastText predicts labels, not neighboring words
The classification paper averages word and word-n-gram features into a document representation, then predicts a class. Let x be a normalized feature-count vector, A a D×F embedding matrix and B a C×D class-score matrix. For a single-label classification task:
The score matrix BA has rank at most D. Its parameters are learned from labels; they need not be the vectors learned from unlabeled neighboring-word prediction. The paper also adds hashed word n-grams to retain some local order and discusses hierarchical softmax for many classes. Classification paper, §2
Character n-grams inside a word and word n-grams across a document are different feature units. Likewise, a single-label softmax objective is not the same as a collection of independent context/noise binary losses. The executable program here demonstrates the subword-vector objective; the classification architecture is explained separately rather than presented as an implemented classifier.
Inspect each OOV contribution before trusting the vector
Save the complete block as fasttext.py and run python3 fasttext.py. The checked environment is Python 3.12.4 with NumPy 1.26.4. The program uses six original two-token sentences and keeps the full training event list fixed, including noise draws, while testing deterministic batch descent.
"""Original inspectable subword-vector lab; NumPy 1.26.4.
Explicit Unicode code-point n-grams, legacy signed-byte FNV hashing, repeated
bucket contributions and exact sum/mean chain rules. Trains a fixed tiny SGNS
objective; not an API clone, pretrained language model or quality benchmark.
"""
from collections import Counter
import json,math
import numpy as np
def word_ok(word):
if not isinstance(word,str) or not word or any(c.isspace() or c in '<>' or 0xD800<=ord(c)<=0xDFFF for c in word):raise ValueError('One nonempty token, without whitespace, reserved boundaries or surrogates, required')
return word
def positive_integer(value):
if type(value) is not int or value<1:raise ValueError('Positive integer required')
return value
def substrings(word,minn=3,maxn=6):
word_ok(word);positive_integer(minn);positive_integer(maxn)
if minn>maxn:raise ValueError('minn must not exceed maxn')
framed='<'+word+'>';result=[]
for i in range(len(framed)):
for length in range(minn,min(maxn,len(framed)-i)+1):
if length==1 and (i==0 or i+length==len(framed)):continue
result.append(framed[i:i+length])
return result
def hash32(text,signed_bytes=True):
if not isinstance(text,str) or any(0xD800<=ord(c)<=0xDFFF for c in text):raise ValueError('Unicode scalar string required')
if type(signed_bytes) is not bool:raise ValueError('Boolean hash compatibility policy required')
h=2166136261
for byte in text.encode('utf-8'):
value=byte-256 if signed_bytes and byte>=128 else byte
h=((h^(value&0xffffffff))*16777619)&0xffffffff
return h
def build(sentences,minn=3,maxn=4,buckets=61,dim=3,seed=17):
positive_integer(buckets);positive_integer(dim)
if type(seed) is not int or seed<0:raise ValueError('Nonnegative integer seed required')
if not isinstance(sentences,(list,tuple)) or not sentences:raise ValueError('Tokenized sentences required')
for row in sentences:
if not isinstance(row,(list,tuple)):raise ValueError('Each sentence must be a token list')
for w in row:word_ok(w)
counts=Counter(w for row in sentences for w in row);words=tuple(sorted(counts))
if not words:raise ValueError('No training vocabulary')
grams={g for w in words for g in substrings(w,minn,maxn)};rng=np.random.default_rng(seed)
return {'words':words,'index':{w:i for i,w in enumerate(words)},'counts':np.array([counts[w] for w in words],dtype=float),
'minn':minn,'maxn':maxn,'buckets':buckets,'gram_inventory':grams,'touched_rows':set(),
'parameters':{'input':rng.uniform(-.1,.1,(len(words)+buckets,dim)),'output':rng.uniform(-.1,.1,(len(words),dim))}}
def features(model,word):
word_ok(word);v=len(model['words']);rows=[]
if word in model['index']:rows.append({'id':model['index'][word],'text':word,'kind':'whole_word','seen_gram':None})
for gram in substrings(word,model['minn'],model['maxn']):
rows.append({'id':v+hash32(gram)%model['buckets'],'text':gram,'kind':'subword','seen_gram':gram in model['gram_inventory']})
return rows
def vector(model,word,aggregation='mean'):
if aggregation not in ('sum','mean'):raise ValueError('Choose sum or mean')
trace=features(model,word);params=model['parameters'];ids=[r['id'] for r in trace]
value=params['input'][ids].sum(axis=0) if ids else np.zeros(params['input'].shape[1])
if aggregation=='mean' and ids:value=value/len(ids)
return {'word':word,'known_word':word in model['index'],'aggregation':aggregation,'feature_count':len(ids),'trace':trace,'vector':value.tolist(),
'used_in_update_occurrences':sum(i in model['touched_rows'] for i in ids),'zero_reason':'no_subwords' if not ids else ('zero_sum' if not np.any(value) else None)}
def index_list(values,size,empty=False):
if not isinstance(values,(list,tuple)) or (not values and not empty) or any(type(i) is not int or not 0<=i<size for i in values):raise ValueError('Valid index list required')
return list(values)
def sigmoid(x):
out=np.empty_like(x);positive=x>=0;out[positive]=1/(1+np.exp(-x[positive]));e=np.exp(x[~positive]);out[~positive]=e/(1+e)
return out
def loss_gradient(parameters,inputs,target,negatives,aggregation='sum'):
if not isinstance(parameters,dict) or set(parameters)!= {'input','output'}:raise ValueError('Input and output matrices required')
a,b=(np.asarray(parameters[k],dtype=float) for k in ('input','output'))
if a.ndim!=2 or b.ndim!=2 or not all(a.shape) or not all(b.shape) or a.shape[1]!=b.shape[1] or not np.isfinite(a).all() or not np.isfinite(b).all():raise ValueError('Finite compatible parameter matrices required')
inputs=index_list(inputs,len(a));index_list([target],len(b));negatives=index_list(negatives,len(b),True)
if target in negatives:raise ValueError('This lab requires negative draws to exclude the positive target')
if aggregation not in ('sum','mean'):raise ValueError('Choose sum or mean')
scale=1/len(inputs) if aggregation=='mean' else 1.
with np.errstate(over='raise',invalid='raise'):
try:
h=a[inputs].sum(axis=0)*scale;targets=[target]+negatives;scores=b[targets]@h
signs=np.ones(len(targets));signs[0]=-1;loss=float(np.logaddexp(0,signs*scores).sum());delta=sigmoid(scores);delta[0]-=1
da=np.zeros_like(a);db=np.zeros_like(b);np.add.at(da,inputs,scale*(delta@b[targets]));np.add.at(db,targets,delta[:,None]*h)
except FloatingPointError as error:raise ValueError('Objective arithmetic overflow') from error
if not math.isfinite(loss) or not np.isfinite(da).all() or not np.isfinite(db).all():raise ValueError('Nonfinite objective or gradient')
return loss,{'input':da,'output':db}
def fixed_events(model,sentences,k=2,seed=23):
if type(k) is not int or k<0 or type(seed) is not int or seed<0:raise ValueError('Nonnegative integer draws and seed required')
rng=np.random.default_rng(seed);result=[]
if not isinstance(sentences,(list,tuple)):raise ValueError('Sentence collection required')
for sentence in sentences:
if not isinstance(sentence,(list,tuple)) or any(word_ok(w) not in model['index'] for w in sentence):raise ValueError('Fixed training words required')
for i,word in enumerate(sentence):
for j in [i-1,i+1]:
if not 0<=j<len(sentence):continue
target=model['index'][sentence[j]];weights=np.sqrt(model['counts']);weights[target]=0
if k and not weights.sum():raise ValueError('No supported negative target remains')
negatives=rng.choice(len(weights),size=k,replace=True,p=weights/weights.sum()).tolist() if k else []
result.append({'word':word,'input':[r['id'] for r in features(model,word)],'target':target,'negative':negatives})
return result
def batch(parameters,events,aggregation):
if not events:raise ValueError('Nonempty fixed training event list required')
gradient={k:np.zeros_like(v) for k,v in parameters.items()};total=0.
for row in events:
value,g=loss_gradient(parameters,row['input'],row['target'],row['negative'],aggregation);total+=value
for key in gradient:gradient[key]+=g[key]
return total/len(events),{k:v/len(events) for k,v in gradient.items()}
def train(model,events,steps=60,rate=.2,aggregation='sum'):
if type(steps) is not int or steps<0:raise ValueError('Nonnegative integer steps required')
if isinstance(rate,bool) or not isinstance(rate,(int,float)) or not math.isfinite(rate) or rate<=0:raise ValueError('Positive finite rate required')
result={**model,'parameters':{k:v.copy() for k,v in model['parameters'].items()},'touched_rows':set(model['touched_rows'])}
p=result['parameters'];value,grad=batch(p,events,aggregation);trace=[value]
for _ in range(steps):
norm=sum(float(np.sum(g*g)) for g in grad.values())
if norm<1e-24:break
step=rate
for attempt in range(40):
candidate={k:p[k]-step*grad[k] for k in p}
try:new,ng=batch(candidate,events,aggregation)
except ValueError:new=math.inf
if new<=value-1e-4*step*norm:break
step*=.5
else:raise ValueError('No decreasing step found')
p,value,grad=candidate,new,ng;trace.append(value)
result['touched_rows'].update(i for row in events for i in row['input'])
result['parameters']=p
return result,trace
def demo():
sentences=[['cats','play'],['dogs','play'],['cat','plays'],['dog','plays'],['cats','walk'],['dogs','walk']]
model=build(sentences);events=fixed_events(model,sentences);fitted,trace=train(model,events)
tiny=build([['cat','dog']],minn=3,maxn=3,buckets=1);left=vector(tiny,'zzzz');right=vector(tiny,'qqqq')
short=build([['longword','otherword']],minn=6,maxn=6)
return {'training':sentences,'vocabulary':list(model['words']),'counts':model['counts'].tolist(),'events':len(events),
'config':{'minn':model['minn'],'maxn':model['maxn'],'buckets':model['buckets'],'training_aggregation':'sum','export_aggregation':'mean','noise_power':.5,'exclude_positive':True},
'loss_trace':trace,'queries':[vector(fitted,w) for w in ['cats','catlike','東京']],
'known_sum':vector(fitted,'cats','sum'),'known_mean':vector(fitted,'cats','mean'),
'collision':{'left':left,'right':right,'equal_vectors':left['vector']==right['vector'],'shared_raw_grams':sorted(set(r['text'] for r in left['trace'])&set(r['text'] for r in right['trace']))},
'short_oov':vector(short,'a'),'hash_examples':{word:{'legacy_signed':hash32(word),'unsigned_fnv1a':hash32(word,False)} for word in ['a','é','研究']},
'scope':'Original fixed tiny subword-SGNS objective. Unicode scalar n-grams, repeated hashed occurrences and separate whole-word rows. Paper-style sum training and explicit mean export; not the author unsupervised gradient scaling or API. Touched rows mean participation in accepted updates, not semantic quality. Unused random buckets can contribute to OOV vectors.'}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2,allow_nan=False))
The default configuration uses n-gram lengths 3–4, 61 buckets, three dimensions, sum training and mean export. It constructs 12 directed neighbor events from 12 input tokens. The fixed objective falls from about 2.082240 to 1.211318 over 60 accepted steps. This verifies optimization of a small specified function, not a language-quality result.
Each query prints the raw feature text, row ID, whole-word/subword role and whether the raw n-gram appeared in the vocabulary’s substring inventory. It also counts feature occurrences whose rows participated in accepted training updates. That participation flag does not mean a nonzero update occurred every time or that a feature has learned a useful meaning.
The trained query cats has eight occurrences, all using rows that participated in updates. The OOV query catlike has 13 occurrences: six use rows that participated, but only three raw n-grams were present in the vocabulary inventory. The OOV query 東京 has three occurrences: two map to rows that participated, while none of its raw n-grams were seen. The difference comes from hashing; a previously used bucket does not prove the substring itself was observed.
Unvisited buckets retain random initial rows. They can still contribute to an OOV vector, so even a nonzero vector before any training is possible. With a deliberately tiny one-bucket table, zzzz and qqqq have no shared raw trigrams but receive the same mean vector. This is a controlled collision example, not a statement about the collision rate of a large production model.
An OOV word may also have no eligible subwords. With minimum and maximum n-gram length six, the framed one-letter query <a> is too short, producing a zero vector and reason no_subwords. A known word can still use its independent whole-word row. The scoring function rejects an empty training input instead of dividing by zero.
What the small implementation costs
For a word of L code points, the substring routine examines starts and permitted lengths up to n_max. With bounded n_max, there are O(L n_max) candidate occurrences. Python creates substring copies, and hashing scans their UTF-8 bytes, so a character-level worst-case bound includes O(L n_max²) copying/hashing work. The bound is for this implementation, not a grapheme parser or a claim that hash calls are free.
With V known words, B buckets and dimension D, parameter storage is O((V+B)D+VD). This lab additionally stores the exact raw-gram inventory and query traces for auditing; production systems may make other storage choices. Each ideal sparse SGNS event needs O((m+K)D) score/gradient-contribution work, but our implementation validates and allocates full parameter-shaped gradient arrays on every call. Actual work and storage therefore include O((V+B)D+VD) per event.
Preparing each event also constructs a V-entry square-root noise distribution before sampling. Batch backtracking evaluates the entire fixed event collection repeatedly, with at most 40 proposals per step. Larger bucket counts can reduce forced sharing while increasing both table storage and this dense lab’s overhead; measure a specified implementation before making a speed claim.
Shared spelling is evidence to test
Character fragments may help connect spelling variants, but do not by themselves identify morphemes, word senses or meanings. Normalization policies, script, minimum lengths and boundary symbols alter which parameters are shared. Hash collisions add another source of sharing that has no linguistic guarantee.
A whole-word vector and its character contributions can pull in different directions during training. Exporting a mean or sum must be recorded along with the model version; identical cosine directions do not imply identical logits. Static subword representations still produce the same result for the same spelling across contexts, unlike contextual embeddings.
The toy model demonstrates gradients and support conditions. It does not reproduce pretrained fastText vectors, quantization, a full tokenizer, invalid-UTF-8 handling, supervised classification or the original multi-language evaluations. The code’s input domain and its treatment of untrained buckets are part of its contract, not claims that those issues have disappeared.
Evaluate the intended task with explicit data and OOV categories: seen word, new combination of seen fragments, unseen fragments and collision-only support. A single averaged score can hide these different cases. Embedding evaluation provides the broader comparison framework.
Ask which row supplied the information
1. Understanding: count the feature occurrences
For known cats with n=3–4, list the character features and explain why the input contains eight occurrences. Does OOV catlike receive a new whole-word row during lookup?
Answer: The seven character features are <ca, <cat, cat, cats, ats, ats>, ts>. The known word adds its separate row, making eight. Lookup does not expand the vocabulary, so catlike uses only its 13 character-feature occurrences, not a new whole-word parameter.
2. Hand calculation: duplicate buckets and zero logits
Let input rows be [1,0] and [0,1], output rows all zero, input IDs [0,0], positive target 1 and noise targets [2,2]. Under sum aggregation, find the loss and the two relevant output-row gradients. What changes with mean aggregation at this initial point?
Answer: Sum gives h=[2,0] and three zero logits, so loss is 3ln2. Output row 1 receives [−1,0], while the two negative occurrences sum to [2,0] for row 2. Mean gives h=[1,0], the same initial loss because the output table is zero, and output gradients [−0.5,0] and [1,0]. The input gradient is zero in both cases at this point; nonzero-output finite-difference tests are needed to check its sum/mean scaling.
3. Counterexample: the bucket was trained
An OOV query has no raw n-gram in the training vocabulary, yet two of its hash rows participated in updates. Does that show those n-grams were learned? Explain the one-bucket zzzz/qqqq example.
Answer: No. Other raw strings can map to the same bucket. With one bucket, every eligible trigram uses the same row, and the two equal-length OOV words average the same repeated row despite sharing no raw trigram. Participation history refers to a parameter row; it is not a record of every string or a semantic validation.
4. Transfer: choose the correct fastText task
You have labeled documents for topic classification and an unlabeled corpus for word similarity. Are the two training objectives interchangeable? Can successful vector lookup on every new spelling replace OOV evaluation?
Answer: The classification objective trains averaged document features to predict labels; the subword objective trains word features to discriminate observed contexts from noise. Their learned parameters and outputs answer different questions. Complete lookup coverage only establishes computability under a policy. Evaluate unseen-fragment and collision cases separately before claiming useful OOV behavior.
Distinguish the papers and the pinned library
The subword paper appears in TACL volume 5 (2017), pages 135–146. The separate classification paper appears in the EACL 2017 short-paper proceedings, pages 427–431. The verified publication identities here do not establish the unreviewed preprint-version history. Their method sections support different uses of the fastText name. Subword paper Classification paper
The reviewed library snapshot is commit 1142dc4, dated March 13, 2024. Source inspection covered dictionary construction and hashing, mean vector operations, the supervised gradient flag and square-root negative sampling. Its root MIT license was identified; no library code or pretrained assets were copied or executed. The original Python lab uses explicit policies and finite-difference checks, not a claim of bitwise API or optimizer equivalence.
The source scope includes inspected PDF page 3 (printed137) for subwords, the classification method text and the listed code blocks. The numerical corpus, collision construction, hash checks, gradients and exercises here are original. Author speed and benchmark claims were not adopted as independent results.
Make a prediction, then check
An unseen word gets a nonzero vector from hash buckets. What does that establish by itself?
Learning objectives
- Trace whole-word and character-subword feature occurrences.
- Derive sum and mean gradients with repeated hash indices.
- Distinguish a computable OOV vector from trained semantic evidence.
- Separate unsupervised subword vectors from supervised fastText classification.
Prerequisites & connections
Explore related knowledge →References
- Enriching Word Vectors with Subword Information
Piotr Bojanowski; Edouard Grave; Armand Joulin; Tomas Mikolov · 2017 - Bag of Tricks for Efficient Text Classification
Armand Joulin; Edouard Grave; Piotr Bojanowski; Tomas Mikolov · 2017 - fastText dictionary and subword hashing, pinned snapshot
fastText contributors · 2024 - fastText hidden representation and input update
fastText contributors · 2024 - fastText exported word vectors and model-mode flag
fastText contributors · 2024 - fastText negative-sampling loss
fastText contributors · 2024 - fastText dense row averaging
fastText contributors · 2024
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-08 · Codex single-AI-author technical check: scoped subword and supervised-classifier papers plus pinned author dictionary/model/export/noise/matrix code; eight paired equations, repeated subword occurrences, signed-byte hash, known versus OOV rows, sum/mean strict chain rule versus library scaling, square-root noise and positive exclusion, shared-bucket counterexample, classifier formula as explanation only, dense costs and four explained exercises. No full classifier or author-training reproduction; no semantic or human-peer-review claim.
- Both languages align on eight displayed equations, four explained exercises and seven scoped sources. Kept character versus word n-grams, supervised classification versus subword training, whole-word versus bucket rows, codepoint versus byte rules, paper sum versus pinned mean/gradient scaling, square-root noise and positive-target resampling distinct.
- Production suite executes actual MDX:20 original checks,3 article math cases and6 publication checks. Checked repeated-row sum/mean gradients, signed-byte hashes, cats8/8/7, catlike13/6/3 and Tokyo3/2/0 occurrence counts, untouched/random OOV buckets and a one-bucket equal-vector counterexample. Supervised BAx normalization/rank is a mathematical example, not an implemented classifier.
- Four original SVGs bind the exact MDX results; eight figure tests check data, arithmetic, bars and bilingual references. Isolated18 language/width combinations and four fallback fonts passed after isolating the harness from the Astro development toolbar. Actual desktop/mobile screenshots inspected. Full article browser acceptance recorded separately; no human peer review or upstream code execution.
Source locations checked:
- Enriching Word Vectors with Subword Information · Sections3.1–3.2 and scoped4.2–4.3; PDF page3 (printed137) inspected: character subwords, sum score, binary objective, hashing; square-root noise setting read. No multilingual benchmark reproduction.
- Bag of Tricks for Efficient Text Classification · Scoped section2, extracted text19–103 with43–86 reread: mean feature representation, low-rank class scores, softmax and word n-grams. No classifier program or speed benchmark reproduced here.
- fastText dictionary and subword hashing, pinned snapshot · Lines75–120 and160–210: known/OOV features, whole-word row, signed-byte hash, Unicode start boundaries and repeated n-grams. Root MIT license identified; no upstream execution.
- fastText hidden representation and input update · Lines35–92: mean hidden representation, optional input-gradient normalization and per-row accumulation. This is a code-reading scope, not proof of equivalence with the article optimizer.
- fastText exported word vectors and model-mode flag · Lines100–125 and754–772: mean exported vectors; normalizeGradient enabled for supervised mode. Other API paths and quantized models not reviewed.
- fastText negative-sampling loss · Lines125–195: square-root count table, positive/noise updates and rejection resampling of the positive target. No execution or sampling-table equivalence claim.
- fastText dense row averaging · Lines173–237: SIMD and ordinary row accumulation followed by division by row count; verifies the operation behind the helper name.
Related topics