File size: 12,077 Bytes
3879aae 4fcb6ed 877e393 3879aae 877e393 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 |
---
license: mit
viewer: false
task_categories:
- zero-shot-classification
- text-classification
tags:
- uv-script
- classification
- structured-outputs
- zero-shot
---
# Hugging Face Dataset Classification With Sieves
GPU-accelerated text classification for Hugging Face datasets with guaranteed valid outputs through structured
generation with [Sieves](https://github.com/MantisAI/sieves/), [Outlines](https://github.com/dottxt-ai/outlines) and
Hugging Face zero-shot pipelines.
This is a modified version of https://huggingface.co/datasets/uv-scripts/classification.
## π Quick Start
```bash
# Classify IMDB reviews
uv run examples/classify-dataset.py \
--input-dataset stanfordnlp/imdb \
--column text \
--labels "positive,negative" \
--model HuggingFaceTB/SmolLM-360M-Instruct \
--output-dataset user/imdb-classified
```
That's it! No installation, no setup - just `uv run`.
## π Requirements
- **GPU Recommended**: Uses GPU-accelerated inference (CPU fallback available but slow)
- Python 3.12+
- UV (will handle all dependencies automatically)
**Python Package Dependencies** (automatically installed via UV):
- `sieves` with engines support (>= 0.17.4)
- `typer` (>= 0.12)
- `datasets`
- `huggingface-hub`
## π― Features
- **Guaranteed valid outputs** using structured generation with Outlines guided decoding
- **Zero-shot classification** without training data required
- **GPU-optimized** for maximum throughput and efficiency
- **Multi-label support** for documents with multiple applicable labels
- **Flexible model selection** - works with any instruction-tuned transformer model
- **Robust text handling** with preprocessing and validation
- **Automatic progress tracking** and detailed statistics
- **Direct Hub integration** - read and write datasets seamlessly
- **Label descriptions** support for providing context to improve accuracy
- **Optimized batching** with Sieves' automatic batch processing
- **Multiple guided backends** - supports `outlines` to handle any general language model on Hugging Face, and fast Hugging Face zero-shot classification pipelines
## π» Usage
### Basic Classification
```bash
uv run examples/classify-dataset.py \
--input-dataset <dataset-id> \
--column <text-column> \
--labels <comma-separated-labels> \
--model <model-id> \
--output-dataset <output-id>
```
### Arguments
**Required:**
- `--input-dataset`: Hugging Face dataset ID (e.g., `stanfordnlp/imdb`, `user/my-dataset`)
- `--column`: Name of the text column to classify
- `--labels`: Comma-separated classification labels (e.g., `"spam,ham"`)
- `--model`: Model to use (e.g., `HuggingFaceTB/SmolLM-360M-Instruct`)
- `--output-dataset`: Where to save the classified dataset
**Optional:**
- `--label-descriptions`: Provide descriptions for each label to improve classification accuracy
- `--multi-label`: Enable multi-label classification mode (creates multi-hot encoded labels)
- `--split`: Dataset split to process (default: `train`)
- `--max-samples`: Limit samples for testing
- `--shuffle`: Shuffle dataset before selecting samples (useful for random sampling)
- `--shuffle-seed`: Random seed for shuffling
- `--batch-size`: Batch size for inference (default: 64)
- `--max-tokens`: Maximum tokens to generate per sample (default: 200)
- `--hf-token`: Hugging Face token (or use `HF_TOKEN` env var)
### Label Descriptions
Provide context for your labels to improve classification accuracy:
```bash
uv run examples/classify-dataset.py \
--input-dataset user/support-tickets \
--column content \
--labels "bug,feature,question,other" \
--label-descriptions "bug:something is broken,feature:request for new functionality,question:asking for help,other:anything else" \
--model HuggingFaceTB/SmolLM-360M-Instruct \
--output-dataset user/tickets-classified
```
The model uses these descriptions to better understand what each label represents, leading to more accurate classifications.
### Multi-Label Classification
Enable multi-label mode for documents that can have multiple applicable labels:
```bash
uv run examples/classify-dataset.py \
--input-dataset ag_news \
--column text \
--labels "world,sports,business,science" \
--multi-label \
--model HuggingFaceTB/SmolLM-360M-Instruct \
--output-dataset user/ag-news-multilabel
```
## π Examples
### Sentiment Analysis
```bash
uv run examples/classify-dataset.py \
--input-dataset stanfordnlp/imdb \
--column text \
--labels "positive,ambivalent,negative" \
--model HuggingFaceTB/SmolLM-360M-Instruct \
--output-dataset user/imdb-sentiment
```
### Support Ticket Classification
```bash
uv run examples/classify-dataset.py \
--input-dataset user/support-tickets \
--column content \
--labels "bug,feature_request,question,other" \
--label-descriptions "bug:code or product not working as expected,feature_request:asking for new functionality,question:seeking help or clarification,other:general comments or feedback" \
--model HuggingFaceTB/SmolLM-360M-Instruct \
--output-dataset user/tickets-classified
```
### News Categorization
```bash
uv run examples/classify-dataset.py \
--input-dataset ag_news \
--column text \
--labels "world,sports,business,tech" \
--model HuggingFaceTB/SmolLM-1.7B-Instruct \
--output-dataset user/ag-news-categorized
```
### Multi-Label News Classification
```bash
uv run examples/classify-dataset.py \
--input-dataset ag_news \
--column text \
--labels "world,sports,business,tech" \
--multi-label \
--label-descriptions "world:global and international events,sports:sports and athletics,business:business and finance,tech:technology and innovation" \
--model HuggingFaceTB/SmolLM-1.7B-Instruct \
--output-dataset user/ag-news-multilabel
```
This combines label descriptions with multi-label mode for comprehensive categorization of news articles.
### ArXiv ML Research Classification
Classify academic papers into machine learning research areas:
```bash
# Fast classification with random sampling
uv run examples/classify-dataset.py \
--input-dataset librarian-bots/arxiv-metadata-snapshot \
--column abstract \
--labels "llm,computer_vision,reinforcement_learning,optimization,theory,other" \
--label-descriptions "llm:language models and NLP,computer_vision:image and video processing,reinforcement_learning:RL and decision making,optimization:training and efficiency,theory:theoretical ML foundations,other:other ML topics" \
--model HuggingFaceTB/SmolLM-360M-Instruct \
--output-dataset user/arxiv-ml-classified \
--split "train" \
--max-samples 100 \
--shuffle
# Multi-label for nuanced classification
uv run examples/classify-dataset.py \
--input-dataset librarian-bots/arxiv-metadata-snapshot \
--column abstract \
--labels "multimodal,agents,reasoning,safety,efficiency" \
--label-descriptions "multimodal:vision-language and cross-modal models,agents:autonomous agents and tool use,reasoning:reasoning and planning systems,safety:alignment and safety research,efficiency:model optimization and deployment" \
--multi-label \
--model HuggingFaceTB/SmolLM-360M-Instruct \
--output-dataset user/arxiv-frontier-research \
--split "train[:1000]" \
--max-samples 50
```
Multi-label mode is particularly valuable for academic abstracts where papers often span multiple topics and require careful analysis to determine all relevant research areas.
## π Running Locally vs Cloud
This script is optimized to run locally on GPU-equipped machines:
```bash
# Local execution with your GPU
uv run examples/classify-dataset.py \
--input-dataset stanfordnlp/imdb \
--column text \
--labels "positive,negative" \
--model HuggingFaceTB/SmolLM-360M-Instruct \
--output-dataset user/imdb-classified
```
For cloud deployment, you can use Hugging Face Spaces or other GPU services by adapting the command to your environment.
## π§ Advanced Usage
### Random Sampling
When working with ordered datasets, use `--shuffle` with `--max-samples` to get a representative sample:
```bash
# Get 50 random reviews instead of the first 50
uv run examples/classify-dataset.py \
--input-dataset stanfordnlp/imdb \
--column text \
--labels "positive,negative" \
--model HuggingFaceTB/SmolLM-360M-Instruct \
--output-dataset user/imdb-sample \
--max-samples 50 \
--shuffle \
--shuffle-seed 123 # For reproducibility
```
### Using Different Models
By default, this script works with any instruction-tuned model. Here are some recommended options:
```bash
# Lightweight model for fast classification
uv run examples/classify-dataset.py \
--input-dataset user/my-dataset \
--column text \
--labels "A,B,C" \
--model HuggingFaceTB/SmolLM-360M-Instruct \
--output-dataset user/classified
# Larger model for complex classification
uv run examples/classify-dataset.py \
--input-dataset user/legal-docs \
--column text \
--labels "contract,patent,brief,memo,other" \
--model HuggingFaceTB/SmolLM3-3B-Instruct \
--output-dataset user/legal-classified
# Specialized zero-shot classifier
uv run examples/classify-dataset.py \
--input-dataset user/my-dataset \
--column text \
--labels "A,B,C" \
--model MoritzLaurer/deberta-v3-large-zeroshot-v2.0 \
--output-dataset user/classified
```
### Large Datasets
Configure `--batch-size` for more effective batch processing with large datasets:
```bash
uv run examples/classify-dataset.py \
--input-dataset user/huge-dataset \
--column text \
--labels "A,B,C" \
--model HuggingFaceTB/SmolLM-360M-Instruct \
--output-dataset user/huge-classified \
--batch-size 128
```
## π€ How It Works
1. **Sieves**: Provides a zero-shot task pipeline system for structured NLP workflows
2. **Outlines**: Provides guided decoding to guarantee valid label outputs
3. **UV**: Handles all dependencies automatically
The script loads your dataset, preprocesses texts, classifies each one with guaranteed valid outputs using Sieves'
`Classification` task, then saves the results as a new column in the output dataset.
## π Troubleshooting
### GPU Not Available
This script works best with a GPU but can run on CPU (much slower). To use GPU:
- Run on a machine with NVIDIA GPU
- Use cloud GPU instances (AWS, GCP, Azure, etc.)
- Use Hugging Face Spaces with GPU
### Out of Memory
- Use a smaller model (e.g., SmolLM-360M instead of 3B)
- Reduce `--batch-size` (try 32, 16, or 8)
- Reduce `--max-tokens` for shorter generations
### Invalid/Skipped Texts
- Texts shorter than 3 characters are skipped
- Empty or None values are marked as invalid
- Very long texts are truncated to 4000 characters
### Classification Quality
- With Outlines guided decoding, outputs are guaranteed to be valid labels
- For better results, use clear and distinct label names
- Try `--label-descriptions` to provide context
- Use a larger model for nuanced tasks
- In multi-label mode, adjust the confidence threshold (defaults to 0.5)
### Authentication Issues
If you see authentication errors:
- Run `huggingface-cli login` to cache your token
- Or set `export HF_TOKEN=your_token_here`
- Verify your token has read/write permissions on the Hub
## π¬ Advanced Workflows
### Full Pipeline Workflow
Start with small tests, then run on the full dataset:
```bash
# Step 1: Test with small sample
uv run examples/classify-dataset.py \
--input-dataset your-dataset \
--column text \
--labels "label1,label2,label3" \
--model HuggingFaceTB/SmolLM-360M-Instruct \
--output-dataset user/test-classification \
--max-samples 100
# Step 2: If results look good, run on full dataset
uv run examples/classify-dataset.py \
--input-dataset your-dataset \
--column text \
--labels "label1,label2,label3" \
--label-descriptions "label1:description,label2:description,label3:description" \
--model HuggingFaceTB/SmolLM-360M-Instruct \
--output-dataset user/final-classification \
--batch-size 64
```
## π License
This example is provided as part of the [Sieves](https://github.com/MantisAI/sieves/) project. |