| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| """ |
| Classify arXiv CS papers to identify which ones introduce new datasets. |
| |
| This script processes papers from the arxiv-metadata-snapshot dataset, |
| classifies them using a fine-tuned ModernBERT model, and outputs results |
| to Lance format for efficient vector search on the HF Hub. |
| |
| Output supports direct remote queries via the hf:// protocol, enabling |
| semantic search without downloading the full dataset. |
| |
| Example usage: |
| # Incremental update (only new papers since last run) |
| uv run classify_arxiv_to_lance.py |
| |
| # Full refresh (reprocess everything) |
| uv run classify_arxiv_to_lance.py --full-refresh |
| |
| # Test with small sample |
| uv run classify_arxiv_to_lance.py --limit 100 |
| |
| # Run on HF Jobs (A100) |
| hf jobs uv run \\ |
| --flavor a100-large \\ |
| --image vllm/vllm-openai \\ |
| --secrets HF_TOKEN \\ |
| classify_arxiv_to_lance.py |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import logging |
| import os |
| import shutil |
| import tempfile |
| from datetime import datetime |
| from pathlib import Path |
| from typing import TYPE_CHECKING |
|
|
| import polars as pl |
| import torch |
| from huggingface_hub import HfApi, login |
| from toolz import partition_all |
| from tqdm.auto import tqdm |
|
|
| |
| if TYPE_CHECKING: |
| from typing import Optional |
|
|
| |
| try: |
| import vllm |
| from vllm import LLM |
|
|
| VLLM_AVAILABLE = True |
| except ImportError: |
| VLLM_AVAILABLE = False |
|
|
| |
| try: |
| import lance |
|
|
| LANCE_AVAILABLE = True |
| except ImportError: |
| LANCE_AVAILABLE = False |
|
|
| |
| logging.basicConfig( |
| level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" |
| ) |
| logger = logging.getLogger(__name__) |
|
|
| |
| |
| |
|
|
| DEFAULT_INPUT_DATASET = "librarian-bots/arxiv-metadata-snapshot" |
| DEFAULT_OUTPUT_DATASET = "davanstrien/arxiv-cs-papers-lance" |
| DEFAULT_MODEL = "davanstrien/ModernBERT-base-is-new-arxiv-dataset" |
|
|
| |
| BATCH_SIZES = { |
| "vllm": 500_000, |
| "cuda": 256, |
| "mps": 1_000, |
| "cpu": 100, |
| } |
|
|
| |
| LANCE_DATA_PATH = "data/train.lance" |
|
|
|
|
| |
| |
| |
|
|
|
|
| def check_backend() -> tuple[str, int]: |
| """ |
| Check available backend and return (backend_name, recommended_batch_size). |
| |
| Priority: vLLM (CUDA) > CUDA (transformers) > MPS > CPU |
| |
| Returns: |
| Tuple of (backend_name, batch_size) where backend is |
| 'vllm', 'cuda', 'mps', or 'cpu' |
| """ |
| if torch.cuda.is_available() and VLLM_AVAILABLE: |
| gpu_name = torch.cuda.get_device_name(0) |
| gpu_memory = torch.cuda.get_device_properties(0).total_memory / 1024**3 |
| logger.info(f"GPU detected: {gpu_name} with {gpu_memory:.1f} GB memory") |
| logger.info(f"vLLM version: {vllm.__version__}") |
| return "vllm", BATCH_SIZES["vllm"] |
| elif torch.cuda.is_available(): |
| gpu_name = torch.cuda.get_device_name(0) |
| gpu_memory = torch.cuda.get_device_properties(0).total_memory / 1024**3 |
| logger.info(f"GPU detected: {gpu_name} with {gpu_memory:.1f} GB memory") |
| logger.info("vLLM not available, using transformers with CUDA") |
| return "cuda", BATCH_SIZES["cuda"] |
| elif torch.backends.mps.is_available(): |
| logger.info("Using Apple Silicon MPS device with transformers") |
| return "mps", BATCH_SIZES["mps"] |
| else: |
| logger.info("Using CPU device with transformers") |
| return "cpu", BATCH_SIZES["cpu"] |
|
|
|
|
| |
| |
| |
|
|
|
|
| def get_last_update_date( |
| output_dataset: str, hf_token: Optional[str] = None |
| ) -> Optional[str]: |
| """ |
| Get the maximum update_date from the existing Lance dataset on HF Hub. |
| |
| For now, returns None to trigger full refresh mode. |
| TODO: Implement incremental mode by querying existing Lance dataset. |
| |
| Args: |
| output_dataset: HuggingFace dataset ID (e.g., "davanstrien/arxiv-cs-papers-lance") |
| hf_token: Optional HuggingFace token for private datasets |
| |
| Returns: |
| ISO format date string of the last update, or None if dataset doesn't exist |
| """ |
| |
| |
| logger.info("Incremental mode not yet implemented - will do full refresh") |
| return None |
|
|
|
|
| |
| |
| |
|
|
|
|
| def prepare_incremental_data( |
| input_dataset: str, |
| temp_dir: Path, |
| last_update_date: Optional[str] = None, |
| limit: Optional[int] = None, |
| full_refresh: bool = False, |
| ) -> Optional[pl.DataFrame]: |
| """ |
| Prepare data for incremental classification. |
| |
| Downloads source dataset, filters to CS papers, applies incremental |
| filtering based on last_update_date, and formats text for classification. |
| |
| Args: |
| input_dataset: Source dataset ID on HF Hub |
| temp_dir: Directory for temporary files |
| last_update_date: Date of last classification run (for incremental mode) |
| limit: Optional limit for testing |
| full_refresh: If True, process all papers regardless of date |
| |
| Returns: |
| Polars DataFrame ready for classification, or None if no new papers |
| """ |
| from huggingface_hub import snapshot_download |
|
|
| logger.info(f"Loading source dataset: {input_dataset}") |
|
|
| |
| local_dir = temp_dir / "raw_data" |
| snapshot_download( |
| input_dataset, |
| local_dir=str(local_dir), |
| allow_patterns=["*.parquet"], |
| repo_type="dataset", |
| ) |
| parquet_files = list(local_dir.rglob("*.parquet")) |
| logger.info(f"Found {len(parquet_files)} parquet files") |
|
|
| |
| lf = pl.scan_parquet(parquet_files) |
|
|
| |
| logger.info("Filtering to CS papers...") |
| lf_cs = lf.filter(pl.col("categories").str.contains("cs.")) |
|
|
| |
| if not full_refresh and last_update_date: |
| logger.info(f"Filtering for papers newer than {last_update_date}") |
| lf_cs = lf_cs.filter(pl.col("update_date") > last_update_date) |
| elif full_refresh: |
| logger.info("Full refresh mode - processing all CS papers") |
| else: |
| logger.info("No existing dataset found - processing all CS papers") |
|
|
| |
| if limit: |
| logger.info(f"Limiting to {limit} papers for testing") |
| lf_cs = lf_cs.head(limit) |
|
|
| |
| columns_to_keep = ["id", "title", "abstract", "categories", "update_date", "authors"] |
| available_columns = lf_cs.collect_schema().names() |
| lf_selected = lf_cs.select([col for col in columns_to_keep if col in available_columns]) |
|
|
| |
| logger.info("Formatting text for classification...") |
| lf_formatted = lf_selected.with_columns( |
| pl.concat_str( |
| [ |
| pl.lit("TITLE: "), |
| pl.col("title"), |
| pl.lit(" \n\nABSTRACT: "), |
| pl.col("abstract"), |
| ] |
| ).alias("text_for_classification") |
| ) |
|
|
| |
| logger.info("Collecting data...") |
| df = lf_formatted.collect(engine="streaming") |
|
|
| if df.height == 0: |
| logger.info("No papers to classify") |
| return None |
|
|
| logger.info(f"Prepared {df.height:,} papers for classification") |
| return df |
|
|
|
|
| |
| |
| |
|
|
|
|
| def classify_with_vllm( |
| df: pl.DataFrame, |
| model_id: str, |
| batch_size: int = 500_000, |
| ) -> list[dict]: |
| """ |
| Classify papers using vLLM for efficient GPU inference. |
| |
| Uses vLLM's pooling runner for sequence classification, which provides |
| significant speedup over transformers pipeline on large batches. |
| |
| Args: |
| df: DataFrame with 'text_for_classification' column |
| model_id: HuggingFace model ID for classification |
| batch_size: Number of texts to process per batch |
| |
| Returns: |
| List of dicts with keys: classification_label, is_new_dataset, confidence_score |
| """ |
| logger.info(f"Initializing vLLM with model: {model_id}") |
| llm = LLM(model=model_id, runner="pooling") |
|
|
| texts = df["text_for_classification"].to_list() |
| total_papers = len(texts) |
|
|
| logger.info(f"Starting vLLM classification of {total_papers:,} papers") |
| all_results = [] |
|
|
| for batch in tqdm( |
| list(partition_all(batch_size, texts)), |
| desc="Processing batches", |
| unit="batch", |
| ): |
| batch_results = llm.classify(list(batch)) |
|
|
| for result in batch_results: |
| logits = torch.tensor(result.outputs.probs) |
| probs = torch.nn.functional.softmax(logits, dim=0) |
| top_idx = torch.argmax(probs).item() |
| top_prob = probs[top_idx].item() |
|
|
| |
| label = "new_dataset" if top_idx == 0 else "no_new_dataset" |
|
|
| all_results.append( |
| { |
| "classification_label": label, |
| "is_new_dataset": label == "new_dataset", |
| "confidence_score": float(top_prob), |
| } |
| ) |
|
|
| logger.info(f"Classified {len(all_results):,} papers with vLLM") |
| return all_results |
|
|
|
|
| def classify_with_transformers( |
| df: pl.DataFrame, |
| model_id: str, |
| batch_size: int = 1_000, |
| device: str = "cpu", |
| ) -> list[dict]: |
| """ |
| Classify papers using transformers pipeline. |
| |
| Fallback for environments without vLLM or for smaller datasets. |
| |
| Args: |
| df: DataFrame with 'text_for_classification' column |
| model_id: HuggingFace model ID for classification |
| batch_size: Number of texts to process per batch |
| device: Device to use ('cuda', 'mps', or 'cpu') |
| |
| Returns: |
| List of dicts with keys: classification_label, is_new_dataset, confidence_score |
| """ |
| from transformers import pipeline |
|
|
| logger.info(f"Initializing transformers pipeline with model: {model_id}") |
|
|
| if device == "cuda": |
| device_map = 0 |
| elif device == "mps": |
| device_map = "mps" |
| else: |
| device_map = None |
|
|
| pipe = pipeline( |
| "text-classification", |
| model=model_id, |
| device=device_map, |
| batch_size=batch_size, |
| ) |
|
|
| texts = df["text_for_classification"].to_list() |
| total_papers = len(texts) |
|
|
| logger.info(f"Starting transformers classification of {total_papers:,} papers") |
| all_results = [] |
|
|
| with tqdm(total=total_papers, desc="Classifying papers", unit="papers") as pbar: |
| for batch in partition_all(batch_size, texts): |
| batch_list = list(batch) |
| predictions = pipe(batch_list) |
|
|
| for pred in predictions: |
| label = pred["label"] |
| all_results.append( |
| { |
| "classification_label": label, |
| "is_new_dataset": label == "new_dataset", |
| "confidence_score": float(pred["score"]), |
| } |
| ) |
|
|
| pbar.update(len(batch_list)) |
|
|
| logger.info(f"Classified {len(all_results):,} papers with transformers") |
| return all_results |
|
|
|
|
| |
| |
| |
|
|
|
|
| def save_to_lance( |
| df: pl.DataFrame, |
| output_path: Path, |
| mode: str = "overwrite", |
| ) -> None: |
| """ |
| Save classified DataFrame to Lance format. |
| |
| Args: |
| df: Classified DataFrame with all columns |
| output_path: Local path for Lance dataset |
| mode: 'overwrite' for full refresh, 'append' for incremental |
| """ |
| if not LANCE_AVAILABLE: |
| raise ImportError("Lance library not available. Install with: pip install pylance") |
|
|
| logger.info(f"Saving {df.height:,} papers to Lance format at {output_path}") |
|
|
| |
| arrow_table = df.to_arrow() |
|
|
| |
| if mode == "overwrite" or not output_path.exists(): |
| lance.write_dataset(arrow_table, str(output_path), mode="overwrite") |
| logger.info(f"Created new Lance dataset at {output_path}") |
| else: |
| |
| lance.write_dataset(arrow_table, str(output_path), mode="append") |
| logger.info(f"Appended to existing Lance dataset at {output_path}") |
|
|
| |
| ds = lance.dataset(str(output_path)) |
| logger.info(f"Lance dataset now has {ds.count_rows():,} total rows") |
|
|
|
|
| def upload_to_hub( |
| lance_path: Path, |
| output_dataset: str, |
| hf_token: Optional[str] = None, |
| ) -> None: |
| """ |
| Upload Lance dataset to HuggingFace Hub. |
| |
| Args: |
| lance_path: Local path to Lance dataset |
| output_dataset: Target dataset ID on HF Hub |
| hf_token: HuggingFace token for authentication |
| """ |
| api = HfApi() |
|
|
| |
| try: |
| api.create_repo( |
| repo_id=output_dataset, |
| repo_type="dataset", |
| exist_ok=True, |
| token=hf_token, |
| ) |
| logger.info(f"Dataset repo ready: {output_dataset}") |
| except Exception as e: |
| logger.warning(f"Could not create repo (may already exist): {e}") |
|
|
| |
| logger.info(f"Uploading Lance dataset to {output_dataset}...") |
| api.upload_folder( |
| folder_path=str(lance_path), |
| path_in_repo=LANCE_DATA_PATH, |
| repo_id=output_dataset, |
| repo_type="dataset", |
| token=hf_token, |
| commit_message=f"Update Lance dataset - {datetime.now().isoformat()}", |
| ) |
|
|
| logger.info(f"Successfully uploaded to https://huggingface.co/datasets/{output_dataset}") |
|
|
|
|
| |
| |
| |
|
|
|
|
| def main( |
| input_dataset: str = DEFAULT_INPUT_DATASET, |
| output_dataset: str = DEFAULT_OUTPUT_DATASET, |
| model_id: str = DEFAULT_MODEL, |
| batch_size: Optional[int] = None, |
| limit: Optional[int] = None, |
| full_refresh: bool = False, |
| temp_dir: Optional[str] = None, |
| hf_token: Optional[str] = None, |
| ) -> None: |
| """ |
| Main classification pipeline. |
| |
| Flow: |
| 1. Authenticate with HF Hub |
| 2. Detect backend (vLLM/CUDA/MPS/CPU) |
| 3. Check for existing Lance dataset, get last update date |
| 4. Download and filter source data (incremental or full) |
| 5. Classify papers using appropriate backend |
| 6. Save results to Lance format |
| 7. Upload to HF Hub |
| 8. Print statistics |
| |
| Args: |
| input_dataset: Source arxiv metadata dataset |
| output_dataset: Target Lance dataset on HF Hub |
| model_id: Classification model ID |
| batch_size: Override auto-detected batch size |
| limit: Limit papers for testing |
| full_refresh: Process all papers (ignore existing data) |
| temp_dir: Custom temp directory (auto-created if not specified) |
| hf_token: HF token (falls back to HF_TOKEN env var) |
| """ |
| |
| logger.info("=" * 60) |
| logger.info("ArXiv CS Papers Classification Pipeline (Lance Output)") |
| logger.info("=" * 60) |
|
|
| |
| HF_TOKEN = hf_token or os.environ.get("HF_TOKEN") |
| if HF_TOKEN: |
| login(token=HF_TOKEN) |
| logger.info("Authenticated with HuggingFace Hub") |
| else: |
| logger.warning("No HF_TOKEN found. May fail for private datasets or uploads.") |
|
|
| |
| if temp_dir: |
| temp_path = Path(temp_dir) |
| temp_path.mkdir(parents=True, exist_ok=True) |
| else: |
| temp_path = Path(tempfile.mkdtemp(prefix="arxiv_lance_")) |
| logger.info(f"Using temp directory: {temp_path}") |
|
|
| |
| backend, default_batch_size = check_backend() |
| if batch_size is None: |
| batch_size = default_batch_size |
| logger.info(f"Backend: {backend}, Batch size: {batch_size:,}") |
|
|
| |
| last_update_date = None |
| if not full_refresh: |
| last_update_date = get_last_update_date(output_dataset, HF_TOKEN) |
| if last_update_date: |
| logger.info(f"Incremental mode: processing papers after {last_update_date}") |
| else: |
| logger.info("No existing dataset found - processing all papers") |
| else: |
| logger.info("Full refresh mode - processing all papers") |
|
|
| |
| df = prepare_incremental_data( |
| input_dataset, |
| temp_path, |
| last_update_date, |
| limit, |
| full_refresh, |
| ) |
|
|
| if df is None or df.height == 0: |
| logger.info("No new papers to classify. Dataset is up to date!") |
| |
| if not temp_dir and temp_path.exists(): |
| shutil.rmtree(temp_path) |
| return |
|
|
| logger.info(f"Prepared {df.height:,} papers for classification") |
|
|
| |
| if backend == "vllm": |
| results = classify_with_vllm(df, model_id, batch_size) |
| else: |
| results = classify_with_transformers(df, model_id, batch_size, backend) |
|
|
| |
| logger.info("Adding classification results...") |
| df = df.with_columns( |
| [ |
| pl.Series("classification_label", [r["classification_label"] for r in results]), |
| pl.Series("is_new_dataset", [r["is_new_dataset"] for r in results]), |
| pl.Series("confidence_score", [r["confidence_score"] for r in results]), |
| pl.lit(datetime.now().isoformat()).alias("classification_date"), |
| pl.lit(model_id).alias("model_version"), |
| |
| pl.lit(None).cast(pl.List(pl.Float32)).alias("embedding"), |
| pl.lit(None).cast(pl.Utf8).alias("embedding_model"), |
| ] |
| ) |
|
|
| |
| if "text_for_classification" in df.columns: |
| df = df.drop("text_for_classification") |
|
|
| |
| lance_output_path = temp_path / "output.lance" |
| mode = "overwrite" if full_refresh or last_update_date is None else "append" |
| save_to_lance(df, lance_output_path, mode) |
|
|
| |
| if HF_TOKEN: |
| upload_to_hub(lance_output_path, output_dataset, HF_TOKEN) |
| else: |
| logger.warning(f"No HF_TOKEN - results saved locally at {lance_output_path}") |
|
|
| |
| num_new_datasets = df.filter(pl.col("is_new_dataset")).height |
| avg_confidence = df["confidence_score"].mean() |
|
|
| logger.info("=" * 60) |
| logger.info("Classification Complete!") |
| logger.info(f"Total papers classified: {df.height:,}") |
| logger.info( |
| f"Papers with new datasets: {num_new_datasets:,} ({num_new_datasets/df.height*100:.1f}%)" |
| ) |
| logger.info(f"Average confidence score: {avg_confidence:.3f}") |
| logger.info(f"Output dataset: {output_dataset}") |
| logger.info("=" * 60) |
|
|
| |
| if not temp_dir and temp_path.exists(): |
| logger.info(f"Cleaning up temp directory: {temp_path}") |
| shutil.rmtree(temp_path) |
|
|
|
|
| |
| |
| |
|
|
| if __name__ == "__main__": |
| parser = argparse.ArgumentParser( |
| description="Classify arXiv CS papers for new datasets (Lance output)", |
| formatter_class=argparse.RawDescriptionHelpFormatter, |
| epilog=""" |
| Examples: |
| # Incremental update (only new papers since last run) |
| uv run classify_arxiv_to_lance.py |
| |
| # Full refresh (reprocess all papers) |
| uv run classify_arxiv_to_lance.py --full-refresh |
| |
| # Test with small sample |
| uv run classify_arxiv_to_lance.py --limit 100 |
| |
| # Run on HF Jobs with A100 |
| hf jobs uv run \\ |
| --flavor a100-large \\ |
| --image vllm/vllm-openai \\ |
| --secrets HF_TOKEN \\ |
| classify_arxiv_to_lance.py --full-refresh |
| """, |
| ) |
|
|
| parser.add_argument( |
| "--input-dataset", |
| type=str, |
| default=DEFAULT_INPUT_DATASET, |
| help=f"Input dataset on HuggingFace Hub (default: {DEFAULT_INPUT_DATASET})", |
| ) |
| parser.add_argument( |
| "--output-dataset", |
| type=str, |
| default=DEFAULT_OUTPUT_DATASET, |
| help=f"Output Lance dataset on HuggingFace Hub (default: {DEFAULT_OUTPUT_DATASET})", |
| ) |
| parser.add_argument( |
| "--model", |
| type=str, |
| default=DEFAULT_MODEL, |
| help=f"Model ID for classification (default: {DEFAULT_MODEL})", |
| ) |
| parser.add_argument( |
| "--batch-size", |
| type=int, |
| help="Batch size for inference (auto-detected based on backend if not specified)", |
| ) |
| parser.add_argument( |
| "--limit", |
| type=int, |
| help="Limit number of papers for testing", |
| ) |
| parser.add_argument( |
| "--full-refresh", |
| action="store_true", |
| help="Process all papers regardless of update date (monthly refresh)", |
| ) |
| parser.add_argument( |
| "--temp-dir", |
| type=str, |
| help="Directory for temporary files (auto-created if not specified)", |
| ) |
| parser.add_argument( |
| "--hf-token", |
| type=str, |
| help="HuggingFace token (can also use HF_TOKEN env var)", |
| ) |
|
|
| args = parser.parse_args() |
|
|
| main( |
| input_dataset=args.input_dataset, |
| output_dataset=args.output_dataset, |
| model_id=args.model, |
| batch_size=args.batch_size, |
| limit=args.limit, |
| full_refresh=args.full_refresh, |
| temp_dir=args.temp_dir, |
| hf_token=args.hf_token, |
| ) |
|
|