arxiv-classifier-dev / classify_arxiv_to_lance.py
davanstrien's picture
davanstrien HF Staff
Upload classify_arxiv_to_lance.py with huggingface_hub
fedc701 verified
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "huggingface-hub[hf_transfer]>=0.20",
# "polars>=1.0",
# "torch>=2.0",
# "transformers>=4.40",
# "vllm",
# "pylance>=0.20",
# "pyarrow>=15.0",
# "tqdm",
# "toolz",
# ]
# [[tool.uv.index]]
# url = "https://wheels.vllm.ai/nightly"
# ///
"""
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
# Conditional imports for type checking
if TYPE_CHECKING:
from typing import Optional
# Try to import vLLM - may not be available in all environments
try:
import vllm
from vllm import LLM
VLLM_AVAILABLE = True
except ImportError:
VLLM_AVAILABLE = False
# Try to import lance
try:
import lance
LANCE_AVAILABLE = True
except ImportError:
LANCE_AVAILABLE = False
# Logging setup
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
# =============================================================================
# Constants
# =============================================================================
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 tuned for different backends
BATCH_SIZES = {
"vllm": 500_000, # vLLM on A100 can handle large batches
"cuda": 256, # transformers on CUDA needs smaller batches
"mps": 1_000, # Apple Silicon
"cpu": 100, # CPU fallback
}
# Lance output path within the dataset repo
LANCE_DATA_PATH = "data/train.lance"
# =============================================================================
# Backend Detection
# =============================================================================
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"]
# =============================================================================
# Incremental Processing Support
# =============================================================================
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
"""
# TODO: Implement incremental mode
# For now, always return None to trigger full refresh
logger.info("Incremental mode not yet implemented - will do full refresh")
return None
# =============================================================================
# Data Preparation
# =============================================================================
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}")
# Download 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")
# Create lazy frame
lf = pl.scan_parquet(parquet_files)
# Filter to CS papers
logger.info("Filtering to CS papers...")
lf_cs = lf.filter(pl.col("categories").str.contains("cs."))
# Apply incremental filter if not full refresh
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")
# Apply limit if specified (for testing) - AFTER filtering to CS
if limit:
logger.info(f"Limiting to {limit} papers for testing")
lf_cs = lf_cs.head(limit)
# Select only the columns we need (drop nested columns that cause issues)
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])
# Add formatted text column for classification
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")
)
# Collect the data
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
# =============================================================================
# Classification Functions
# =============================================================================
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()
# Model config: 0 -> new_dataset, 1 -> no_new_dataset
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
# =============================================================================
# Output to Lance
# =============================================================================
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}")
# Convert Polars DataFrame to PyArrow Table
arrow_table = df.to_arrow()
# Write to Lance format
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:
# Append mode for incremental updates
lance.write_dataset(arrow_table, str(output_path), mode="append")
logger.info(f"Appended to existing Lance dataset at {output_path}")
# Verify the write
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()
# Create the dataset repo if it doesn't exist
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}")
# Upload the Lance directory
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}")
# =============================================================================
# Main Pipeline
# =============================================================================
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)
"""
# === Step 0: Setup ===
logger.info("=" * 60)
logger.info("ArXiv CS Papers Classification Pipeline (Lance Output)")
logger.info("=" * 60)
# Authentication
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.")
# Setup temp directory
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}")
# === Step 1: Detect backend ===
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:,}")
# === Step 2: Check existing dataset for incremental mode ===
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")
# === Step 3: Prepare data ===
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!")
# Cleanup
if not temp_dir and temp_path.exists():
shutil.rmtree(temp_path)
return
logger.info(f"Prepared {df.height:,} papers for classification")
# === Step 4: Classify papers ===
if backend == "vllm":
results = classify_with_vllm(df, model_id, batch_size)
else:
results = classify_with_transformers(df, model_id, batch_size, backend)
# === Step 5: Add classification results to DataFrame ===
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"),
# Placeholder for embeddings (filled by embed_arxiv_lance.py)
pl.lit(None).cast(pl.List(pl.Float32)).alias("embedding"),
pl.lit(None).cast(pl.Utf8).alias("embedding_model"),
]
)
# Remove temporary columns
if "text_for_classification" in df.columns:
df = df.drop("text_for_classification")
# === Step 6: Save to Lance ===
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)
# === Step 7: Upload to Hub ===
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}")
# === Step 8: Print statistics ===
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)
# Cleanup
if not temp_dir and temp_path.exists():
logger.info(f"Cleaning up temp directory: {temp_path}")
shutil.rmtree(temp_path)
# =============================================================================
# CLI Entry Point
# =============================================================================
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,
)