transformers-inference

HuggingFace Transformers for model inference. Use when: text classification, NER, question answering, summarization, embeddings, zero-shot classification. NOT for: training large models (use cloud), simple regex/rule-based tasks, production serving at scale (use vLLM).

564 stars

Best use case

transformers-inference is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

HuggingFace Transformers for model inference. Use when: text classification, NER, question answering, summarization, embeddings, zero-shot classification. NOT for: training large models (use cloud), simple regex/rule-based tasks, production serving at scale (use vLLM).

Teams using transformers-inference should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/transformers-inference/SKILL.md --create-dirs "https://raw.githubusercontent.com/beita6969/ScienceClaw/main/skills/transformers-inference/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/transformers-inference/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How transformers-inference Compares

Feature / Agenttransformers-inferenceStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

HuggingFace Transformers for model inference. Use when: text classification, NER, question answering, summarization, embeddings, zero-shot classification. NOT for: training large models (use cloud), simple regex/rule-based tasks, production serving at scale (use vLLM).

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# HuggingFace Transformers Inference

Text classification, NER, question answering, summarization, embeddings, and zero-shot classification using pretrained models.

## When to Use / When NOT to Use

**Use when:** text classification, named entity recognition, question answering, summarization, text generation, sentence embeddings, zero-shot classification, translation, fill-mask tasks.

**NOT for:** training large models from scratch (use cloud GPU clusters), simple regex or rule-based text processing, production serving at scale (use vLLM or TGI), tasks that don't need neural models.

## Quick Pipelines

```python
from transformers import pipeline

# Text classification (sentiment)
clf = pipeline("text-classification", model="distilbert-base-uncased-finetuned-sst-2-english")
result = clf("This movie was fantastic!")
# [{'label': 'POSITIVE', 'score': 0.9998}]

# Named entity recognition
ner = pipeline("ner", model="dslim/bert-base-NER", aggregation_strategy="simple")
entities = ner("Hugging Face is based in New York City.")
# [{'entity_group': 'ORG', ...}, {'entity_group': 'LOC', ...}]

# Question answering (extractive)
qa = pipeline("question-answering", model="distilbert-base-cased-distilled-squad")
answer = qa(question="What is the capital of France?",
            context="France is a country in Europe. Its capital is Paris.")
# {'answer': 'Paris', 'score': 0.99, ...}

# Summarization
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
summary = summarizer(long_text, max_length=130, min_length=30, do_sample=False)

# Zero-shot classification (no task-specific training needed)
zsc = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
result = zsc("I need to pay my electricity bill",
             candidate_labels=["finance", "health", "technology"])
# {'labels': ['finance', ...], 'scores': [0.95, ...]}
```

## Manual Model and Tokenizer Loading

```python
from transformers import AutoTokenizer, AutoModel, AutoModelForSequenceClassification
import torch

model_name = "bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name)

inputs = tokenizer("Hello world", return_tensors="pt", padding=True, truncation=True)
with torch.no_grad():
    outputs = model(**inputs)

# outputs.last_hidden_state: [batch, seq_len, hidden_dim]
# outputs.pooler_output:     [batch, hidden_dim]
```

## Sentence Embeddings (Mean Pooling)

```python
from transformers import AutoTokenizer, AutoModel
import torch
import torch.nn.functional as F

model_name = "sentence-transformers/all-MiniLM-L6-v2"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name)

def get_embeddings(texts):
    inputs = tokenizer(texts, return_tensors="pt", padding=True, truncation=True)
    with torch.no_grad():
        outputs = model(**inputs)
    mask = inputs['attention_mask'].unsqueeze(-1)
    embeddings = (outputs.last_hidden_state * mask).sum(1) / mask.sum(1)
    return F.normalize(embeddings, p=2, dim=1)

embs = get_embeddings(["Hello world", "Hi there"])
similarity = torch.mm(embs, embs.T)  # cosine similarity matrix
```

## Batch Processing

```python
clf = pipeline("text-classification", model="distilbert-base-uncased-finetuned-sst-2-english",
               device=0 if torch.cuda.is_available() else -1)

texts = ["Great product!", "Terrible service.", "It was okay."]
results = clf(texts, batch_size=16)           # batch for throughput

# For large datasets, use dataset streaming
from transformers import pipeline
for result in clf(iter(large_text_list), batch_size=32):
    process(result)
```

## Best Practices

1. Use `pipeline()` for quick prototyping; load model/tokenizer manually for custom logic.
2. Set `device=0` for GPU or `device="mps"` on Apple Silicon; default is CPU.
3. Always use `torch.no_grad()` during inference to save memory.
4. Use `truncation=True` and `max_length` to handle long inputs safely.
5. For repeated inference, load the model once and reuse; avoid reloading per call.
6. Prefer distilled models (distilbert, distilgpt2) for faster inference when accuracy allows.
7. Use `model.half()` or `torch.float16` to reduce memory footprint on GPU.
8. Cache models locally with `TRANSFORMERS_CACHE` env var to avoid repeated downloads.

Related Skills

xurl

564
from beita6969/ScienceClaw

A CLI tool for making authenticated requests to the X (Twitter) API. Use this skill when you need to post tweets, reply, quote, search, read posts, manage followers, send DMs, upload media, or interact with any X API v2 endpoint.

xlsx

564
from beita6969/ScienceClaw

Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved.

writing

564
from beita6969/ScienceClaw

No description provided.

world-bank-data

564
from beita6969/ScienceClaw

World Bank Open Data API for development indicators. Use when: user asks about GDP, population, poverty, health, or education statistics by country. NOT for: real-time financial data or stock prices.

wikipedia-search

564
from beita6969/ScienceClaw

Search and fetch structured content from Wikipedia using the MediaWiki API for reliable, encyclopedic information

wikidata-knowledge

564
from beita6969/ScienceClaw

Query Wikidata for structured knowledge using SPARQL and entity search. Use when: (1) finding structured facts about entities (people, places, organizations), (2) querying relationships between entities, (3) cross-referencing external identifiers (Wikipedia, VIAF, GND, ORCID), (4) building knowledge graphs from linked data. NOT for: full-text article content (use Wikipedia API), scientific literature (use semantic-scholar), geospatial data (use OpenStreetMap).

weather

564
from beita6969/ScienceClaw

Get current weather and forecasts via wttr.in or Open-Meteo. Use when: user asks about weather, temperature, or forecasts for any location. NOT for: historical weather data, severe weather alerts, or detailed meteorological analysis. No API key needed.

wacli

564
from beita6969/ScienceClaw

Send WhatsApp messages to other people or search/sync WhatsApp history via the wacli CLI (not for normal user chats).

voice-call

564
from beita6969/ScienceClaw

Start voice calls via the OpenClaw voice-call plugin.

visualization

564
from beita6969/ScienceClaw

Create publication-quality scientific figures and plots using Python (matplotlib, seaborn, plotly). Supports bar charts, scatter plots, heatmaps, box plots, violin plots, survival curves, network graphs, and more. Use when user asks to plot data, create figures, make charts, visualize results, or generate publication-ready graphics. Triggers on "plot", "chart", "figure", "graph", "visualize", "heatmap", "scatter plot", "bar chart", "histogram".

video-frames

564
from beita6969/ScienceClaw

Extract frames or short clips from videos using ffmpeg.

venue-templates

564
from beita6969/ScienceClaw

Access comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.