Chapter 6 · Vector Data & Deep NLP: Learned Neural Embeddings (vktorch + vkvec)¶
In Chapter 5 (05_vector_search_classical_ml.ipynb), we used vkvec.TfidfVectorizer and vkvec.VectorIndex to turn 7,600 AG News articles into 2,000-D word-count vectors and run < 3 ms GPU cosine search — reaching 86.44% topic accuracy, but hitting the "Synonym Wall" (0.000 similarity when two sentences use different words for the same idea).
How Deep NLP Fixes This: Learned Dense Embeddings!¶
Instead of keeping a huge, sparse 2,000-column word-count vector where every word lives on its own isolated axis, we train a vktorch Neural Text Encoder with a 64-D bottleneck layer:
3,000-D text vector → Linear(128) → LayerNorm → GELU → Dropout → Linear(64) → LayerNorm(64-D Neural Embedding!)→ Linear(4)(topic prediction)- To predict the topic accurately through a narrow 64-D bottleneck, the GPU is forced to map related words and synonyms (like
"chip","processor","software","linux","microsoft") into the same region of 64-D vector space! - Then we drop those learned 64-D meaning vectors right into
vkvec.VectorIndex(metric="cosine")for 31× smaller, faster semantic search!
import csv, sys, time, urllib.request
from pathlib import Path
_root = next((p for p in [Path.cwd(), *Path.cwd().parents] if (p / "vknumpy").is_dir()), Path.cwd())
if str(_root) not in sys.path:
sys.path.insert(0, str(_root))
import numpy as np
from PIL import Image, ImageDraw
from IPython.display import display
import vklearn as vkl
import vkvis
import vkvec
import vktorch as vt
from vktorch import nn, optim
from vktorch.data import DataLoader, TensorDataset
CLASS_NAMES = ["World", "Sports", "Business", "Sci/Tech"]
# 1. Load exact same cached AG News dataset & 6,000 / 1,600 split (seed=42) as Chapter 5
data_dir = Path(_root) / "examples" / "tldr_end2end" / "data" / "ag_news"
data_dir.mkdir(parents=True, exist_ok=True)
csv_path = data_dir / "ag_news_7600.csv"
if not csv_path.exists():
urllib.request.urlretrieve(
"https://raw.githubusercontent.com/mhjabreel/CharCnn_Keras/master/data/ag_news_csv/test.csv",
csv_path,
)
texts, labels = [], []
with open(csv_path, encoding="utf-8") as f:
for row in csv.reader(f):
labels.append(int(row[0]) - 1)
texts.append(f"{row[1]}. {row[2]}")
labels = np.array(labels, dtype=np.int32)
rng = np.random.default_rng(42)
tr_idx, te_idx = [], []
for c in range(4):
c_idx = np.where(labels == c)[0]
rng.shuffle(c_idx)
tr_idx.append(c_idx[:1500])
te_idx.append(c_idx[1500:1900])
tr_idx = np.concatenate(tr_idx); rng.shuffle(tr_idx)
te_idx = np.concatenate(te_idx); rng.shuffle(te_idx)
texts_tr = [texts[i] for i in tr_idx]
texts_te = [texts[i] for i in te_idx]
y_tr, y_te = labels[tr_idx], labels[te_idx]
# Vectorize text with vkvec.TfidfVectorizer (3,000-word vocab, fit on train only)
vec = vkvec.TfidfVectorizer(max_features=3000, use_idf=True, sublinear_tf=True)
X_tr = vec.fit_transform(texts_tr).to_numpy()
X_te = vec.transform(texts_te).to_numpy()
print(f"Ready! Train: {X_tr.shape} | Test: {X_te.shape} (4 balanced topics)")
ggml_vulkan: Found 1 Vulkan devices: ggml_vulkan: 0 = AMD Custom GPU 0405 (RADV VANGOGH) (radv) | uma: 1 | rebar: 1 | fp16: 0 | bf16: 0 | fp4: 0 | warp size: 32 | shared memory: 65536 | int dot: 1 | matrix cores: none
Ready! Train: (6000, 3000) | Test: (1600, 3000) (4 balanced topics)
Step 1: Train a vktorch Neural Embedding Encoder on Vulkan GPU¶
Notice the .encode(x) method below: it stops right at the 64-D emb_norm layer, giving us a compact 64-number meaning vector for any English sentence! Every LayerNorm, GELU, CrossEntropy, and AdamW step runs in our fused SPIR-V GPU shaders.
class NeuralTextEncoder(nn.Module):
def __init__(self, vocab_dim: int, emb_dim: int = 64, num_classes: int = 4, seed: int = 42):
super().__init__()
self.fc1 = nn.Linear(vocab_dim, 128, seed=seed)
self.norm1 = nn.LayerNorm(128)
self.drop1 = nn.Dropout(0.35)
self.fc_emb = nn.Linear(128, emb_dim, seed=seed + 1)
self.emb_norm = nn.LayerNorm(emb_dim)
self.drop2 = nn.Dropout(0.25)
self.head = nn.Linear(emb_dim, num_classes, seed=seed + 2)
def encode(self, x: vt.Tensor) -> vt.Tensor:
h = self.drop1(self.norm1(self.fc1(x)).gelu())
return self.emb_norm(self.fc_emb(h))
def forward(self, x: vt.Tensor) -> vt.Tensor:
emb = self.encode(x)
return self.head(self.drop2(emb.gelu()))
model = NeuralTextEncoder(X_tr.shape[1], emb_dim=64, num_classes=4, seed=42)
print(f"NeuralTextEncoder parameters: {model.num_parameters():,}")
epochs = 16
opt = optim.AdamW(model.parameters(), lr=3e-3, weight_decay=2e-2)
sched = optim.CosineAnnealingLR(opt, T_max=epochs, eta_min=1e-4)
crit = nn.CrossEntropyLoss()
loader = DataLoader(TensorDataset(X_tr, y_tr), batch_size=256, shuffle=True, seed=42)
X_te_t = vt.Tensor(X_te, requires_grad=False)
best_acc, best_state = 0.0, None
t0 = time.perf_counter()
for ep in range(1, epochs + 1):
model.train()
ep_loss = 0.0
for xb, yb in loader:
opt.zero_grad()
loss = crit(model(xb), yb)
loss.backward()
optim.clip_grad_norm_(model.parameters(), 2.0)
opt.step()
ep_loss += loss.item()
sched.step()
model.eval()
with vt.no_grad():
preds = np.argmax(model(X_te_t).numpy(), axis=1)
acc = float(np.mean(preds == y_te))
if acc > best_acc:
best_acc = acc
best_state = model.state_dict()
if ep == 1 or ep % 4 == 0 or ep == epochs:
print(f" Epoch {ep:2d}/{epochs} | Train Loss: {ep_loss / len(loader):.4f} | Test Acc: {acc:6.2%} | lr={opt.lr:.5f}")
dt_nn = time.perf_counter() - t0
model.load_state_dict(best_state)
model.eval()
print(f"\nFinished {epochs} epochs in {dt_nn:.1f}s -> Best Neural NLP Test Accuracy: {best_acc:.2%}")
NeuralTextEncoder parameters: 393,028
Epoch 1/16 | Train Loss: 0.6742 | Test Acc: 87.31% | lr=0.00297
Epoch 4/16 | Train Loss: 0.0635 | Test Acc: 84.62% | lr=0.00258
Epoch 8/16 | Train Loss: 0.0110 | Test Acc: 84.12% | lr=0.00155
Epoch 12/16 | Train Loss: 0.0038 | Test Acc: 84.00% | lr=0.00052
Epoch 16/16 | Train Loss: 0.0030 | Test Acc: 83.56% | lr=0.00010 Finished 16 epochs in 14.2s -> Best Neural NLP Test Accuracy: 87.31%
Step 2: Index the 64-D Neural Embeddings in vkvec.VectorIndex & Break the Synonym Wall!¶
Now let's extract the 64-D learned embeddings for all 6,000 training articles and 1,600 test articles, store them in a vkvec.VectorIndex(metric="cosine"), and test:
# 1. Extract 64-D learned neural embeddings on Vulkan GPU
def encode_texts(doc_list):
x_np = vec.transform(doc_list).to_numpy()
with vt.no_grad():
return model.encode(vt.Tensor(x_np)).numpy()
E_tr = encode_texts(texts_tr) # (6000, 64)
E_te = encode_texts(texts_te) # (1600, 64)
# 2. Build a compact 64-D Vulkan GPU Vector Database with vkvec!
neural_index = vkvec.VectorIndex(metric="cosine").add(
E_tr,
metadata=[{"topic": CLASS_NAMES[y], "text": t} for y, t in zip(y_tr, texts_tr)],
)
# 3. Evaluate Neural Embeddings + GPU KNN (k=11) vs Classical ML (Ch. 5)
t0 = time.perf_counter()
pred_emb_knn = vkl.KNeighborsClassifier(n_neighbors=11).fit(E_tr, y_tr).predict(E_te).to_numpy()
dt_eknn = time.perf_counter() - t0
acc_emb_knn = float(vkl.accuracy_score(y_te, pred_emb_knn))
leaderboard = [
("1. Bag-of-Words (2000-D) + GPU KNN [Ch.5]", 0.8212, "0.20s"),
("2. TF-IDF -> PCA (64-D) + LogReg [Ch.5]", 0.8319, "0.16s"),
("3. TF-IDF (2000-D) + GPU KNN [Ch.5]", 0.8419, "0.17s"),
("4. TF-IDF (2000-D) + GPU Ridge [Ch.5]", 0.8644, "1.40s"),
("5. vktorch 64-D Embeddings + GPU KNN [Ch.6]", acc_emb_knn, f"{dt_eknn:.2f}s"),
("6. vktorch Neural NLP Classifier [Ch.6]", best_acc, f"{dt_nn:.1f}s"),
]
print(f"{'Vector / NLP Model':46s} | {'Test Acc':>9s} | {'Time':>7s}")
print("-" * 70)
for name, acc, ts in leaderboard:
print(f"{name:46s} | {acc:8.2%} | {ts:>7s}")
# 4. Breaking the Synonym Wall! Compare TF-IDF vs 64-D Neural Embedding Cosine Similarity
print("\nBreaking the Synonym Wall (TF-IDF vs. Learned 64-D Neural Embeddings):")
pairs = [
("laptop computer software chip", "internet microsoft processor security"),
("stock market oil prices bank", "wall street earnings economy profit"),
("olympic basketball coach game", "football playoff stadium championship"),
("laptop computer software chip", "football playoff stadium championship"), # unrelated control!
]
for a, b in pairs:
s_tfidf = float(vkvec.cosine_similarity(vec.transform([a]), vec.transform([b])).to_numpy()[0, 0])
s_nn = float(vkvec.cosine_similarity(encode_texts([a]), encode_texts([b])).to_numpy()[0, 0])
print(f' "{a}" vs "{b}"')
print(f" TF-IDF sim = {s_tfidf:+.3f} | Neural Embedding sim = {s_nn:+.3f}")
# 5. Live Neural Vector Search on 64-D vkvec.VectorIndex
q = "microsoft security software linux"
t0 = time.perf_counter()
hits = neural_index.search(encode_texts([q]), k=3)[0]
ms = (time.perf_counter() - t0) * 1000.0
print(f'\nNeural Vector DB Search: "{q}" ({ms:.2f} ms in 64-D VRAM):')
for rank, h in enumerate(hits, 1):
print(f" {rank}. [sim={h['score']:.3f} | {h['metadata']['topic']:8s}] {h['metadata']['text'][:88]}...")
Vector / NLP Model | Test Acc | Time
----------------------------------------------------------------------
1. Bag-of-Words (2000-D) + GPU KNN [Ch.5] | 82.12% | 0.20s
2. TF-IDF -> PCA (64-D) + LogReg [Ch.5] | 83.19% | 0.16s
3. TF-IDF (2000-D) + GPU KNN [Ch.5] | 84.19% | 0.17s
4. TF-IDF (2000-D) + GPU Ridge [Ch.5] | 86.44% | 1.40s
5. vktorch 64-D Embeddings + GPU KNN [Ch.6] | 87.94% | 0.04s
6. vktorch Neural NLP Classifier [Ch.6] | 87.31% | 14.2s
Breaking the Synonym Wall (TF-IDF vs. Learned 64-D Neural Embeddings):
"laptop computer software chip" vs "internet microsoft processor security"
TF-IDF sim = +0.000 | Neural Embedding sim = +0.943
"stock market oil prices bank" vs "wall street earnings economy profit"
TF-IDF sim = +0.000 | Neural Embedding sim = +0.946
"olympic basketball coach game" vs "football playoff stadium championship"
TF-IDF sim = +0.000 | Neural Embedding sim = +0.991
"laptop computer software chip" vs "football playoff stadium championship"
TF-IDF sim = +0.000 | Neural Embedding sim = -0.244
Neural Vector DB Search: "microsoft security software linux" (8.60 ms in 64-D VRAM):
1. [sim=0.993 | Sci/Tech] Injection Flaw Found in Browsers. Danish security research firm Secunia has reported a v...
2. [sim=0.993 | Sci/Tech] IBM Unveils New Storage Technology. IBM recently unveiled the TotalStorage DS6000, a rou...
3. [sim=0.992 | Sci/Tech] Interview: OSDL chief Stuart Cohen - Part 2. In the second of a two-part interview, Open...
Step 3: Visualize the Learned 64-D Neural Vector Space (vkvis.UMAP) & Save Index¶
Compare this 2D vkvis.UMAP map of our 64-D Neural Embeddings against Chapter 5's raw TF-IDF PCA map — notice how cleanly the 4 news topics (World, Sports, Business, Sci/Tech) separate into distinct, tight clusters!
Finally, we save both the trained vktorch encoder (.npz) and the vkvec.VectorIndex (.npz + .meta.json) so you can reload your semantic search engine in 2 lines anytime.
# 1. GPU UMAP on the 1,600 test articles' 64-D Neural Embeddings
emb_2d = vkvis.UMAP(n_neighbors=15, min_dist=0.25, n_epochs=140, metric="cosine", seed=42).fit_transform(E_te)
lo, hi = np.percentile(emb_2d, [1.5, 98.5], axis=0)
emb_clip = np.clip(emb_2d, lo, hi)
hex_pal = ["#36f9f6", "#fede5d", "#72f1b8", "#ff7edb"]
rgb_pal = [(54, 249, 246), (254, 222, 93), (114, 241, 184), (255, 126, 219)]
img_umap = vkvis.render_embedding(
emb_clip, labels=y_te, width=640, height=440, point_size=3, palette=hex_pal,
background="#161224",
title="Learned 64-D Neural Embedding Space (vktorch -> 2D GPU UMAP)",
)
bar = Image.new("RGB", (img_umap.width, img_umap.height + 36), (22, 18, 36))
bar.paste(img_umap.convert("RGB"), (0, 0))
dr = ImageDraw.Draw(bar)
for c, name in enumerate(CLASS_NAMES):
x0 = 40 + c * 150
dr.ellipse((x0, img_umap.height + 11, x0 + 12, img_umap.height + 23), fill=rgb_pal[c])
dr.text((x0 + 18, img_umap.height + 11), f"{c}: {name}", fill=(244, 238, 228))
display(bar)
# 2. Persist BOTH the vktorch Neural Encoder and the vkvec Vector Database!
vt.save(model.state_dict(), data_dir / "ag_news_encoder.npz")
neural_index.save(data_dir / "ag_news_neural_index.npz")
reloaded_idx = vkvec.VectorIndex.load(data_dir / "ag_news_neural_index.npz")
print(f"Saved & reloaded vkvec.VectorIndex ({len(reloaded_idx):,} x {reloaded_idx.dim}-D vectors) cleanly!")
Saved & reloaded vkvec.VectorIndex (6,000 x 64-D vectors) cleanly!
Step 5 · Production Hybrid Search: Fusing BM25 Keywords + 64-D Neural Embeddings (vkvec.HybridIndex)¶
Neural embeddings shattered the Synonym Wall — so should we throw away keyword search completely?
No! In real-world production AI & RAG systems (Elasticsearch, Qdrant, Weaviate), neural embeddings have one blind spot: rare exact strings — like a specific company name, stock ticker, product model (RTX4090), or error code (ERR504). Meanwhile, classic Okapi BM25 (an inverted full-text index) nails exact words with 100% precision.
The production solution is Hybrid Search with Reciprocal Rank Fusion (RRF):
- Run GPU Vector Search (
vkvec.VectorIndex) to capture meaning & synonyms. - Run BM25 Full-Text Search (
vkvec.BM25Index) to capture exact names, codes & tickers. - Fuse both ranked lists with RRF:
score(d) = sum(w / (60 + rank))— completely scale-invariant, no fragile score calibration needed!
vkvec.HybridIndex wraps both engines into a single 3-line Vulkan-accelerated API.
# Build a HybridIndex (Vulkan GPU 64-D Neural Vectors + Okapi BM25 Inverted Index)
t0 = time.perf_counter()
hybrid = vkvec.HybridIndex(metric="cosine").add(
E_tr,
texts_tr,
metadata=[{"topic": CLASS_NAMES[y], "text": t} for y, t in zip(y_tr, texts_tr)],
)
dt_build = time.perf_counter() - t0
print(f"Indexed {len(hybrid):,} articles into vkvec.HybridIndex ({hybrid.dim}-D GPU + {hybrid.bm25_index.vocab_size:,} BM25 terms) in {dt_build:.2f}s\n")
queries = [
("IBM Linux enterprise server chip", None),
("Boeing airline jet fuel earnings", {"topic": "Business"}),
]
for q_text, where_filter in queries:
q_vec = encode_texts([q_text])
vec_hits = hybrid.search_vector(q_vec, k=3, where=where_filter)[0]
bm_hits = hybrid.search_bm25(q_text, k=3, where=where_filter)[0]
hyb_hits = hybrid.search(q_vec, q_text, k=3, where=where_filter, mode="rrf", alpha=0.5)[0]
filt_lbl = f" [filter={where_filter}]" if where_filter else ""
print(f"=== Query: {q_text!r}{filt_lbl} ===")
for mode_name, hits in [("Neural Vector Only", vec_hits), ("BM25 Keyword Only ", bm_hits), ("Hybrid RRF (50/50)", hyb_hits)]:
top = hits[0]
snippet = top["metadata"]["text"][:88].replace("\n", " ")
print(f" {mode_name} -> [{top['metadata']['topic']:8s}] (score={top['score']:.4f}) {snippet}...")
print()
Indexed 6,000 articles into vkvec.HybridIndex (64-D GPU + 19,615 BM25 terms) in 0.22s
=== Query: 'IBM Linux enterprise server chip' ===
Neural Vector Only -> [Sci/Tech] (score=0.9943) IBM Unveils New Storage Technology. IBM recently unveiled the TotalStorage DS6000, a rou...
BM25 Keyword Only -> [Sci/Tech] (score=18.9975) China's Red Flag Linux to focus on enterprise. Red Flag Software Co., the company behind...
Hybrid RRF (50/50) -> [Sci/Tech] (score=0.0156) Novell ships Desktop Linux for the enterprise. NOVELL Inc has announced the availability...
=== Query: 'Boeing airline jet fuel earnings' [filter={'topic': 'Business'}] ===
Neural Vector Only -> [Business] (score=0.9825) Check Boeing sops, Airbustells US Check Boeing sops, Airbustells <b>...</b>....
BM25 Keyword Only -> [Business] (score=13.7922) Boeing CEO: Jet Market Recovery Slower (Reuters). Reuters - Boeing Co. Chief Executive H...
Hybrid RRF (50/50) -> [Business] (score=0.0138) BA hikes oil surcharge by up to 8 per ticket. British Airways, Europe #39;s biggest airl...
What Did We Learn Across All 3 Data Types (Chapters 1–6)?¶
- Tabular Data (Ch. 1–2 — Housing): Feature engineering + Residual MLP beat Classical ML (
$69.6k → $48.2kRMSE). - Image Data (Ch. 3–4 — Fashion-MNIST): 2D
Conv2dCNN beat hand-crafted Sobel/HOG features (81.5% → 87.7%). - Vector / Text Data & NLP (Ch. 5–6 — AG News):
vktorchlearned compact 64-D neural embeddings (31× smaller than 2,000-DTF-IDF!) that broke past the Synonym Wall (giving high similarity to related concepts with zero shared words!) and beat ClassicalTF-IDFon topic classification — all indexed invkvec.VectorIndexon your Vulkan GPU!