Generated banner for Transformers
Generated logo for Transformers

Transformers

K-DenseCommunityCreated by K-Dense Inc.

  • Skill
  • Tool integration
  • Data and AI
  • MIT
  • Low risk

From the author

Hugging Face Transformers for loading Hub models, running pipeline inference, text generation, and Trainer fine-tuning on NLP, vision, audio, and multimodal tasks. Applies when working with AutoModel, pipelines, tokenizers, generation configs, or TrainingArguments within Transformers.
— the description by K-Dense Inc.

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The Transformers skill provides a programmatic interface to the Hugging Face ecosystem, enabling users to load pre-trained models, execute inference pipelines, and perform fine-tuning on custom datasets. It supports a wide range of modalities including text, vision, and audio, with specific utilities for tokenization, generation control, and device management using the Trainer API.

What it does

  • Loads pre-trained models via AutoModel classes for various tasks.
  • Executes inference using the Pipeline API for rapid prototyping.
  • Configures text generation parameters such as temperature, top-k, and top-p sampling.
  • Facilitates model fine-tuning using the Trainer API with support for custom datasets.
  • Manages tokenization, including padding, truncation, and special token handling.
  • Handles authentication for private or gated models via the Hugging Face Hub.

When to use it

  • When integrating pre-trained models into custom Python workflows.
  • For performing inference on text, audio, or vision data.
  • When fine-tuning models on domain-specific datasets.
  • For managing complex model configurations and device placement.

Advantages

  • Provides unified access to diverse model architectures.
  • Simplifies complex tasks through high-level pipeline abstractions.
  • Offers granular control over model precision and hardware utilization.
  • Supports standard authentication patterns for secure model access.

Usage examples

“Use the pipeline API to generate text with a specific model.”
The agent initializes a text-generation pipeline with the specified model and returns generated text based on the input prompt.
“Load a model for sequence classification with custom device mapping.”
The agent uses AutoModelForSequenceClassification to load the model, applying automatic device placement for optimized execution.
“Fine-tune a model using the Trainer API.”
The agent configures TrainingArguments and initializes a Trainer instance to execute the fine-tuning process on the provided dataset.
“Authenticate to the Hugging Face Hub for private model access.”
The agent guides the user through the CLI login process or environment variable configuration to securely access gated models.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/k-dense-ai/transformers/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip transformers.zip -d .agents/skills

Documentation by K-Dense Inc.

Transformers

Overview

The Hugging Face Transformers library provides access to thousands of pre-trained models for tasks across NLP, computer vision, audio, and multimodal domains. Use this skill to load models, perform inference, and fine-tune on custom data.

Installation

Targets Transformers 5.18.0, verified against its released source on 2026-10-01. Native CPU checks use Python 3.11, Torch 2.14.1, Datasets 5.0.1, Accelerate 1.15.0, PEFT 0.21.2, and Hub 1.33.0. The Torch extra requires Torch >=2.5. Install in a dedicated environment:

uv venv --python 3.11 .venv-transformers
uv pip install --python .venv-transformers/bin/python "transformers[torch]==5.18.0" "torch==2.14.1" "huggingface-hub==1.33.0" "datasets==5.0.1" "accelerate==1.15.0" "peft==0.21.2"

Use .venv-transformers/Scripts/python.exe on Windows. Select an appropriate Torch build for the target hardware before installation. Hub 2.1.1 is newer, but Datasets 5.0.1 requires Hub <2; upgrading every package independently makes this training stack unsatisfiable. The separate esm SDK currently requires Transformers <5 and belongs in another environment.

Optional dependencies (install only for the selected workflow): Pillow 12.3.0 for images; torchvision matched to Torch and timm 1.0.30 for models that require them; librosa 1.0.0 and soundfile 0.14.0 for audio preprocessing (librosa requires Python >=3.12); FFmpeg for encoded audio file inputs; pytesseract plus Tesseract for OCR document pipelines; bitsandbytes 0.50.2 for supported quantization backends. See model loading before choosing precision or quantization.

Verification used tiny random models, synthetic input, and local save/reload only. Hub pretrained examples throughout this skill are illustrative: public checkpoint metadata and configurations were reviewed, but no weights or datasets were downloaded and no hosted inference or uploads were run. Optional export/distributed/hardware paths are source-checked, not end-to-end tested. See review evidence.

Check your version:

import transformers
print(transformers.__version__)

Authentication

Many models on the Hugging Face Hub are gated or private. Authenticate before loading them.

Recommended: CLI login (uses $HF_TOKEN_PATH, defaulting to $HF_HOME/token, normally ~/.cache/huggingface/token):

hf auth login

Python:

from huggingface_hub import login
login()  # Interactive prompt; do not hardcode tokens in scripts

Servers / CI: set HF_TOKEN in the environment (never commit tokens to git or shell profiles):

export HF_TOKEN="..."  # Read token from a secret manager, not source code

Get tokens at: https://huggingface.co/settings/tokens

Security: Never paste tokens into notebooks, repos, or shared configs. Prefer hf auth login over exporting tokens in .bashrc or .zshrc.

Use the narrowest token scope that works: read for private or gated model downloads, write only for uploads. If a long-running environment should not send the stored token on every Hub request, set HF_HUB_DISABLE_IMPLICIT_TOKEN=1 and pass a token only where authentication is required.

Transformers v5

Transformers v5 is PyTorch-only (TensorFlow and JAX backends were removed). For upgrades from v4, see the v5 migration guide. Transformers 5.18.0 accepts Hub >=1.31,<3; preserve the tighter constraint of Datasets when training.

Gated or custom architectures: accept the model license on the Hub, then load with trust_remote_code=True only when required custom code has been reviewed; pin its full immutable commit with revision (and code_revision for a separate code repository). Gating and custom code are independent: a gated built-in architecture does not require remote code.

Cache location: set HF_HOME for all Hugging Face caches, or HF_HUB_CACHE just for Hub files. Use HF_HUB_OFFLINE=1 only after required model snapshots are already cached.

Quick Start

Use the Pipeline API for fast inference without manual configuration:

from transformers import pipeline

# Text generation (prefer max_new_tokens for causal LMs)
generator = pipeline("text-generation", model="Qwen/Qwen2.5-1.5B")
result = generator("The future of AI is", max_new_tokens=50)

# Text classification
classifier = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
result = classifier("This movie was excellent!")

# Generative question answering: verify responses against the supplied context.
qa = pipeline("text-generation", model="Qwen/Qwen2.5-0.5B-Instruct")
result = qa([{ "role": "user", "content": "Context: AI means artificial intelligence. What does AI mean?" }], max_new_tokens=32, do_sample=False)

Core Capabilities

1. Pipelines for Quick Inference

Use for simple, optimized inference across many tasks. Supports text generation, classification, NER, image classification, object detection, audio classification, and more. In v5, question-answering, summarization, translation*, text2text-generation, image-to-text, and visual-question-answering pipelines are removed. Use direct task models when exact extractive/seq2seq semantics are needed; generative text/VLM pipelines are different tasks, not equivalent replacements.

When to use: Quick prototyping, simple inference tasks, no custom preprocessing needed.

See references/pipelines.md for comprehensive task coverage and optimization.

2. Model Loading and Management

Load pre-trained models with fine-grained control over configuration, device placement, and precision.

When to use: Custom model initialization, advanced device management, model inspection.

See references/models.md for loading patterns and best practices.

3. Text Generation

Generate text with LLMs using various decoding strategies (greedy, beam search, sampling) and control parameters (temperature, top-k, top-p).

When to use: Creative text generation, code generation, conversational AI, text completion.

For chat or instruction-tuned checkpoints, format messages with that checkpoint's tokenizer.apply_chat_template rather than hand-written role delimiters. Prefer tokenize=True; if formatting with tokenize=False and tokenizing afterward, set add_special_tokens=False to avoid duplicated BOS/EOS tokens. Use add_generation_prompt=True to start a new assistant reply, and preserve the same template when preparing fine-tuning data.

See references/generation.md for generation strategies and parameters.

4. Training and Fine-Tuning

Fine-tune pre-trained models on custom datasets using the Trainer API with automatic mixed precision, distributed training, and logging.

When to use: Task-specific model adaptation, domain adaptation, improving model performance.

See references/training.md for training workflows and best practices.

5. Tokenization

Convert text to tokens and token IDs for model input, with padding, truncation, and special token handling.

When to use: Custom preprocessing pipelines, understanding model inputs, batch processing.

See references/tokenizers.md for tokenization details.

Common Patterns

Pattern 1: Simple Inference

For straightforward tasks, use pipelines:

pipe = pipeline("task-name", model="model-id")
output = pipe(input_data)
Pattern 2: Custom Model Usage

For advanced control, load model and tokenizer separately:

from transformers import AutoModelForCausalLM, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("model-id")
model = AutoModelForCausalLM.from_pretrained("model-id", device_map="auto")

inputs = tokenizer("text", return_tensors="pt").to(model.device)
outputs = model.generate(**inputs, max_new_tokens=100)
result = tokenizer.decode(outputs[0])
Pattern 3: Fine-Tuning

For task adaptation, use Trainer:

from transformers import Trainer, TrainingArguments

training_args = TrainingArguments(
    output_dir="./results",
    num_train_epochs=3,
    per_device_train_batch_size=8,
    report_to="none",
)

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=train_dataset,
    processing_class=tokenizer,
)

trainer.train()

Research validation

Record package versions, checkpoint and dataset revisions, label order, preprocessing, split units, seeds, and generation settings. Split by patient, subject, document family, or time when observations are dependent; fit preprocessing and tune hyperparameters on training/validation data only. Report truncation and excluded records. A softmax score is not calibrated certainty, and decoding choices do not establish factual accuracy. Compare against held-out baselines and inspect failures before scientific use. Test adapters such as SHAP against the actual output shape/class order; their compatibility is not established by Transformers alone.

Reference Documentation

For detailed information on specific components:

  • Pipelines: references/pipelines.md - All supported tasks and optimization

  • Models: references/models.md - Loading, saving, and configuration

  • Generation: references/generation.md - Text generation strategies and parameters

  • Training: references/training.md - Fine-tuning with Trainer API

  • Tokenizers: references/tokenizers.md - Tokenization and preprocessing

Citing Scientific Agent Skills

This skill is part of Scientific Agent Skills by K-Dense. If it materially contributed to a manuscript, report, presentation, or code release, add the paper to the references or software section and tell the user you did so:

Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065. https://doi.org/10.48550/arXiv.2609.00065

Always cite the current version. The DOI and https://arxiv.org/abs/2609.00065 resolve to the latest arXiv version, so never append a version suffix such as v1. When network access is available, fetch https://arxiv.org/abs/2609.00065 (or http://export.arxiv.org/api/query?id_list=2609.00065) before writing the reference and take the author list, year, and version from that record. If the record lists a journal reference or publisher DOI, cite the published version instead.

Files

references/generation.md

Text Generation

Targets Transformers 5.18.0. Hub examples are illustrative; greedy, sampling, beam search, chat dictionaries, streaming, and static cache are tested with tiny local models. See review evidence.

Overview

Generate text with language models using the generate() method. Control output quality and style through generation strategies and parameters.

For quick prototyping, the Pipeline API wraps tokenization and generate(); use model.generate() directly when you need custom preprocessing or decoding control.

Basic Generation

from transformers import AutoModelForCausalLM, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")

# Tokenize input
inputs = tokenizer("Once upon a time", return_tensors="pt").to(model.device)

# Generate
outputs = model.generate(**inputs, max_new_tokens=50)

# Decode
text = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(text)

Generation Strategies

Greedy Decoding

Select highest probability token at each step (deterministic):

outputs = model.generate(
    **inputs,
    max_new_tokens=50,
    do_sample=False,  # Explicitly override any checkpoint sampling default
    num_beams=1
)

Use for: A non-sampling baseline. Greedy decoding does not make content factual, and exact reproducibility also depends on kernels, hardware, versions, and seeds.

Sampling

Randomly sample from probability distribution:

outputs = model.generate(
    **inputs,
    max_new_tokens=50,
    do_sample=True,
    temperature=0.7,
    top_k=50,
    top_p=0.95
)

Use for: Creative writing, diverse outputs, open-ended generation.

Explore multiple hypotheses in parallel:

outputs = model.generate(
    **inputs,
    max_new_tokens=50,
    num_beams=5,
    do_sample=False,
    early_stopping=True
)

Use for: Comparing candidate seq2seq translations or summaries. More beams do not guarantee better factuality or task quality.

Former built-in decoding strategies

Contrastive and constrained beam search moved to Hub custom-generation repositories. Legacy penalty_alpha / force_words_ids settings are not a self-contained offline implementation. Prefer the built-in greedy/sampling/beam paths unless you intentionally review the external implementation and dependencies, pin its code revision, and authorize custom code. See the current generation strategy guide; this skill does not execute Hub custom-generation code.

Key Parameters

Length Control

max_new_tokens: Maximum tokens to generate

max_new_tokens=100  # Generate up to 100 new tokens

max_length: Total decoder sequence length (prompt + output for decoder-only models; decoder-side length for encoder-decoder models). max_new_tokens takes precedence.

max_length=512  # Total sequence length

min_new_tokens: Minimum tokens to generate

min_new_tokens=50  # Force at least 50 tokens

min_length: Minimum total length

min_length=100
Temperature

Controls randomness (only with sampling):

temperature=1.0   # Default, balanced
temperature=0.7   # More focused, less random
temperature=1.5   # More creative, more random

Lower temperature → more deterministic Higher temperature → more random

Top-K Sampling

Consider only top K most likely tokens:

do_sample=True
top_k=50  # Sample from top 50 tokens

Common values: 40-100 for balanced output, 10-20 for focused output.

Top-P (Nucleus) Sampling

Consider tokens with cumulative probability ≥ P:

do_sample=True
top_p=0.95  # Sample from smallest set with 95% cumulative probability

Common values: 0.9-0.95 for balanced, 0.7-0.85 for focused.

Repetition Penalty

Discourage repetition:

repetition_penalty=1.2  # Penalize repeated tokens

Values: 1.0 = no penalty, 1.2-1.5 = moderate, 2.0+ = strong penalty.

Beam Search Parameters

num_beams: Number of beams

num_beams=5  # Keep 5 hypotheses

early_stopping: Stop when num_beams sentences are finished

early_stopping=True

no_repeat_ngram_size: Prevent n-gram repetition

no_repeat_ngram_size=3  # Don't repeat any 3-gram
Output Control

num_return_sequences: Generate multiple outputs

outputs = model.generate(
    **inputs,
    max_new_tokens=50,
    num_beams=5,
    do_sample=False,
    num_return_sequences=3  # Must not exceed num_beams here; uniqueness is not guaranteed
)

pad_token_id: Specify padding token

pad_token_id=tokenizer.eos_token_id

eos_token_id: Stop generation at specific token

eos_token_id=tokenizer.eos_token_id

Advanced Features

Batch Generation

Generate for multiple prompts:

prompts = ["Hello, my name is", "Once upon a time"]
# Decoder-only batch generation uses left padding; this is not a training rule.
tokenizer.padding_side = "left"
if tokenizer.pad_token is None:
    tokenizer.pad_token = tokenizer.eos_token
inputs = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device)

outputs = model.generate(**inputs, max_new_tokens=50, pad_token_id=tokenizer.pad_token_id)

for i, output in enumerate(outputs):
    text = tokenizer.decode(output[inputs["input_ids"].shape[1]:], skip_special_tokens=True)
    print(f"Prompt {i}: {text}\n")
Streaming Generation

TextStreamer writes decoded chunks synchronously:

from transformers import TextStreamer

streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
outputs = model.generate(**inputs, streamer=streamer, max_new_tokens=32, num_beams=1)

For UI iteration, TextIteratorStreamer(tokenizer, timeout=30.0, skip_prompt=True) is consumed concurrently with generate() in a worker thread. A timeout raises queue.Empty; capture and propagate the worker exception, join/clean up the worker, and do not treat timeout as a completed answer. Streamers do not support beam search. Chunk boundaries are not guaranteed to equal token boundaries.

Guidance and Control

Prevent bad words:

bad_words = ["offensive", "inappropriate"]
bad_words_ids = [tokenizer.encode(word, add_special_tokens=False) for word in bad_words]

outputs = model.generate(
    **inputs,
    bad_words_ids=bad_words_ids
)
Generation Config

Save and reuse generation parameters:

from transformers import GenerationConfig

# Create config
generation_config = GenerationConfig(
    max_new_tokens=100,
    temperature=0.7,
    top_k=50,
    top_p=0.95,
    do_sample=True
)

# Save
generation_config.save_pretrained("./my_generation_config")

# Load and use
generation_config = GenerationConfig.from_pretrained("./my_generation_config")
outputs = model.generate(**inputs, generation_config=generation_config)

Model-Specific Generation

Chat Models

Use a checkpoint with a saved chat template (plain GPT-2 does not provide one). In v5 apply_chat_template(..., tokenize=True) returns BatchEncoding; unpack it and keep its attention mask:

messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "What is the capital of France?"}
]

inputs = tokenizer.apply_chat_template(
    messages,
    tokenize=True,
    add_generation_prompt=True,
    return_tensors="pt"
).to(model.device)

outputs = model.generate(**inputs, max_new_tokens=100)
response = tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True)
Encoder-Decoder Models

For T5, BART, etc.:

from transformers import AutoModelForSeq2SeqLM, AutoTokenizer

model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-small")
tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")

# T5 uses task prefixes
input_text = "translate English to French: Hello, how are you?"
inputs = tokenizer(input_text, return_tensors="pt").to(model.device)

outputs = model.generate(**inputs, max_new_tokens=50)
translation = tokenizer.decode(outputs[0], skip_special_tokens=True)

Optimization

Caching

Enable KV cache for faster generation:

outputs = model.generate(
    **inputs,
    max_new_tokens=100,
    use_cache=True  # Default, faster generation
)
Static Cache

For a supported architecture, allocate capacity for the full decoder sequence. Cache memory is allocated lazily; old max_batch_size and device kwargs are not required:

from transformers import StaticCache

cache = StaticCache(config=model.config, max_cache_len=inputs["input_ids"].shape[1] + 100)

outputs = model.generate(
    **inputs,
    max_new_tokens=100,
    past_key_values=cache
)
Attention Implementation

Use Flash Attention for speed:

model = AutoModelForCausalLM.from_pretrained(
    "model-id",
    attn_implementation="flash_attention_2"
)

Generation Recipes

Creative Writing
outputs = model.generate(
    **inputs,
    max_new_tokens=200,
    do_sample=True,
    temperature=0.8,
    top_k=50,
    top_p=0.95,
    repetition_penalty=1.2
)
Non-sampling Baseline
outputs = model.generate(
    **inputs,
    max_new_tokens=100,
    do_sample=False,  # Greedy
    repetition_penalty=1.1
)
Diverse Outputs
outputs = model.generate(
    **inputs,
    max_new_tokens=100,
    num_beams=5,
    num_return_sequences=5,
    temperature=1.5,
    do_sample=True
)
Long-Form Generation

Check prompt length plus token budget against the model context window; larger output budgets consume cache memory.

outputs = model.generate(
    **inputs,
    max_new_tokens=1000,
    do_sample=True,
    temperature=0.8,
    top_p=0.95,
    repetition_penalty=1.2
)
Translation/Summarization
outputs = model.generate(
    **inputs,
    max_new_tokens=100,
    num_beams=5,
    do_sample=False,
    early_stopping=True,
    no_repeat_ngram_size=3
)

Common Issues

Repetitive output:

  • Increase repetition_penalty (1.2-1.5)

  • Use no_repeat_ngram_size (2-3)

  • Inspect the prompt/template and repeated-token distribution

  • Lower temperature

Poor quality:

  • Use beam search (num_beams=5)

  • Lower temperature

  • Adjust top_k/top_p

Too deterministic:

  • Enable sampling (do_sample=True)

  • Increase temperature (0.7-1.0)

  • Adjust top_k/top_p

Slow generation:

  • Reduce batch size

  • Enable use_cache=True

  • Use Flash Attention

  • Reduce max_new_tokens

Best Practices

  1. Start with defaults: Then tune based on output

  2. Evaluate the strategy: Use held-out task metrics and check factual claims against evidence

  3. Set max_new_tokens: Avoid unnecessarily long generation

  4. Enable caching: For faster sequential generation

  5. Tune temperature: Most impactful parameter for sampling

  6. Use beam search carefully: More memory/compute; benchmark whether it improves task quality

  7. Test different seeds: For reproducibility with sampling

  8. Monitor memory: Large beams use significant memory

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Declares allowed tools, Needs network access, Needs Python

The author says: Requires Python 3.10+, PyTorch 2.5+, and transformers 5.18.0; optional librosa 1.0 requires Python 3.12+. Network access for Hub downloads. Gated or private Hub models need an HF token (`hf auth login` or `HF_TOKEN`).

Security

What our scanner noticed· Low risk

  • Instructions that use the network

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
K-Dense Inc.
Publisher
K-Dense (Community)
Source
K-Dense-AI/scientific-agent-skills · skills/transformers · commit a25cf9e
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE.md)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by K-Dense Inc. or K-Dense.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download transformers.zip