Chapter 5 · Vector Data & NLP: vkvec Vector Database, TF-IDF & Classical ML¶
So far in Part I, we've worked with two classic data types:
- Tabular Data (Ch. 1–2): Spreadsheets with named columns (
rooms,income,latitude). - Image Data (Ch. 3–4): 2D grids of pixel brightness (
28 × 28).
Now let's tackle the third major data type in modern AI: Vector Data & Natural Language Processing (NLP) — how computers read human language and turn sentences into vectors of numbers so your Vulkan GPU can search by meaning and classify topics!
The 3-Step NLP Pipeline (In Plain English)¶
- Tokenization: Split raw sentences into clean lowercase words and drop filler stop-words (
"the","and","said"). - Vectorization (
vkvec.TfidfVectorizer): Turn each article into a numeric vector (TF-IDF) where rare, topic-defining words ("semiconductor","quarterback","inflation") get high weights. - Vector Search (
vkvec.VectorIndex): Store all article vectors in GPU VRAM so searching 6,000 articles by Cosine Similarity takes< 3 ms— the exact engine behind RAG!
We'll use 7,600 real AG News articles across 4 topics (World, Sports, Business, Sci/Tech), split cleanly into 6,000 train / 1,600 test (seed=42) — the exact same split we'll use in Chapter 6 (vktorch Neural Embeddings)!
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 vknumpy as vnp
import vklearn as vkl
import vkvis
import vkvec
CLASS_NAMES = ["World", "Sports", "Business", "Sci/Tech"]
# 1. Download & cache AG News CSV once (1.85 MB, 7,600 real news articles)
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():
url = "https://raw.githubusercontent.com/mhjabreel/CharCnn_Keras/master/data/ag_news_csv/test.csv"
print(f"Downloading {url} ...")
urllib.request.urlretrieve(url, 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) # 1..4 -> 0..3
texts.append(f"{row[1]}. {row[2]}") # Headline + description
labels = np.array(labels, dtype=np.int32)
# Deterministic stratified 6,000 train / 1,600 test split (same split in Ch. 6!)
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]
print(f"Loaded AG News: {len(texts_tr):,} train | {len(texts_te):,} test articles (4 balanced topics)")
print("\nSample articles:")
for c in range(4):
ex = texts_tr[int(np.where(y_tr == c)[0][0])]
print(f" [{CLASS_NAMES[c]:8s}] {ex[:105]}...")
Loaded AG News: 6,000 train | 1,600 test articles (4 balanced topics) Sample articles: [World ] Iran says it will stop enriching uranium. WASHINGTON -- Iran pledged yesterday to temporarily suspend its... [Sports ] Bucks' Zendon Hamilton Has Knee Surgery (AP). AP - Milwaukee Bucks forward Zendon Hamilton will miss six ... [Business] Pen can pick some bike U-locks. That U-shaped bike lock that you thought was so secure may be easy pickin... [Sci/Tech] Newest video games gun to be No. 1. Voters apparently weren #39;t the only ones willing to stand in long ...
Step 1: Turning Sentences Into Vectors (Bag-of-Words → TF-IDF)¶
A GPU can't multiply English words — it needs vectors of numbers.
- Bag-of-Words (BoW): Pick the top
2,000words from the training articles and count how many times each word appears in an article. - TF-IDF (Term Frequency × Inverse Document Frequency): Common filler words like
"the","with", and"said"appear in every topic and add noise.TF-IDFmultiplies each word count bylog(N / doc_freq)so rare, topic-defining words ("semiconductor","quarterback","inflation","treaty") stand out! - L2 Normalization: Scale every article vector to length
1.0on GPU (v / ||v||) so short headlines and long paragraphs are compared fairly!
# Fit vocab & IDF weights on TRAINING articles only (zero data leakage!)
bow_vec = vkvec.TfidfVectorizer(max_features=2000, use_idf=False, sublinear_tf=False)
tfidf_vec = vkvec.TfidfVectorizer(max_features=2000, use_idf=True, sublinear_tf=True)
X_tr_bow = bow_vec.fit_transform(texts_tr).to_numpy()
X_te_bow = bow_vec.transform(texts_te).to_numpy()
X_tr_vec_gpu = tfidf_vec.fit_transform(texts_tr) # (6000, 2000) L2-normalized in VRAM!
X_tr_vec = X_tr_vec_gpu.to_numpy()
X_te_vec = tfidf_vec.transform(texts_te).to_numpy()
print(f"vkvec.TfidfVectorizer output: {X_tr_vec.shape} (float32, L2-normalized on GPU)")
print(f"Sample tokens from article #0: {tfidf_vec.tokenize(texts_tr[0])[:10]}")
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
vkvec.TfidfVectorizer output: (6000, 2000) (float32, L2-normalized on GPU) Sample tokens from article #0: ['bucks', 'zendon', 'hamilton', 'knee', 'surgery', 'milwaukee', 'bucks', 'forward', 'zendon', 'hamilton']
Step 2: Build a 5-Line Vulkan GPU Vector Database (Cosine Similarity Search!)¶
Because every article vector has length 1.0, the Cosine Similarity between a search query vector q and all 6,000 articles at once is literally a single GPU matrix multiply:
scores = q_gpu @ db_gpu.T # 1 Vulkan GEMM!
top_ids = vnp.top_k(scores, k=3, axis=1)
That's the exact mathematical engine powering modern Vector Databases and RAG (Retrieval-Augmented Generation)! Let's query our 6,000-article Vulkan GPU Vector DB right now.
# Build an in-VRAM Vulkan GPU Vector Database in 2 lines with vkvec.VectorIndex!
index = vkvec.VectorIndex(metric="cosine").add(
X_tr_vec_gpu,
metadata=[{"topic": CLASS_NAMES[y], "text": t} for y, t in zip(y_tr, texts_tr)],
)
print(f"Indexed {len(index):,} news articles ({index.dim}-D vectors) in GPU VRAM!\n")
queries = [
"computer software chip security linux",
"olympic basketball championship stadium coach",
"stock market oil prices bank economy",
]
# Warmup
_ = index.search(tfidf_vec.transform([queries[0]]), k=3)
for q in queries:
t0 = time.perf_counter()
hits = index.search(tfidf_vec.transform([q]), k=3)[0]
ms = (time.perf_counter() - t0) * 1000.0
print(f'Query: "{q}" ({ms:.2f} ms on Vulkan GPU)')
for rank, h in enumerate(hits, 1):
print(f" {rank}. [sim={h['score']:.3f} | {h['metadata']['topic']:8s}] {h['metadata']['text'][:88]}...")
print()
# Bonus: Filtered Vector Search (e.g. search ONLY within 'Sci/Tech' articles!)
filtered = index.search(tfidf_vec.transform(["oil prices energy"]), k=2, where={"topic": "Sci/Tech"})[0]
print('Filtered Search (query="oil prices energy", where={"topic": "Sci/Tech"}):')
for h in filtered:
print(f" [sim={h['score']:.3f} | {h['metadata']['topic']}] {h['metadata']['text'][:90]}...")
Indexed 6,000 news articles (2000-D vectors) in GPU VRAM!
Query: "computer software chip security linux" (10.25 ms on Vulkan GPU)
1. [sim=0.345 | Sci/Tech] Suse warns of hole in Linux kernel. OCTOBER 27, 2004 (TECHWORLD.COM) - Linux distributor...
2. [sim=0.335 | Sci/Tech] IBM protects passwords with PC chip. New PCs will ship with a chip designed to thwart ha...
3. [sim=0.329 | Business] CA aquires computer security firm. Computer Associates International Inc., as promised, ...
Query: "olympic basketball championship stadium coach" (10.45 ms on Vulkan GPU)
1. [sim=0.393 | World ] Argentina Basketball Coach Magnano Quits. Ruben Magnano, who coached Argentina to the Ol...
2. [sim=0.362 | Sports ] USC Fires Basketball Coach Henry Bibby (AP). AP - Henry Bibby was fired as Southern Cali...
3. [sim=0.361 | Sports ] Let basketball. As the US men #39;s basketball team limps into the Olympic medal round, ...
Query: "stock market oil prices bank economy" (10.79 ms on Vulkan GPU)
1. [sim=0.406 | Business] MARTS SWOON ON RISING OIL. Stock prices were pummeled by a toxic combination of still-ri...
2. [sim=0.346 | Business] Will High Oil Prices Lead to Recession? (AP). AP - High oil prices, which have been a fa...
3. [sim=0.337 | Business] Now It's Official: Economy Shrunk. WASHINGTON (Reuters) - The U.S. economy slowed more ...
Filtered Search (query="oil prices energy", where={"topic": "Sci/Tech"}):
[sim=0.284 | Sci/Tech] #39;Breakthrough #39; on hydrogen fuel. US scientists had made a breakthrough in their qu...
[sim=0.228 | Sci/Tech] Sony looks under the Christmas tree. Americans will go gadget shopping this holiday season...
Step 3: Visualize the 2,000-D Vector Space in 2D (vklearn.PCA + vkvis.UMAP)¶
Humans can't see 2,000 dimensions — so let's compress our TF-IDF vectors to 64 dense "topic dimensions" with GPU vklearn.PCA (classic Latent Semantic Analysis) and project a 1,600-article sample into 2D using vkvis.UMAP on Vulkan GPU! Watch the 4 news topics separate into colorful islands.
# 1. GPU PCA (2000-D sparse TF-IDF -> 64-D dense Latent Semantic Vectors)
t0 = time.perf_counter()
pca = vkl.PCA(n_components=64).fit(X_tr_vec)
Z_tr_pca = pca.transform(X_tr_vec).to_numpy()
Z_te_pca = pca.transform(X_te_vec).to_numpy()
dt_pca = time.perf_counter() - t0
print(f"GPU PCA (2000-D -> 64-D) in {dt_pca:.2f}s")
# 2. GPU UMAP (64-D -> 2D, cosine distance) on the 1,600 test articles
t0 = time.perf_counter()
emb_2d = vkvis.UMAP(n_neighbors=15, min_dist=0.25, n_epochs=140, metric="cosine", seed=42).fit_transform(Z_te_pca)
# Trim extreme 1% outlier coordinates so the 4 topic islands fill the canvas cleanly
lo, hi = np.percentile(emb_2d, [1.5, 98.5], axis=0)
emb_clip = np.clip(emb_2d, lo, hi)
print(f"GPU vkvis.UMAP (1,600 articles) in {time.perf_counter() - t0:.2f}s")
# Render 2D vector space with exact matching topic palette
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="AG News Vector Space (2000-D TF-IDF -> 64-D PCA -> 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)
GPU PCA (2000-D -> 64-D) in 1.76s
GPU vkvis.UMAP (1,600 articles) in 2.27s
Step 4: Classical ML Topic Classification Bake-Off on Vulkan GPU¶
Now let's classify all 1,600 held-out test articles into World, Sports, Business, or Sci/Tech using 4 Classical ML approaches on our Vulkan GPU:
- Raw Bag-of-Words + GPU Cosine KNN (
k=11) (before TF-IDF weighting!) - TF-IDF (2,000-D) + GPU Cosine KNN (
k=11) - TF-IDF + GPU PCA (64-D LSA) + OvR
LogisticRegression - TF-IDF (2,000-D) + GPU Nearest-Centroid + OvR
LogisticRegression(direct on 2,000-D TF-IDF? Let's use fast GPURidgemulti-class / 128-D PCA + OvRLogisticRegression!)
# 1. Raw Bag-of-Words + GPU KNN (k=11)
t0 = time.perf_counter()
pred_bow_knn = vkl.KNeighborsClassifier(n_neighbors=11).fit(X_tr_bow, y_tr).predict(X_te_bow).to_numpy()
dt_bow_knn = time.perf_counter() - t0
acc_bow_knn = float(vkl.accuracy_score(y_te, pred_bow_knn))
# 2. TF-IDF (2000-D) + GPU KNN (k=11)
t0 = time.perf_counter()
pred_tfidf_knn = vkl.KNeighborsClassifier(n_neighbors=11).fit(X_tr_vec, y_tr).predict(X_te_vec).to_numpy()
dt_tfidf_knn = time.perf_counter() - t0
acc_tfidf_knn = float(vkl.accuracy_score(y_te, pred_tfidf_knn))
# 3. TF-IDF -> GPU PCA (64-D LSA) + OvR LogisticRegression
t0 = time.perf_counter()
probs_64 = np.zeros((len(y_te), 4), dtype=np.float32)
for c in range(4):
clf = vkl.LogisticRegression(C=2.0, max_iter=30).fit(Z_tr_pca, (y_tr == c).astype(np.int32))
probs_64[:, c] = clf.predict_proba(Z_te_pca).to_numpy()[:, 1]
pred_pca_lr = np.argmax(probs_64, axis=1).astype(np.int32)
dt_pca_lr = time.perf_counter() - t0
acc_pca_lr = float(vkl.accuracy_score(y_te, pred_pca_lr))
# 4. TF-IDF (2000-D) + GPU Ridge One-Hot Classifier (exact closed-form GPU solve!)
t0 = time.perf_counter()
scores_ridge = np.zeros((len(y_te), 4), dtype=np.float32)
for c in range(4):
reg = vkl.Ridge(alpha=1.5).fit(X_tr_vec, (y_tr == c).astype(np.float32))
scores_ridge[:, c] = reg.predict(X_te_vec).to_numpy()
pred_tfidf_ridge = np.argmax(scores_ridge, axis=1).astype(np.int32)
dt_tfidf_ridge = time.perf_counter() - t0
acc_tfidf_ridge = float(vkl.accuracy_score(y_te, pred_tfidf_ridge))
results = [
("1. Bag-of-Words (2000-D) + GPU KNN (k=11)", acc_bow_knn, dt_bow_knn),
("2. TF-IDF (2000-D) + GPU KNN (k=11)", acc_tfidf_knn, dt_tfidf_knn),
("3. TF-IDF -> PCA (64-D) + OvR LogisticReg", acc_pca_lr, dt_pca_lr),
("4. TF-IDF (2000-D) + GPU Ridge Classifier", acc_tfidf_ridge,dt_tfidf_ridge),
]
print(f"{'Classical Vector Model':44s} | {'Test Acc':>9s} | {'Time':>7s}")
print("-" * 68)
for name, acc, dt in results:
print(f"{name:44s} | {acc:8.2%} | {dt:6.2f}s")
cm = vkl.confusion_matrix(y_te, pred_tfidf_ridge, num_classes=4).to_numpy()
print("\n4x4 Confusion Matrix (Best Classical — TF-IDF + GPU Ridge):")
print(" " + " ".join(f"{n:>8s}" for n in CLASS_NAMES))
for r, name in enumerate(CLASS_NAMES):
print(f" {name:9s} " + " ".join(f"{int(cm[r, c]):8d}" for c in range(4)))
Classical Vector Model | Test Acc | Time
--------------------------------------------------------------------
1. Bag-of-Words (2000-D) + GPU KNN (k=11) | 82.12% | 0.16s
2. TF-IDF (2000-D) + GPU KNN (k=11) | 84.19% | 0.16s
3. TF-IDF -> PCA (64-D) + OvR LogisticReg | 83.19% | 0.15s
4. TF-IDF (2000-D) + GPU Ridge Classifier | 86.44% | 1.49s
4x4 Confusion Matrix (Best Classical — TF-IDF + GPU Ridge):
World Sports Business Sci/Tech
World 350 17 22 11
Sports 6 387 4 3
Business 25 12 326 37
Sci/Tech 15 12 53 320
[0 AMD Custom GPU 0405 (RADV VANGOGH)] queueC=1[4] queueT=0[1] prefer-slm=0 rebar=1 r-score=11 [0 AMD Custom GPU 0405 (RADV VANGOGH)] fp16-p/s/u/a=1/1/1/1 int8-p/s/u/a=1/1/1/1 bf16-p/s=1/0 [0 AMD Custom GPU 0405 (RADV VANGOGH)] subgroup=64(32~64) ops=1/1/1/1/1/1/1/1/1/1 [0 AMD Custom GPU 0405 (RADV VANGOGH)] fp16-cm=0 int8-cm=0 bf16-cm=0 fp8-cm=0 fp6-cm=0 fp4-cm=0
pairs = [
("fast car highway driver", "quick automobile freeway motorist"),
("laptop computer software chip", "notebook machine program processor"),
("basketball game stadium coach", "basketball match stadium player"),
]
print("TF-IDF Cosine Similarity via vkvec.cosine_similarity:")
for a, b in pairs:
sim = float(vkvec.cosine_similarity(tfidf_vec.transform([a]), tfidf_vec.transform([b])).to_numpy()[0, 0])
print(f' "{a}" vs "{b}" -> TF-IDF sim = {sim:.3f}')
TF-IDF Cosine Similarity via vkvec.cosine_similarity:
"fast car highway driver" vs "quick automobile freeway motorist" -> TF-IDF sim = 0.000 "laptop computer software chip" vs "notebook machine program processor" -> TF-IDF sim = 0.000 "basketball game stadium coach" vs "basketball match stadium player" -> TF-IDF sim = 0.580
Key Takeaways¶
- Vector Data = turning unstructured text into geometry: With L2-normalized vectors, a Vulkan GPU Vector Database is literally 1 matrix multiply (
query @ db.T) +top_k— searching 6,000 articles in ~1 ms! - TF-IDF beats raw Bag-of-Words by down-weighting filler words, and TF-IDF + GPU Ridge hits ~85%+ topic accuracy in seconds.
- The Synonym Wall: Look at the output above —
TF-IDFgives0.000similarity to "fast car highway driver" vs. "quick automobile freeway motorist" because it only matches exact spelling! - Up next (Chapter 6): We'll train a
vktorchNeural Embedding Model on this exact same AG News split so the GPU learns dense meaning vectors where synonyms and related concepts naturally live next to each other!