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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Step 2: BERTopic + UMAP clustering on GPU.
|
| 3 |
+
Run this on RUNPOD (2x RTX 5090, 64GB VRAM).
|
| 4 |
+
|
| 5 |
+
Input: embeddings.npz + doc_metadata.jsonl (from Step 1)
|
| 6 |
+
Output: bertopic_results.jsonl (doc_id -> topic assignments + labels)
|
| 7 |
+
topic_info.json (topic descriptions)
|
| 8 |
+
umap_coords.npz (2D coordinates for visualization)
|
| 9 |
+
|
| 10 |
+
Install: pip install bertopic cuml-cu12 hdbscan umap-learn plotly
|
| 11 |
+
(or: pip install bertopic[all] cuml-cu12)
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import json
|
| 15 |
+
import time
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
# ── Configuration ─────────────────────────────────────────────────────────────
|
| 19 |
+
|
| 20 |
+
WORKSPACE = "/workspace" # RunPod default
|
| 21 |
+
EMBEDDINGS_FILE = f"{WORKSPACE}/embeddings.npz"
|
| 22 |
+
METADATA_FILE = f"{WORKSPACE}/doc_metadata.jsonl"
|
| 23 |
+
OUTPUT_DIR = WORKSPACE
|
| 24 |
+
|
| 25 |
+
# BERTopic parameters
|
| 26 |
+
MIN_TOPIC_SIZE = 50 # minimum docs per topic
|
| 27 |
+
NR_TOPICS = "auto" # let BERTopic decide, or set int like 100
|
| 28 |
+
UMAP_N_NEIGHBORS = 15
|
| 29 |
+
UMAP_N_COMPONENTS = 5 # internal UMAP dims for clustering
|
| 30 |
+
UMAP_MIN_DIST = 0.0
|
| 31 |
+
UMAP_METRIC = "cosine"
|
| 32 |
+
|
| 33 |
+
# Visualization UMAP (separate 2D projection)
|
| 34 |
+
VIZ_N_COMPONENTS = 2
|
| 35 |
+
VIZ_N_NEIGHBORS = 15
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def main():
|
| 39 |
+
t_start = time.time()
|
| 40 |
+
|
| 41 |
+
# ── Load data ─────────────────────────────────────────────────────────────
|
| 42 |
+
print("Loading embeddings...")
|
| 43 |
+
data = np.load(EMBEDDINGS_FILE)
|
| 44 |
+
embeddings = data["embeddings"] # (N, 384)
|
| 45 |
+
doc_ids = data["doc_ids"] # (N,)
|
| 46 |
+
print(f" Shape: {embeddings.shape}, dtype: {embeddings.dtype}")
|
| 47 |
+
print(f" Memory: {embeddings.nbytes / 1e9:.2f} GB")
|
| 48 |
+
|
| 49 |
+
print("Loading metadata...")
|
| 50 |
+
metadata = {}
|
| 51 |
+
with open(METADATA_FILE) as f:
|
| 52 |
+
for line in f:
|
| 53 |
+
d = json.loads(line)
|
| 54 |
+
metadata[d["id"]] = d
|
| 55 |
+
print(f" Documents: {len(metadata)}")
|
| 56 |
+
|
| 57 |
+
# ── Try GPU-accelerated UMAP (cuML), fall back to CPU ─────────────────────
|
| 58 |
+
try:
|
| 59 |
+
from cuml.manifold import UMAP as cuUMAP
|
| 60 |
+
print("\nUsing GPU-accelerated UMAP (cuML)")
|
| 61 |
+
umap_model = cuUMAP(
|
| 62 |
+
n_neighbors=UMAP_N_NEIGHBORS,
|
| 63 |
+
n_components=UMAP_N_COMPONENTS,
|
| 64 |
+
min_dist=UMAP_MIN_DIST,
|
| 65 |
+
metric=UMAP_METRIC,
|
| 66 |
+
random_state=42,
|
| 67 |
+
)
|
| 68 |
+
USE_GPU = True
|
| 69 |
+
except ImportError:
|
| 70 |
+
from umap import UMAP
|
| 71 |
+
print("\nUsing CPU UMAP (cuML not available)")
|
| 72 |
+
umap_model = UMAP(
|
| 73 |
+
n_neighbors=UMAP_N_NEIGHBORS,
|
| 74 |
+
n_components=UMAP_N_COMPONENTS,
|
| 75 |
+
min_dist=UMAP_MIN_DIST,
|
| 76 |
+
metric=UMAP_METRIC,
|
| 77 |
+
random_state=42,
|
| 78 |
+
low_memory=True,
|
| 79 |
+
)
|
| 80 |
+
USE_GPU = False
|
| 81 |
+
|
| 82 |
+
# ── HDBSCAN ───────────────────────────────────────────────────────────────
|
| 83 |
+
try:
|
| 84 |
+
from cuml.cluster import HDBSCAN as cuHDBSCAN
|
| 85 |
+
print("Using GPU-accelerated HDBSCAN (cuML)")
|
| 86 |
+
hdbscan_model = cuHDBSCAN(
|
| 87 |
+
min_cluster_size=MIN_TOPIC_SIZE,
|
| 88 |
+
min_samples=10,
|
| 89 |
+
gen_min_span_tree=True,
|
| 90 |
+
prediction_data=True,
|
| 91 |
+
)
|
| 92 |
+
except ImportError:
|
| 93 |
+
from hdbscan import HDBSCAN
|
| 94 |
+
print("Using CPU HDBSCAN")
|
| 95 |
+
hdbscan_model = HDBSCAN(
|
| 96 |
+
min_cluster_size=MIN_TOPIC_SIZE,
|
| 97 |
+
min_samples=10,
|
| 98 |
+
gen_min_span_tree=True,
|
| 99 |
+
prediction_data=True,
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
# ── BERTopic ──────────────────────────────────────────────────────────────
|
| 103 |
+
from bertopic import BERTopic
|
| 104 |
+
from bertopic.vectorizers import ClassTfidfTransformer
|
| 105 |
+
from sklearn.feature_extraction.text import CountVectorizer
|
| 106 |
+
|
| 107 |
+
# We already have embeddings, so no embedding model needed
|
| 108 |
+
# We need document texts for topic representation (c-TF-IDF)
|
| 109 |
+
# If no texts available, BERTopic can still cluster but won't generate labels
|
| 110 |
+
# We'll use the file paths as pseudo-documents and rely on keyword extraction
|
| 111 |
+
|
| 112 |
+
print("\nPreparing document texts from metadata...")
|
| 113 |
+
# Use source_section + filename as lightweight pseudo-text
|
| 114 |
+
# The actual topic labeling will come from the cluster structure
|
| 115 |
+
docs = []
|
| 116 |
+
for doc_id in doc_ids:
|
| 117 |
+
meta = metadata.get(int(doc_id), {})
|
| 118 |
+
section = meta.get("section", "unknown")
|
| 119 |
+
path = meta.get("path", "")
|
| 120 |
+
fname = path.split("/")[-1] if path else ""
|
| 121 |
+
docs.append(f"{section} {fname}")
|
| 122 |
+
|
| 123 |
+
vectorizer = CountVectorizer(stop_words="english", ngram_range=(1, 2))
|
| 124 |
+
ctfidf = ClassTfidfTransformer(reduce_frequent_words=True)
|
| 125 |
+
|
| 126 |
+
print("\nInitializing BERTopic...")
|
| 127 |
+
topic_model = BERTopic(
|
| 128 |
+
umap_model=umap_model,
|
| 129 |
+
hdbscan_model=hdbscan_model,
|
| 130 |
+
vectorizer_model=vectorizer,
|
| 131 |
+
ctfidf_model=ctfidf,
|
| 132 |
+
nr_topics=NR_TOPICS,
|
| 133 |
+
top_n_words=10,
|
| 134 |
+
verbose=True,
|
| 135 |
+
calculate_probabilities=False, # saves memory at 234K docs
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
# ── Fit ───────────────────────────────────────────────────────────────────
|
| 139 |
+
print(f"\nFitting BERTopic on {len(embeddings)} documents...")
|
| 140 |
+
t_fit = time.time()
|
| 141 |
+
topics, probs = topic_model.fit_transform(docs, embeddings=embeddings)
|
| 142 |
+
print(f"Fit complete in {(time.time() - t_fit) / 60:.1f} minutes")
|
| 143 |
+
|
| 144 |
+
# ── Topic info ────────────────────────────────────────────────────────────
|
| 145 |
+
topic_info = topic_model.get_topic_info()
|
| 146 |
+
print(f"\nTopics discovered: {len(topic_info) - 1}") # -1 for outlier topic
|
| 147 |
+
print(f"Outlier documents (topic -1): {(np.array(topics) == -1).sum()}")
|
| 148 |
+
print("\nTop 20 topics:")
|
| 149 |
+
print(topic_info.head(20).to_string())
|
| 150 |
+
|
| 151 |
+
# ── 2D UMAP for visualization ─────────────────────────────────────────────
|
| 152 |
+
print("\nComputing 2D UMAP projection for visualization...")
|
| 153 |
+
t_viz = time.time()
|
| 154 |
+
try:
|
| 155 |
+
if USE_GPU:
|
| 156 |
+
viz_umap = cuUMAP(
|
| 157 |
+
n_neighbors=VIZ_N_NEIGHBORS,
|
| 158 |
+
n_components=VIZ_N_COMPONENTS,
|
| 159 |
+
min_dist=0.1,
|
| 160 |
+
metric=UMAP_METRIC,
|
| 161 |
+
random_state=42,
|
| 162 |
+
)
|
| 163 |
+
else:
|
| 164 |
+
from umap import UMAP
|
| 165 |
+
viz_umap = UMAP(
|
| 166 |
+
n_neighbors=VIZ_N_NEIGHBORS,
|
| 167 |
+
n_components=VIZ_N_COMPONENTS,
|
| 168 |
+
min_dist=0.1,
|
| 169 |
+
metric=UMAP_METRIC,
|
| 170 |
+
random_state=42,
|
| 171 |
+
low_memory=True,
|
| 172 |
+
)
|
| 173 |
+
coords_2d = viz_umap.fit_transform(embeddings)
|
| 174 |
+
if hasattr(coords_2d, "to_numpy"):
|
| 175 |
+
coords_2d = coords_2d.to_numpy()
|
| 176 |
+
coords_2d = np.array(coords_2d, dtype=np.float32)
|
| 177 |
+
print(f"2D projection complete in {(time.time() - t_viz) / 60:.1f} minutes")
|
| 178 |
+
except Exception as e:
|
| 179 |
+
print(f"2D projection failed: {e}")
|
| 180 |
+
coords_2d = np.zeros((len(embeddings), 2), dtype=np.float32)
|
| 181 |
+
|
| 182 |
+
# ── Save results ──────────────────────────────────────────────────────────
|
| 183 |
+
print("\nSaving results...")
|
| 184 |
+
|
| 185 |
+
# 1. Per-document topic assignments
|
| 186 |
+
results_path = f"{OUTPUT_DIR}/bertopic_results.jsonl"
|
| 187 |
+
with open(results_path, "w") as f:
|
| 188 |
+
for i, doc_id in enumerate(doc_ids):
|
| 189 |
+
meta = metadata.get(int(doc_id), {})
|
| 190 |
+
record = {
|
| 191 |
+
"document_id": int(doc_id),
|
| 192 |
+
"source_section": meta.get("section", ""),
|
| 193 |
+
"topic_id": int(topics[i]),
|
| 194 |
+
"umap_x": float(coords_2d[i][0]),
|
| 195 |
+
"umap_y": float(coords_2d[i][1]),
|
| 196 |
+
}
|
| 197 |
+
f.write(json.dumps(record) + "\n")
|
| 198 |
+
print(f" {results_path} ({len(doc_ids)} records)")
|
| 199 |
+
|
| 200 |
+
# 2. Topic descriptions
|
| 201 |
+
topic_info_path = f"{OUTPUT_DIR}/topic_info.json"
|
| 202 |
+
topic_details = {}
|
| 203 |
+
for topic_id in topic_info["Topic"].unique():
|
| 204 |
+
if topic_id == -1:
|
| 205 |
+
topic_details[-1] = {"label": "Outlier", "words": [], "count": int((np.array(topics) == -1).sum())}
|
| 206 |
+
continue
|
| 207 |
+
words = topic_model.get_topic(topic_id)
|
| 208 |
+
topic_details[int(topic_id)] = {
|
| 209 |
+
"label": "_".join([w for w, _ in words[:3]]),
|
| 210 |
+
"words": [{"word": w, "score": float(s)} for w, s in words[:10]],
|
| 211 |
+
"count": int((np.array(topics) == topic_id).sum()),
|
| 212 |
+
}
|
| 213 |
+
with open(topic_info_path, "w") as f:
|
| 214 |
+
json.dump(topic_details, f, indent=2)
|
| 215 |
+
print(f" {topic_info_path} ({len(topic_details)} topics)")
|
| 216 |
+
|
| 217 |
+
# 3. UMAP coordinates
|
| 218 |
+
coords_path = f"{OUTPUT_DIR}/umap_coords.npz"
|
| 219 |
+
np.savez_compressed(coords_path, coords=coords_2d, doc_ids=doc_ids, topics=np.array(topics))
|
| 220 |
+
print(f" {coords_path}")
|
| 221 |
+
|
| 222 |
+
# 4. Save the BERTopic model
|
| 223 |
+
model_path = f"{OUTPUT_DIR}/bertopic_model"
|
| 224 |
+
topic_model.save(model_path, serialization="safetensors", save_ctfidf=True)
|
| 225 |
+
print(f" {model_path}/")
|
| 226 |
+
|
| 227 |
+
# ── Summary ───────────────────────────────────────────────────────────────
|
| 228 |
+
total_time = (time.time() - t_start) / 60
|
| 229 |
+
print(f"\n{'='*60}")
|
| 230 |
+
print(f"BERTopic clustering complete!")
|
| 231 |
+
print(f" Documents: {len(doc_ids):,}")
|
| 232 |
+
print(f" Topics found: {len(topic_details) - 1}") # exclude outlier
|
| 233 |
+
print(f" Outliers: {(np.array(topics) == -1).sum():,}")
|
| 234 |
+
print(f" Total time: {total_time:.1f} minutes")
|
| 235 |
+
print(f" GPU used: {USE_GPU}")
|
| 236 |
+
print(f"\nFiles to transfer back to Hetzner:")
|
| 237 |
+
print(f" scp {results_path} {topic_info_path} {coords_path} hetzner:/var/www/research/runpod/")
|
| 238 |
+
print(f"{'='*60}")
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
if __name__ == "__main__":
|
| 242 |
+
main()
|