| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| """ |
| Compare text classification approaches on the FineWeb2 Portuguese dataset. |
| |
| Usage (from repo root): |
| uv run scripts/classify_compare.py |
| |
| Compares: |
| 1. TF-IDF + Logistic Regression (baseline, pure CPU) |
| 2. FastText supervised (default + tuned params) |
| 3. Sentence Transformers (small multilingual) + LogReg |
| 4. Sentence Transformers (larger multilingual) + LogReg |
| 5. Gemma embeddings (local server) + LogReg |
| |
| Prints a final summary table with accuracy, f1, throughput, and projected |
| time to classify 16M rows. |
| """ |
|
|
| import json |
| import tempfile |
| import time |
| import urllib.request |
| from dataclasses import dataclass |
| from pathlib import Path |
|
|
| import fasttext |
| import numpy |
| import polars |
| from sklearn.feature_extraction.text import TfidfVectorizer |
| from sklearn.linear_model import LogisticRegression |
| from sklearn.metrics import classification_report, f1_score, accuracy_score |
| from sklearn.model_selection import train_test_split |
|
|
| DATASET_PATH = Path("reference/fineweb2_classification_sample.parquet") |
| EMBEDDING_URL = "http://localhost:8000/v1/embeddings" |
| MAX_CHARS = 800 |
| EMBEDDING_BATCH_SIZE = 100 |
| TEST_SIZE = 0.20 |
| RANDOM_STATE = 42 |
| TARGET_ROWS = 16_000_000 |
|
|
|
|
| @dataclass |
| class Result: |
| name: str |
| accuracy: float |
| macro_f1: float |
| train_time: float |
| predict_time: float |
| throughput: float |
|
|
|
|
| RESULTS: list[Result] = [] |
|
|
|
|
| def load_dataset() -> polars.DataFrame: |
| df = polars.read_parquet(DATASET_PATH) |
| df = df.select(["text", "category"]).drop_nulls() |
| print(f"Loaded {len(df)} samples") |
| print(df["category"].value_counts().sort("count", descending=True)) |
| return df |
|
|
|
|
| def split_data( |
| df: polars.DataFrame, |
| ) -> tuple[list[str], list[str], list[str], list[str]]: |
| texts = df["text"].to_list() |
| labels = df["category"].to_list() |
| return train_test_split( |
| texts, labels, test_size=TEST_SIZE, random_state=RANDOM_STATE, stratify=labels |
| ) |
|
|
|
|
| def truncate(texts: list[str]) -> list[str]: |
| return [t[:MAX_CHARS].strip() for t in texts] |
|
|
|
|
| def record( |
| name: str, |
| test_labels: list[str], |
| predictions: list, |
| train_time: float, |
| predict_time: float, |
| n_test: int, |
| ): |
| acc = accuracy_score(y_true=test_labels, y_pred=predictions) |
| f1 = f1_score( |
| y_true=test_labels, y_pred=predictions, average="macro", zero_division=0 |
| ) |
| throughput = n_test / predict_time if predict_time > 0 else 0 |
| RESULTS.append( |
| Result( |
| name=name, |
| accuracy=acc, |
| macro_f1=f1, |
| train_time=train_time, |
| predict_time=predict_time, |
| throughput=throughput, |
| ) |
| ) |
| print( |
| f"\n{classification_report(y_true=test_labels, y_pred=predictions, zero_division=0)}" |
| ) |
|
|
|
|
| |
|
|
|
|
| def run_tfidf_logreg( |
| train_texts: list[str], |
| test_texts: list[str], |
| train_labels: list[str], |
| test_labels: list[str], |
| ): |
| print("\n" + "=" * 60) |
| print("TF-IDF + Logistic Regression") |
| print("=" * 60) |
|
|
| train_trunc = truncate(train_texts) |
| test_trunc = truncate(test_texts) |
|
|
| t0 = time.perf_counter() |
| vectorizer = TfidfVectorizer( |
| max_features=50_000, sublinear_tf=True, ngram_range=(1, 2) |
| ) |
| train_features = vectorizer.fit_transform(train_trunc) |
| classifier = LogisticRegression( |
| max_iter=2000, C=1.0, class_weight="balanced", random_state=RANDOM_STATE |
| ) |
| classifier.fit(X=train_features, y=train_labels) |
| train_time = time.perf_counter() - t0 |
|
|
| t0 = time.perf_counter() |
| test_features = vectorizer.transform(test_trunc) |
| predictions = classifier.predict(X=test_features) |
| predict_time = time.perf_counter() - t0 |
|
|
| print( |
| f"\nTiming: Train: {train_time:.2f}s | Predict: {predict_time:.4f}s | Throughput: {len(test_texts) / predict_time:.0f} samples/s" |
| ) |
| record( |
| name="TF-IDF + LogReg", |
| test_labels=test_labels, |
| predictions=predictions, |
| train_time=train_time, |
| predict_time=predict_time, |
| n_test=len(test_texts), |
| ) |
|
|
|
|
| |
|
|
|
|
| def write_fasttext_file(texts: list[str], labels: list[str], path: str): |
| with open(path, "w") as f: |
| for text, label in zip(texts, labels): |
| clean_text = text[:MAX_CHARS].replace("\n", " ").replace("\r", " ").strip() |
| f.write(f"__label__{label} {clean_text}\n") |
|
|
|
|
| def run_fasttext_variants( |
| train_texts: list[str], |
| test_texts: list[str], |
| train_labels: list[str], |
| test_labels: list[str], |
| ): |
| print("\n" + "=" * 60) |
| print("FastText Supervised") |
| print("=" * 60) |
|
|
| with tempfile.TemporaryDirectory() as tmpdir: |
| train_path = f"{tmpdir}/train.txt" |
| write_fasttext_file(texts=train_texts, labels=train_labels, path=train_path) |
|
|
| configs = [ |
| ( |
| "FastText (default)", |
| dict(epoch=25, lr=0.5, wordNgrams=2, dim=100, loss="softmax"), |
| ), |
| ( |
| "FastText (tuned)", |
| dict(epoch=50, lr=0.3, wordNgrams=3, dim=200, loss="softmax"), |
| ), |
| ] |
|
|
| for name, params in configs: |
| print(f"\n--- {name} ---") |
| t0 = time.perf_counter() |
| model = fasttext.train_supervised(input=train_path, verbose=0, **params) |
| train_time = time.perf_counter() - t0 |
|
|
| t0 = time.perf_counter() |
| predictions = [] |
| for text in test_texts: |
| clean = text[:MAX_CHARS].replace("\n", " ").replace("\r", " ").strip() |
| pred = model.predict(clean) |
| predictions.append(pred[0][0].replace("__label__", "")) |
| predict_time = time.perf_counter() - t0 |
|
|
| print( |
| f"Timing: Train: {train_time:.2f}s | Predict: {predict_time:.4f}s | Throughput: {len(test_texts) / predict_time:.0f} samples/s" |
| ) |
| record( |
| name=name, |
| test_labels=test_labels, |
| predictions=predictions, |
| train_time=train_time, |
| predict_time=predict_time, |
| n_test=len(test_texts), |
| ) |
|
|
|
|
| |
|
|
|
|
| def get_device() -> str: |
| import torch |
|
|
| if torch.backends.mps.is_available(): |
| return "mps" |
| if torch.cuda.is_available(): |
| return "cuda" |
| return "cpu" |
|
|
|
|
| def run_sentence_transformer( |
| train_texts: list[str], |
| test_texts: list[str], |
| train_labels: list[str], |
| test_labels: list[str], |
| model_name: str, |
| label: str, |
| ): |
| from sentence_transformers import SentenceTransformer |
|
|
| device = get_device() |
|
|
| print(f"\n{'=' * 60}") |
| print(f"{label} (device={device})") |
| print(f"{'=' * 60}") |
|
|
| train_trunc = truncate(train_texts) |
| test_trunc = truncate(test_texts) |
|
|
| model = SentenceTransformer(model_name, device=device) |
|
|
| t0 = time.perf_counter() |
| train_embeddings = model.encode(train_trunc, batch_size=256, show_progress_bar=True) |
| embed_train_time = time.perf_counter() - t0 |
|
|
| classifier = LogisticRegression( |
| max_iter=2000, C=1.0, class_weight="balanced", random_state=RANDOM_STATE |
| ) |
| t0 = time.perf_counter() |
| classifier.fit(X=train_embeddings, y=train_labels) |
| fit_time = time.perf_counter() - t0 |
|
|
| t0 = time.perf_counter() |
| test_embeddings = model.encode(test_trunc, batch_size=256, show_progress_bar=True) |
| embed_test_time = time.perf_counter() - t0 |
|
|
| t0 = time.perf_counter() |
| predictions = classifier.predict(X=test_embeddings) |
| classify_time = time.perf_counter() - t0 |
|
|
| total_train = embed_train_time + fit_time |
| total_predict = embed_test_time + classify_time |
|
|
| print(f"\nTiming:") |
| print( |
| f" Train embed: {embed_train_time:.2f}s | Fit: {fit_time:.2f}s | Total train: {total_train:.2f}s" |
| ) |
| print( |
| f" Test embed: {embed_test_time:.2f}s | Predict: {classify_time:.4f}s | Total test: {total_predict:.2f}s" |
| ) |
| print(f" Throughput (test): {len(test_texts) / total_predict:.0f} samples/s") |
| record( |
| name=label, |
| test_labels=test_labels, |
| predictions=predictions, |
| train_time=total_train, |
| predict_time=total_predict, |
| n_test=len(test_texts), |
| ) |
|
|
|
|
| |
|
|
|
|
| def fetch_embeddings(texts: list[str]) -> numpy.ndarray: |
| truncated = truncate(texts) |
| all_embeddings = [] |
| for i in range(0, len(truncated), EMBEDDING_BATCH_SIZE): |
| chunk = truncated[i : i + EMBEDDING_BATCH_SIZE] |
| request = urllib.request.Request( |
| url=EMBEDDING_URL, |
| data=json.dumps( |
| {"input": chunk, "model": "embed", "encoding_format": "float"} |
| ).encode("utf-8"), |
| headers={"Content-Type": "application/json"}, |
| method="POST", |
| ) |
| with urllib.request.urlopen(request) as response: |
| result = json.load(response) |
| sorted_data = sorted(result["data"], key=lambda x: x["index"]) |
| all_embeddings.extend([d["embedding"] for d in sorted_data]) |
| return numpy.array(all_embeddings) |
|
|
|
|
| def embedding_is_available() -> bool: |
| try: |
| request = urllib.request.Request( |
| url=EMBEDDING_URL, |
| data=json.dumps( |
| {"input": ["test"], "model": "embed", "encoding_format": "float"} |
| ).encode("utf-8"), |
| headers={"Content-Type": "application/json"}, |
| method="POST", |
| ) |
| with urllib.request.urlopen(request, timeout=5) as response: |
| json.load(response) |
| return True |
| except Exception: |
| return False |
|
|
|
|
| def run_gemma_logreg( |
| train_texts: list[str], |
| test_texts: list[str], |
| train_labels: list[str], |
| test_labels: list[str], |
| ): |
| print("\n" + "=" * 60) |
| print("Gemma Embedding (local) + LogReg") |
| print("=" * 60) |
|
|
| if not embedding_is_available(): |
| print(f"SKIPPED: embedding server not reachable at {EMBEDDING_URL}") |
| return |
|
|
| t0 = time.perf_counter() |
| train_embeddings = fetch_embeddings(texts=train_texts) |
| embed_train_time = time.perf_counter() - t0 |
|
|
| classifier = LogisticRegression( |
| max_iter=2000, C=1.0, class_weight="balanced", random_state=RANDOM_STATE |
| ) |
| t0 = time.perf_counter() |
| classifier.fit(X=train_embeddings, y=train_labels) |
| fit_time = time.perf_counter() - t0 |
|
|
| t0 = time.perf_counter() |
| test_embeddings = fetch_embeddings(texts=test_texts) |
| embed_test_time = time.perf_counter() - t0 |
|
|
| t0 = time.perf_counter() |
| predictions = classifier.predict(X=test_embeddings) |
| predict_time = time.perf_counter() - t0 |
|
|
| total_train = embed_train_time + fit_time |
| total_predict = embed_test_time + predict_time |
|
|
| print(f"\nTiming:") |
| print( |
| f" Train embed: {embed_train_time:.2f}s | Fit: {fit_time:.2f}s | Total train: {total_train:.2f}s" |
| ) |
| print( |
| f" Test embed: {embed_test_time:.2f}s | Predict: {predict_time:.4f}s | Total test: {total_predict:.2f}s" |
| ) |
| print(f" Throughput (test): {len(test_texts) / total_predict:.0f} samples/s") |
| record( |
| name="Gemma Embed + LogReg", |
| test_labels=test_labels, |
| predictions=predictions, |
| train_time=total_train, |
| predict_time=total_predict, |
| n_test=len(test_texts), |
| ) |
|
|
|
|
| |
|
|
|
|
| def print_summary(): |
| print("\n\n") |
| print("=" * 90) |
| print(f"{'SUMMARY':^90}") |
| print("=" * 90) |
| header = f"{'Method':<35} {'Acc':>6} {'F1':>6} {'Train':>8} {'samp/s':>10} {'16M ETA':>12}" |
| print(header) |
| print("-" * 90) |
|
|
| for r in sorted(RESULTS, key=lambda x: x.macro_f1, reverse=True): |
| eta_hours = ( |
| TARGET_ROWS / r.throughput / 3600 if r.throughput > 0 else float("inf") |
| ) |
| if eta_hours < 1: |
| eta_str = f"{eta_hours * 60:.0f} min" |
| else: |
| eta_str = f"{eta_hours:.1f} hrs" |
| print( |
| f"{r.name:<35} {r.accuracy:>6.1%} {r.macro_f1:>6.1%} {r.train_time:>7.1f}s {r.throughput:>10,.0f} {eta_str:>12}" |
| ) |
|
|
| print("-" * 90) |
| print( |
| f"Target: {TARGET_ROWS:,} rows. ETA = projected inference-only time at test throughput." |
| ) |
| print() |
|
|
|
|
| def main(): |
| df = load_dataset() |
| train_texts, test_texts, train_labels, test_labels = split_data(df=df) |
| print(f"Train: {len(train_texts)} | Test: {len(test_texts)}") |
|
|
| args = dict( |
| train_texts=train_texts, |
| test_texts=test_texts, |
| train_labels=train_labels, |
| test_labels=test_labels, |
| ) |
|
|
| |
| run_tfidf_logreg(**args) |
| run_fasttext_variants(**args) |
|
|
| |
| run_sentence_transformer( |
| **args, |
| model_name="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2", |
| label="MiniLM-L12 multilingual + LogReg", |
| ) |
| run_sentence_transformer( |
| **args, |
| model_name="sentence-transformers/all-MiniLM-L6-v2", |
| label="MiniLM-L6 (EN-only) + LogReg", |
| ) |
| run_sentence_transformer( |
| **args, |
| model_name="intfloat/multilingual-e5-small", |
| label="E5-small multilingual + LogReg", |
| ) |
|
|
| |
| run_gemma_logreg(**args) |
|
|
| print_summary() |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|