"""Train both classifiers, enrich every dataset shard, and upload the result.""" import json import multiprocessing import subprocess import time from pathlib import Path import fire import numpy as numpy import polars as polars import torch from sentence_transformers import SentenceTransformer from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_report, confusion_matrix from sklearn.model_selection import StratifiedShuffleSplit from sklearn.preprocessing import StandardScaler HERE = Path(__file__).resolve().parent MODEL = "intfloat/multilingual-e5-small" REPO = "duarteocarmo/bagaco3" TARGETS = ("educational_score", "category") MAX_CHARS = 1_500 CHUNK_SIZE = 20_000 def classifier() -> LogisticRegression: return LogisticRegression( class_weight="balanced", max_iter=5_000, random_state=42, ) def features_for( *, texts: list[str], model: SentenceTransformer, scaler: StandardScaler, batch_size: int, ) -> numpy.ndarray: embeddings = model.encode( inputs=[text[:MAX_CHARS] for text in texts], batch_size=batch_size, normalize_embeddings=True, show_progress_bar=False, ) lengths = numpy.log1p(numpy.array([len(text) for text in texts])).reshape(-1, 1) return numpy.column_stack(tup=(embeddings, scaler.transform(X=lengths) * 0.1)) def evaluation_for( *, labels: list, features: numpy.ndarray, ) -> dict: splitter = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42) train_indices, test_indices = next(splitter.split(X=features, y=labels)) evaluator = classifier().fit( X=features[train_indices], y=[labels[index] for index in train_indices], ) actual = [labels[index] for index in test_indices] predicted = evaluator.predict(X=features[test_indices]) report_labels = sorted(set(labels)) return { "labels": report_labels, "classification_report": classification_report( y_true=actual, y_pred=predicted, labels=report_labels, output_dict=True, zero_division=0, ), "confusion_matrix": confusion_matrix( y_true=actual, y_pred=predicted, labels=report_labels, ).tolist(), } def load_model(*, device: str) -> SentenceTransformer: model_kwargs = {"torch_dtype": torch.float16} if device.startswith("cuda") else {} precision = "float16" if model_kwargs else "float32" print(f"Loading {MODEL} on {device} with {precision}", flush=True) return SentenceTransformer( model_name_or_path=MODEL, device=device, model_kwargs=model_kwargs, ) def train_classifiers( *, output_dir: Path, device: str, batch_size: int, ) -> tuple[SentenceTransformer, StandardScaler, dict[str, LogisticRegression]]: annotations = polars.read_parquet( source=HERE / "data/annotated.parquet", columns=["text", *TARGETS], ).drop_nulls() texts = annotations.get_column("text").to_list() lengths = numpy.log1p(numpy.array([len(text) for text in texts])).reshape(-1, 1) scaler = StandardScaler().fit(X=lengths) model = load_model(device=device) print( f"Encoding {annotations.height:,} annotated rows and training classifiers", flush=True, ) features = features_for( texts=texts, model=model, scaler=scaler, batch_size=batch_size, ) labels = {target: annotations.get_column(target).to_list() for target in TARGETS} metrics = { target: evaluation_for(labels=labels[target], features=features) for target in TARGETS } classifiers = { target: classifier().fit(X=features, y=labels[target]) for target in TARGETS } (output_dir / "classification_metrics.json").write_text( json.dumps(obj=metrics, indent=2) + "\n", encoding="utf-8", ) print( f"Trained and evaluated both classifiers on {annotations.height:,} rows", flush=True, ) return model, scaler, classifiers def classify_shard( *, source_file: Path, output_file: Path, model: SentenceTransformer, scaler: StandardScaler, classifiers: dict[str, LogisticRegression], batch_size: int, ) -> polars.DataFrame: if output_file.exists(): return polars.read_parquet( source=output_file, columns=[*TARGETS, "char_len"], ) with source_file.open(mode="rb") as file: if file.read(4) != b"PAR1": raise RuntimeError(f"{source_file} is a Git LFS pointer; run git lfs pull") data = polars.read_parquet(source=source_file, low_memory=True) predictions = {target: [] for target in TARGETS} for chunk in data.iter_slices(n_rows=CHUNK_SIZE): features = features_for( texts=chunk.get_column("text").to_list(), model=model, scaler=scaler, batch_size=batch_size, ) for target in TARGETS: predictions[target].extend( classifiers[target].predict(X=features).tolist() ) columns = { target: polars.Series(values=values) for target, values in predictions.items() } columns["char_len"] = polars.col("text").str.len_chars() classified = data.with_columns(**columns) temporary_file = output_file.with_suffix(".parquet.tmp") classified.write_parquet(file=temporary_file, compression="zstd") temporary_file.replace(output_file) return classified.select([*TARGETS, "char_len"]) def summary_for(*, data: polars.DataFrame, target: str) -> polars.DataFrame: return data.group_by(target).agg( polars.len().cast(polars.UInt64).alias("rows"), polars.col("char_len").cast(polars.UInt64).sum().alias("total_chars"), ) def format_duration(*, seconds: float) -> str: minutes, seconds = divmod(int(seconds), 60) hours, minutes = divmod(minutes, 60) return f"{hours:d}h {minutes:02d}m {seconds:02d}s" def classify_dataset( *, source_files: list[Path], output_dir: Path, model: SentenceTransformer, scaler: StandardScaler, classifiers: dict[str, LogisticRegression], batch_size: int, ) -> dict[str, list[polars.DataFrame]]: summaries = {target: [] for target in TARGETS} classification_seconds = 0.0 classified_count = 0 total_to_classify = sum( not (output_dir / source_file.name).exists() for source_file in source_files ) print( f"Classifying {len(source_files):,} shards on {model.device}", flush=True, ) for index, source_file in enumerate(source_files, start=1): started_at = time.monotonic() output_file = output_dir / source_file.name existed = output_file.exists() classified = classify_shard( source_file=source_file, output_file=output_file, model=model, scaler=scaler, classifiers=classifiers, batch_size=batch_size, ) for target in TARGETS: summaries[target].append(summary_for(data=classified, target=target)) action = "Kept" if existed else "Classified" if not existed: classification_seconds += time.monotonic() - started_at classified_count += 1 remaining = total_to_classify - classified_count eta = classification_seconds / classified_count * remaining if classified_count else 0 print( f"{action} shard {index:,}/{len(source_files):,} " f"({source_file.name}): {classified.height:,} rows; " f"ETA {format_duration(seconds=eta)}", flush=True, ) return summaries def classify_worker( *, worker_index: int, source_files: list[Path], output_dir: Path, scaler: StandardScaler, classifiers: dict[str, LogisticRegression], batch_size: int, ) -> None: device = f"cuda:{worker_index}" model = load_model(device=device) classify_dataset( source_files=source_files, output_dir=output_dir, model=model, scaler=scaler, classifiers=classifiers, batch_size=batch_size, ) def classify_in_parallel( *, source_files: list[Path], output_dir: Path, scaler: StandardScaler, classifiers: dict[str, LogisticRegression], batch_size: int, workers: int, ) -> None: context = multiprocessing.get_context(method="spawn") processes = [ context.Process( target=classify_worker, kwargs={ "worker_index": worker_index, "source_files": source_files[worker_index::workers], "output_dir": output_dir, "scaler": scaler, "classifiers": classifiers, "batch_size": batch_size, }, ) for worker_index in range(workers) ] started_at = time.monotonic() for process in processes: process.start() for process in processes: process.join() failed = [process.exitcode for process in processes if process.exitcode != 0] if failed: raise RuntimeError(f"Classifier workers failed with exit codes {failed}") elapsed = time.monotonic() - started_at print( f"Completed {len(source_files):,} shards with {workers} workers in " f"{format_duration(seconds=elapsed)}", flush=True, ) def summaries_for_outputs( *, source_files: list[Path], output_dir: Path, ) -> dict[str, list[polars.DataFrame]]: summaries = {target: [] for target in TARGETS} for source_file in source_files: classified = polars.read_parquet( source=output_dir / source_file.name, columns=[*TARGETS, "char_len"], ) for target in TARGETS: summaries[target].append(summary_for(data=classified, target=target)) return summaries def save_class_counts( *, summaries: dict[str, list[polars.DataFrame]], output_dir: Path, ) -> None: counts = { target: ( polars.concat(items=summaries[target]) .group_by(target) .agg(polars.col("rows").sum(), polars.col("total_chars").sum()) .sort(target) .to_dicts() ) for target in TARGETS } (output_dir / "class_counts.json").write_text( json.dumps(obj=counts, indent=2) + "\n", encoding="utf-8", ) print(f"Saved metrics and class counts to {output_dir}", flush=True) def upload_outputs(*, output_dir: Path, repo: str) -> None: subprocess.run( args=[ "uvx", "--from", "huggingface-hub", "hf", "upload-large-folder", repo, str(output_dir), "--repo-type=dataset", "--include=*.parquet", "--include=*.json", ], check=True, ) print( f"Uploaded dataset to https://huggingface.co/datasets/{repo}", flush=True, ) def main( input_dir: str = str(HERE.parent), output_dir: str = str(HERE.parent / "classified"), repo: str = REPO, device: str = "cuda", batch_size: int = 256, workers: int = 1, dry_run: bool = False, upload: bool = True, ) -> None: """Classify the cloned dataset and optionally upload the enriched shards.""" if device.startswith("cuda") and not torch.cuda.is_available(): raise RuntimeError("CUDA is unavailable") if workers < 1: raise RuntimeError("workers must be at least 1") if workers > 1 and device != "cuda": raise RuntimeError("Multiple workers require device=cuda") if workers > torch.cuda.device_count() and device == "cuda": raise RuntimeError(f"Requested {workers} workers but found {torch.cuda.device_count()} GPUs") source_files = sorted(Path(input_dir).glob("*.parquet")) if not source_files: raise RuntimeError(f"No Parquet files found in {input_dir}") output_path = Path(output_dir) if dry_run: source_files = source_files[:workers] output_path = output_path.with_name(f"{output_path.name}-dry-run") if output_path.exists(): raise RuntimeError(f"Dry-run output already exists: {output_path}") upload = False print( f"Dry run: processing {len(source_files)} shards with {workers} workers", flush=True, ) output_path.mkdir(parents=True, exist_ok=True) model, scaler, classifiers = train_classifiers( output_dir=output_path, device=device, batch_size=batch_size, ) if workers == 1: summaries = classify_dataset( source_files=source_files, output_dir=output_path, model=model, scaler=scaler, classifiers=classifiers, batch_size=batch_size, ) else: del model torch.cuda.empty_cache() classify_in_parallel( source_files=source_files, output_dir=output_path, scaler=scaler, classifiers=classifiers, batch_size=batch_size, workers=workers, ) summaries = summaries_for_outputs( source_files=source_files, output_dir=output_path, ) save_class_counts(summaries=summaries, output_dir=output_path) if upload: upload_outputs(output_dir=output_path, repo=repo) if __name__ == "__main__": fire.Fire(component=main)