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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.10"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "huggingface-hub[hf_transfer]>=0.20",
|
| 5 |
+
# "polars>=1.0",
|
| 6 |
+
# "torch>=2.0",
|
| 7 |
+
# "transformers>=4.40",
|
| 8 |
+
# "vllm",
|
| 9 |
+
# "pylance>=0.20",
|
| 10 |
+
# "pyarrow>=15.0",
|
| 11 |
+
# "tqdm",
|
| 12 |
+
# "toolz",
|
| 13 |
+
# ]
|
| 14 |
+
# [[tool.uv.index]]
|
| 15 |
+
# url = "https://wheels.vllm.ai/nightly"
|
| 16 |
+
# ///
|
| 17 |
+
"""
|
| 18 |
+
Classify arXiv CS papers to identify which ones introduce new datasets.
|
| 19 |
+
|
| 20 |
+
This script processes papers from the arxiv-metadata-snapshot dataset,
|
| 21 |
+
classifies them using a fine-tuned ModernBERT model, and outputs results
|
| 22 |
+
to Lance format for efficient vector search on the HF Hub.
|
| 23 |
+
|
| 24 |
+
Output supports direct remote queries via the hf:// protocol, enabling
|
| 25 |
+
semantic search without downloading the full dataset.
|
| 26 |
+
|
| 27 |
+
Example usage:
|
| 28 |
+
# Incremental update (only new papers since last run)
|
| 29 |
+
uv run classify_arxiv_to_lance.py
|
| 30 |
+
|
| 31 |
+
# Full refresh (reprocess everything)
|
| 32 |
+
uv run classify_arxiv_to_lance.py --full-refresh
|
| 33 |
+
|
| 34 |
+
# Test with small sample
|
| 35 |
+
uv run classify_arxiv_to_lance.py --limit 100
|
| 36 |
+
|
| 37 |
+
# Run on HF Jobs (A100)
|
| 38 |
+
hf jobs uv run \\
|
| 39 |
+
--flavor a100-large \\
|
| 40 |
+
--image vllm/vllm-openai \\
|
| 41 |
+
--secrets HF_TOKEN \\
|
| 42 |
+
classify_arxiv_to_lance.py
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
from __future__ import annotations
|
| 46 |
+
|
| 47 |
+
import argparse
|
| 48 |
+
import logging
|
| 49 |
+
import os
|
| 50 |
+
import shutil
|
| 51 |
+
import tempfile
|
| 52 |
+
from datetime import datetime
|
| 53 |
+
from pathlib import Path
|
| 54 |
+
from typing import TYPE_CHECKING
|
| 55 |
+
|
| 56 |
+
import polars as pl
|
| 57 |
+
import pyarrow as pa
|
| 58 |
+
import torch
|
| 59 |
+
from huggingface_hub import HfApi, login
|
| 60 |
+
from toolz import partition_all
|
| 61 |
+
from tqdm.auto import tqdm
|
| 62 |
+
|
| 63 |
+
# Conditional imports for type checking
|
| 64 |
+
if TYPE_CHECKING:
|
| 65 |
+
from typing import Optional
|
| 66 |
+
|
| 67 |
+
# Try to import vLLM - may not be available in all environments
|
| 68 |
+
try:
|
| 69 |
+
import vllm
|
| 70 |
+
from vllm import LLM
|
| 71 |
+
|
| 72 |
+
VLLM_AVAILABLE = True
|
| 73 |
+
except ImportError:
|
| 74 |
+
VLLM_AVAILABLE = False
|
| 75 |
+
|
| 76 |
+
# Try to import lance
|
| 77 |
+
try:
|
| 78 |
+
import lance
|
| 79 |
+
|
| 80 |
+
LANCE_AVAILABLE = True
|
| 81 |
+
except ImportError:
|
| 82 |
+
LANCE_AVAILABLE = False
|
| 83 |
+
|
| 84 |
+
# Logging setup
|
| 85 |
+
logging.basicConfig(
|
| 86 |
+
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
|
| 87 |
+
)
|
| 88 |
+
logger = logging.getLogger(__name__)
|
| 89 |
+
|
| 90 |
+
# =============================================================================
|
| 91 |
+
# Constants
|
| 92 |
+
# =============================================================================
|
| 93 |
+
|
| 94 |
+
DEFAULT_INPUT_DATASET = "librarian-bots/arxiv-metadata-snapshot"
|
| 95 |
+
DEFAULT_OUTPUT_DATASET = "davanstrien/arxiv-cs-papers-lance"
|
| 96 |
+
DEFAULT_MODEL = "davanstrien/ModernBERT-base-is-new-arxiv-dataset"
|
| 97 |
+
|
| 98 |
+
# Batch sizes tuned for different backends
|
| 99 |
+
BATCH_SIZES = {
|
| 100 |
+
"vllm": 500_000, # vLLM on A100 can handle large batches
|
| 101 |
+
"cuda": 256, # transformers on CUDA needs smaller batches
|
| 102 |
+
"mps": 1_000, # Apple Silicon
|
| 103 |
+
"cpu": 100, # CPU fallback
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
# Lance output path within the dataset repo
|
| 107 |
+
LANCE_DATA_PATH = "data/train.lance"
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# =============================================================================
|
| 111 |
+
# Backend Detection
|
| 112 |
+
# =============================================================================
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def check_backend() -> tuple[str, int]:
|
| 116 |
+
"""
|
| 117 |
+
Check available backend and return (backend_name, recommended_batch_size).
|
| 118 |
+
|
| 119 |
+
Priority: vLLM (CUDA) > CUDA (transformers) > MPS > CPU
|
| 120 |
+
|
| 121 |
+
Returns:
|
| 122 |
+
Tuple of (backend_name, batch_size) where backend is
|
| 123 |
+
'vllm', 'cuda', 'mps', or 'cpu'
|
| 124 |
+
"""
|
| 125 |
+
if torch.cuda.is_available() and VLLM_AVAILABLE:
|
| 126 |
+
gpu_name = torch.cuda.get_device_name(0)
|
| 127 |
+
gpu_memory = torch.cuda.get_device_properties(0).total_memory / 1024**3
|
| 128 |
+
logger.info(f"GPU detected: {gpu_name} with {gpu_memory:.1f} GB memory")
|
| 129 |
+
logger.info(f"vLLM version: {vllm.__version__}")
|
| 130 |
+
return "vllm", BATCH_SIZES["vllm"]
|
| 131 |
+
elif torch.cuda.is_available():
|
| 132 |
+
gpu_name = torch.cuda.get_device_name(0)
|
| 133 |
+
gpu_memory = torch.cuda.get_device_properties(0).total_memory / 1024**3
|
| 134 |
+
logger.info(f"GPU detected: {gpu_name} with {gpu_memory:.1f} GB memory")
|
| 135 |
+
logger.info("vLLM not available, using transformers with CUDA")
|
| 136 |
+
return "cuda", BATCH_SIZES["cuda"]
|
| 137 |
+
elif torch.backends.mps.is_available():
|
| 138 |
+
logger.info("Using Apple Silicon MPS device with transformers")
|
| 139 |
+
return "mps", BATCH_SIZES["mps"]
|
| 140 |
+
else:
|
| 141 |
+
logger.info("Using CPU device with transformers")
|
| 142 |
+
return "cpu", BATCH_SIZES["cpu"]
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# =============================================================================
|
| 146 |
+
# Incremental Processing Support
|
| 147 |
+
# =============================================================================
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def get_last_update_date(
|
| 151 |
+
output_dataset: str, hf_token: Optional[str] = None
|
| 152 |
+
) -> Optional[str]:
|
| 153 |
+
"""
|
| 154 |
+
Get the maximum update_date from the existing Lance dataset on HF Hub.
|
| 155 |
+
|
| 156 |
+
Uses the hf:// protocol to query the remote Lance dataset directly,
|
| 157 |
+
avoiding the need to download the entire dataset.
|
| 158 |
+
|
| 159 |
+
Args:
|
| 160 |
+
output_dataset: HuggingFace dataset ID (e.g., "davanstrien/arxiv-cs-papers-lance")
|
| 161 |
+
hf_token: Optional HuggingFace token for private datasets
|
| 162 |
+
|
| 163 |
+
Returns:
|
| 164 |
+
ISO format date string of the last update, or None if dataset doesn't exist
|
| 165 |
+
"""
|
| 166 |
+
raise NotImplementedError("Sub-task 3.3: Implement Lance remote query for max date")
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
# =============================================================================
|
| 170 |
+
# Data Preparation
|
| 171 |
+
# =============================================================================
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def prepare_incremental_data(
|
| 175 |
+
input_dataset: str,
|
| 176 |
+
temp_dir: Path,
|
| 177 |
+
last_update_date: Optional[str] = None,
|
| 178 |
+
limit: Optional[int] = None,
|
| 179 |
+
full_refresh: bool = False,
|
| 180 |
+
) -> Optional[pl.DataFrame]:
|
| 181 |
+
"""
|
| 182 |
+
Prepare data for incremental classification.
|
| 183 |
+
|
| 184 |
+
Downloads source dataset, filters to CS papers, applies incremental
|
| 185 |
+
filtering based on last_update_date, and formats text for classification.
|
| 186 |
+
|
| 187 |
+
Args:
|
| 188 |
+
input_dataset: Source dataset ID on HF Hub
|
| 189 |
+
temp_dir: Directory for temporary files
|
| 190 |
+
last_update_date: Date of last classification run (for incremental mode)
|
| 191 |
+
limit: Optional limit for testing
|
| 192 |
+
full_refresh: If True, process all papers regardless of date
|
| 193 |
+
|
| 194 |
+
Returns:
|
| 195 |
+
Polars DataFrame ready for classification, or None if no new papers
|
| 196 |
+
"""
|
| 197 |
+
raise NotImplementedError("Sub-task 3.4: Implement Polars filtering and formatting")
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
# =============================================================================
|
| 201 |
+
# Classification Functions
|
| 202 |
+
# =============================================================================
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def classify_with_vllm(
|
| 206 |
+
df: pl.DataFrame,
|
| 207 |
+
model_id: str,
|
| 208 |
+
batch_size: int = 500_000,
|
| 209 |
+
) -> list[dict]:
|
| 210 |
+
"""
|
| 211 |
+
Classify papers using vLLM for efficient GPU inference.
|
| 212 |
+
|
| 213 |
+
Uses vLLM's pooling runner for sequence classification, which provides
|
| 214 |
+
significant speedup over transformers pipeline on large batches.
|
| 215 |
+
|
| 216 |
+
Args:
|
| 217 |
+
df: DataFrame with 'text_for_classification' column
|
| 218 |
+
model_id: HuggingFace model ID for classification
|
| 219 |
+
batch_size: Number of texts to process per batch
|
| 220 |
+
|
| 221 |
+
Returns:
|
| 222 |
+
List of dicts with keys: classification_label, is_new_dataset, confidence_score
|
| 223 |
+
"""
|
| 224 |
+
raise NotImplementedError("Sub-task 3.5: Implement vLLM classification")
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def classify_with_transformers(
|
| 228 |
+
df: pl.DataFrame,
|
| 229 |
+
model_id: str,
|
| 230 |
+
batch_size: int = 1_000,
|
| 231 |
+
device: str = "cpu",
|
| 232 |
+
) -> list[dict]:
|
| 233 |
+
"""
|
| 234 |
+
Classify papers using transformers pipeline.
|
| 235 |
+
|
| 236 |
+
Fallback for environments without vLLM or for smaller datasets.
|
| 237 |
+
|
| 238 |
+
Args:
|
| 239 |
+
df: DataFrame with 'text_for_classification' column
|
| 240 |
+
model_id: HuggingFace model ID for classification
|
| 241 |
+
batch_size: Number of texts to process per batch
|
| 242 |
+
device: Device to use ('cuda', 'mps', or 'cpu')
|
| 243 |
+
|
| 244 |
+
Returns:
|
| 245 |
+
List of dicts with keys: classification_label, is_new_dataset, confidence_score
|
| 246 |
+
"""
|
| 247 |
+
raise NotImplementedError("Sub-task 3.5: Implement transformers fallback")
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
# =============================================================================
|
| 251 |
+
# Output to Lance
|
| 252 |
+
# =============================================================================
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def save_to_lance(
|
| 256 |
+
df: pl.DataFrame,
|
| 257 |
+
output_path: Path,
|
| 258 |
+
mode: str = "overwrite",
|
| 259 |
+
) -> None:
|
| 260 |
+
"""
|
| 261 |
+
Save classified DataFrame to Lance format.
|
| 262 |
+
|
| 263 |
+
Args:
|
| 264 |
+
df: Classified DataFrame with all columns
|
| 265 |
+
output_path: Local path for Lance dataset
|
| 266 |
+
mode: 'overwrite' for full refresh, 'append' for incremental
|
| 267 |
+
"""
|
| 268 |
+
raise NotImplementedError("Sub-task 3.6: Implement Lance output")
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def upload_to_hub(
|
| 272 |
+
lance_path: Path,
|
| 273 |
+
output_dataset: str,
|
| 274 |
+
hf_token: Optional[str] = None,
|
| 275 |
+
) -> None:
|
| 276 |
+
"""
|
| 277 |
+
Upload Lance dataset to HuggingFace Hub.
|
| 278 |
+
|
| 279 |
+
Args:
|
| 280 |
+
lance_path: Local path to Lance dataset
|
| 281 |
+
output_dataset: Target dataset ID on HF Hub
|
| 282 |
+
hf_token: HuggingFace token for authentication
|
| 283 |
+
"""
|
| 284 |
+
raise NotImplementedError("Sub-task 3.6: Implement HF Hub upload")
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
# =============================================================================
|
| 288 |
+
# Main Pipeline
|
| 289 |
+
# =============================================================================
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def main(
|
| 293 |
+
input_dataset: str = DEFAULT_INPUT_DATASET,
|
| 294 |
+
output_dataset: str = DEFAULT_OUTPUT_DATASET,
|
| 295 |
+
model_id: str = DEFAULT_MODEL,
|
| 296 |
+
batch_size: Optional[int] = None,
|
| 297 |
+
limit: Optional[int] = None,
|
| 298 |
+
full_refresh: bool = False,
|
| 299 |
+
temp_dir: Optional[str] = None,
|
| 300 |
+
hf_token: Optional[str] = None,
|
| 301 |
+
) -> None:
|
| 302 |
+
"""
|
| 303 |
+
Main classification pipeline.
|
| 304 |
+
|
| 305 |
+
Flow:
|
| 306 |
+
1. Authenticate with HF Hub
|
| 307 |
+
2. Detect backend (vLLM/CUDA/MPS/CPU)
|
| 308 |
+
3. Check for existing Lance dataset, get last update date
|
| 309 |
+
4. Download and filter source data (incremental or full)
|
| 310 |
+
5. Classify papers using appropriate backend
|
| 311 |
+
6. Save results to Lance format
|
| 312 |
+
7. Upload to HF Hub
|
| 313 |
+
8. Print statistics
|
| 314 |
+
|
| 315 |
+
Args:
|
| 316 |
+
input_dataset: Source arxiv metadata dataset
|
| 317 |
+
output_dataset: Target Lance dataset on HF Hub
|
| 318 |
+
model_id: Classification model ID
|
| 319 |
+
batch_size: Override auto-detected batch size
|
| 320 |
+
limit: Limit papers for testing
|
| 321 |
+
full_refresh: Process all papers (ignore existing data)
|
| 322 |
+
temp_dir: Custom temp directory (auto-created if not specified)
|
| 323 |
+
hf_token: HF token (falls back to HF_TOKEN env var)
|
| 324 |
+
"""
|
| 325 |
+
# === Step 0: Setup ===
|
| 326 |
+
logger.info("=" * 60)
|
| 327 |
+
logger.info("ArXiv CS Papers Classification Pipeline (Lance Output)")
|
| 328 |
+
logger.info("=" * 60)
|
| 329 |
+
|
| 330 |
+
# Authentication
|
| 331 |
+
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
|
| 332 |
+
if HF_TOKEN:
|
| 333 |
+
login(token=HF_TOKEN)
|
| 334 |
+
logger.info("Authenticated with HuggingFace Hub")
|
| 335 |
+
else:
|
| 336 |
+
logger.warning("No HF_TOKEN found. May fail for private datasets or uploads.")
|
| 337 |
+
|
| 338 |
+
# Setup temp directory
|
| 339 |
+
if temp_dir:
|
| 340 |
+
temp_path = Path(temp_dir)
|
| 341 |
+
temp_path.mkdir(parents=True, exist_ok=True)
|
| 342 |
+
else:
|
| 343 |
+
temp_path = Path(tempfile.mkdtemp(prefix="arxiv_lance_"))
|
| 344 |
+
logger.info(f"Using temp directory: {temp_path}")
|
| 345 |
+
|
| 346 |
+
# === Step 1: Detect backend ===
|
| 347 |
+
backend, default_batch_size = check_backend()
|
| 348 |
+
if batch_size is None:
|
| 349 |
+
batch_size = default_batch_size
|
| 350 |
+
logger.info(f"Backend: {backend}, Batch size: {batch_size:,}")
|
| 351 |
+
|
| 352 |
+
# === Step 2: Check existing dataset for incremental mode ===
|
| 353 |
+
last_update_date = None
|
| 354 |
+
if not full_refresh:
|
| 355 |
+
last_update_date = get_last_update_date(output_dataset, HF_TOKEN)
|
| 356 |
+
if last_update_date:
|
| 357 |
+
logger.info(f"Incremental mode: processing papers after {last_update_date}")
|
| 358 |
+
else:
|
| 359 |
+
logger.info("No existing dataset found - processing all papers")
|
| 360 |
+
else:
|
| 361 |
+
logger.info("Full refresh mode - processing all papers")
|
| 362 |
+
|
| 363 |
+
# === Step 3: Prepare data ===
|
| 364 |
+
df = prepare_incremental_data(
|
| 365 |
+
input_dataset,
|
| 366 |
+
temp_path,
|
| 367 |
+
last_update_date,
|
| 368 |
+
limit,
|
| 369 |
+
full_refresh,
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
if df is None or df.height == 0:
|
| 373 |
+
logger.info("No new papers to classify. Dataset is up to date!")
|
| 374 |
+
# Cleanup
|
| 375 |
+
if not temp_dir and temp_path.exists():
|
| 376 |
+
shutil.rmtree(temp_path)
|
| 377 |
+
return
|
| 378 |
+
|
| 379 |
+
logger.info(f"Prepared {df.height:,} papers for classification")
|
| 380 |
+
|
| 381 |
+
# === Step 4: Classify papers ===
|
| 382 |
+
if backend == "vllm":
|
| 383 |
+
results = classify_with_vllm(df, model_id, batch_size)
|
| 384 |
+
else:
|
| 385 |
+
results = classify_with_transformers(df, model_id, batch_size, backend)
|
| 386 |
+
|
| 387 |
+
# === Step 5: Add classification results to DataFrame ===
|
| 388 |
+
logger.info("Adding classification results...")
|
| 389 |
+
df = df.with_columns(
|
| 390 |
+
[
|
| 391 |
+
pl.Series("classification_label", [r["classification_label"] for r in results]),
|
| 392 |
+
pl.Series("is_new_dataset", [r["is_new_dataset"] for r in results]),
|
| 393 |
+
pl.Series("confidence_score", [r["confidence_score"] for r in results]),
|
| 394 |
+
pl.lit(datetime.now().isoformat()).alias("classification_date"),
|
| 395 |
+
pl.lit(model_id).alias("model_version"),
|
| 396 |
+
# Placeholder for embeddings (filled by embed_arxiv_lance.py)
|
| 397 |
+
pl.lit(None).cast(pl.List(pl.Float32)).alias("embedding"),
|
| 398 |
+
pl.lit(None).cast(pl.Utf8).alias("embedding_model"),
|
| 399 |
+
]
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
# Remove temporary columns
|
| 403 |
+
if "text_for_classification" in df.columns:
|
| 404 |
+
df = df.drop("text_for_classification")
|
| 405 |
+
|
| 406 |
+
# === Step 6: Save to Lance ===
|
| 407 |
+
lance_output_path = temp_path / "output.lance"
|
| 408 |
+
mode = "overwrite" if full_refresh or last_update_date is None else "append"
|
| 409 |
+
save_to_lance(df, lance_output_path, mode)
|
| 410 |
+
|
| 411 |
+
# === Step 7: Upload to Hub ===
|
| 412 |
+
if HF_TOKEN:
|
| 413 |
+
upload_to_hub(lance_output_path, output_dataset, HF_TOKEN)
|
| 414 |
+
else:
|
| 415 |
+
logger.warning(f"No HF_TOKEN - results saved locally at {lance_output_path}")
|
| 416 |
+
|
| 417 |
+
# === Step 8: Print statistics ===
|
| 418 |
+
num_new_datasets = df.filter(pl.col("is_new_dataset")).height
|
| 419 |
+
avg_confidence = df["confidence_score"].mean()
|
| 420 |
+
|
| 421 |
+
logger.info("=" * 60)
|
| 422 |
+
logger.info("Classification Complete!")
|
| 423 |
+
logger.info(f"Total papers classified: {df.height:,}")
|
| 424 |
+
logger.info(
|
| 425 |
+
f"Papers with new datasets: {num_new_datasets:,} ({num_new_datasets/df.height*100:.1f}%)"
|
| 426 |
+
)
|
| 427 |
+
logger.info(f"Average confidence score: {avg_confidence:.3f}")
|
| 428 |
+
logger.info(f"Output dataset: {output_dataset}")
|
| 429 |
+
logger.info("=" * 60)
|
| 430 |
+
|
| 431 |
+
# Cleanup
|
| 432 |
+
if not temp_dir and temp_path.exists():
|
| 433 |
+
logger.info(f"Cleaning up temp directory: {temp_path}")
|
| 434 |
+
shutil.rmtree(temp_path)
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
# =============================================================================
|
| 438 |
+
# CLI Entry Point
|
| 439 |
+
# =============================================================================
|
| 440 |
+
|
| 441 |
+
if __name__ == "__main__":
|
| 442 |
+
parser = argparse.ArgumentParser(
|
| 443 |
+
description="Classify arXiv CS papers for new datasets (Lance output)",
|
| 444 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 445 |
+
epilog="""
|
| 446 |
+
Examples:
|
| 447 |
+
# Incremental update (only new papers since last run)
|
| 448 |
+
uv run classify_arxiv_to_lance.py
|
| 449 |
+
|
| 450 |
+
# Full refresh (reprocess all papers)
|
| 451 |
+
uv run classify_arxiv_to_lance.py --full-refresh
|
| 452 |
+
|
| 453 |
+
# Test with small sample
|
| 454 |
+
uv run classify_arxiv_to_lance.py --limit 100
|
| 455 |
+
|
| 456 |
+
# Run on HF Jobs with A100
|
| 457 |
+
hf jobs uv run \\
|
| 458 |
+
--flavor a100-large \\
|
| 459 |
+
--image vllm/vllm-openai \\
|
| 460 |
+
--secrets HF_TOKEN \\
|
| 461 |
+
classify_arxiv_to_lance.py --full-refresh
|
| 462 |
+
""",
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
parser.add_argument(
|
| 466 |
+
"--input-dataset",
|
| 467 |
+
type=str,
|
| 468 |
+
default=DEFAULT_INPUT_DATASET,
|
| 469 |
+
help=f"Input dataset on HuggingFace Hub (default: {DEFAULT_INPUT_DATASET})",
|
| 470 |
+
)
|
| 471 |
+
parser.add_argument(
|
| 472 |
+
"--output-dataset",
|
| 473 |
+
type=str,
|
| 474 |
+
default=DEFAULT_OUTPUT_DATASET,
|
| 475 |
+
help=f"Output Lance dataset on HuggingFace Hub (default: {DEFAULT_OUTPUT_DATASET})",
|
| 476 |
+
)
|
| 477 |
+
parser.add_argument(
|
| 478 |
+
"--model",
|
| 479 |
+
type=str,
|
| 480 |
+
default=DEFAULT_MODEL,
|
| 481 |
+
help=f"Model ID for classification (default: {DEFAULT_MODEL})",
|
| 482 |
+
)
|
| 483 |
+
parser.add_argument(
|
| 484 |
+
"--batch-size",
|
| 485 |
+
type=int,
|
| 486 |
+
help="Batch size for inference (auto-detected based on backend if not specified)",
|
| 487 |
+
)
|
| 488 |
+
parser.add_argument(
|
| 489 |
+
"--limit",
|
| 490 |
+
type=int,
|
| 491 |
+
help="Limit number of papers for testing",
|
| 492 |
+
)
|
| 493 |
+
parser.add_argument(
|
| 494 |
+
"--full-refresh",
|
| 495 |
+
action="store_true",
|
| 496 |
+
help="Process all papers regardless of update date (monthly refresh)",
|
| 497 |
+
)
|
| 498 |
+
parser.add_argument(
|
| 499 |
+
"--temp-dir",
|
| 500 |
+
type=str,
|
| 501 |
+
help="Directory for temporary files (auto-created if not specified)",
|
| 502 |
+
)
|
| 503 |
+
parser.add_argument(
|
| 504 |
+
"--hf-token",
|
| 505 |
+
type=str,
|
| 506 |
+
help="HuggingFace token (can also use HF_TOKEN env var)",
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
args = parser.parse_args()
|
| 510 |
+
|
| 511 |
+
main(
|
| 512 |
+
input_dataset=args.input_dataset,
|
| 513 |
+
output_dataset=args.output_dataset,
|
| 514 |
+
model_id=args.model,
|
| 515 |
+
batch_size=args.batch_size,
|
| 516 |
+
limit=args.limit,
|
| 517 |
+
full_refresh=args.full_refresh,
|
| 518 |
+
temp_dir=args.temp_dir,
|
| 519 |
+
hf_token=args.hf_token,
|
| 520 |
+
)
|