Skill Tracer
Skills › Scientific Agent Skills › transformers › models.md

models.md

361 lines · skills/transformers/references/models.md at 5f2bc03

Open on GitHub

Most marks come from matching words in the file, so treat them as pointers.

1# Model Loading and Management
2
3Targets Transformers 5.18.0. Hub/accelerator/export examples are illustrative; tiny local model APIs are exercised by `tests/transformers/`. See [review evidence](review.md).
4

Model Loading and Management

Targets Transformers 5.18.0. Hub/accelerator/export examples are illustrative; tiny local model APIs are exercised by tests/transformers/. See review evidence.

Raw lines 1 to 4
5## Overview
6
7The transformers library provides flexible model loading with automatic architecture detection, device management, and configuration control.
8

Overview

The transformers library provides flexible model loading with automatic architecture detection, device management, and configuration control.

Raw lines 5 to 8
9## Loading Models

Loading Models

Raw lines 9 to 10
11### AutoModel Classes
13Use AutoModel classes for automatic architecture selection:
15```python
16from transformers import AutoModel, AutoModelForSequenceClassification, AutoModelForCausalLM
18# Base model (no task head)
19model = AutoModel.from_pretrained("google-bert/bert-base-uncased")
21# Sequence classification
22model = AutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased")
24# Causal language modeling (GPT-style)
25model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
27# Masked language modeling (BERT-style)
28from transformers import AutoModelForMaskedLM
29model = AutoModelForMaskedLM.from_pretrained("google-bert/bert-base-uncased")
31# Sequence-to-sequence (T5-style)
32from transformers import AutoModelForSeq2SeqLM
33model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-small")
34```

AutoModel Classes

Use AutoModel classes for automatic architecture selection:

from transformers import AutoModel, AutoModelForSequenceClassification, AutoModelForCausalLM

# Base model (no task head)
model = AutoModel.from_pretrained("google-bert/bert-base-uncased")

# Sequence classification
model = AutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased")

# Causal language modeling (GPT-style)
model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")

# Masked language modeling (BERT-style)
from transformers import AutoModelForMaskedLM
model = AutoModelForMaskedLM.from_pretrained("google-bert/bert-base-uncased")

# Sequence-to-sequence (T5-style)
from transformers import AutoModelForSeq2SeqLM
model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-small")
Raw lines 11 to 35
36### Common AutoModel Classes
38**NLP Tasks:**
39- `AutoModelForSequenceClassification`: Text classification, sentiment analysis
40- `AutoModelForTokenClassification`: NER, POS tagging
41- `AutoModelForQuestionAnswering`: Extractive QA
42- `AutoModelForCausalLM`: Text generation (GPT, Llama)
43- `AutoModelForMaskedLM`: Masked language modeling (BERT)
44- `AutoModelForSeq2SeqLM`: Translation, summarization (T5, BART)
46**Vision Tasks:**
47- `AutoModelForImageClassification`: Image classification
48- `AutoModelForObjectDetection`: Object detection
49- `AutoModelForImageSegmentation`: Image segmentation
51**Audio Tasks:**
52- `AutoModelForAudioClassification`: Audio classification
53- `AutoModelForSpeechSeq2Seq`: Speech recognition
55**Multimodal:**
56- `AutoModelForImageTextToText`: Generative image captioning and visual chat, paired with `AutoProcessor`
57- `AutoModelForVisualQuestionAnswering`: Architecture-specific direct VQA models

Common AutoModel Classes

NLP Tasks:

  • AutoModelForSequenceClassification: Text classification, sentiment analysis
  • AutoModelForTokenClassification: NER, POS tagging
  • AutoModelForQuestionAnswering: Extractive QA
  • AutoModelForCausalLM: Text generation (GPT, Llama)
  • AutoModelForMaskedLM: Masked language modeling (BERT)
  • AutoModelForSeq2SeqLM: Translation, summarization (T5, BART)

Vision Tasks:

  • AutoModelForImageClassification: Image classification
  • AutoModelForObjectDetection: Object detection
  • AutoModelForImageSegmentation: Image segmentation

Audio Tasks:

  • AutoModelForAudioClassification: Audio classification
  • AutoModelForSpeechSeq2Seq: Speech recognition

Multimodal:

  • AutoModelForImageTextToText: Generative image captioning and visual chat, paired with AutoProcessor
  • AutoModelForVisualQuestionAnswering: Architecture-specific direct VQA models
Raw lines 36 to 58
59## Loading Parameters

Loading Parameters

Raw lines 59 to 60
61### Basic Parameters
63**pretrained_model_name_or_path**: Model identifier or local path
64```python
65model = AutoModel.from_pretrained("google-bert/bert-base-uncased") # From Hub
66model = AutoModel.from_pretrained("./local/model/path") # From disk
67```
69**num_labels**: Number of output labels for classification
70```python
71model = AutoModelForSequenceClassification.from_pretrained(
72 "google-bert/bert-base-uncased",
73 num_labels=3
75```
77**cache_dir**: Custom cache location
78```python
79model = AutoModel.from_pretrained("model-id", cache_dir="./my_cache")
80```

Basic Parameters

pretrained_model_name_or_path: Model identifier or local path

model = AutoModel.from_pretrained("google-bert/bert-base-uncased")  # From Hub
model = AutoModel.from_pretrained("./local/model/path")  # From disk

num_labels: Number of output labels for classification

model = AutoModelForSequenceClassification.from_pretrained(
    "google-bert/bert-base-uncased",
    num_labels=3
)

cache_dir: Custom cache location

model = AutoModel.from_pretrained("model-id", cache_dir="./my_cache")
Raw lines 61 to 81
82### Device Management
84**device_map**: Automatic device allocation for large models
85```python
86# Automatically distribute across GPUs and CPU
87model = AutoModelForCausalLM.from_pretrained(
88 "Qwen/Qwen2.5-1.5B",
89 device_map="auto"
92# Accelerate device maps are for inference, not distributed Trainer training.
93# Sequential placement
94model = AutoModelForCausalLM.from_pretrained(
95 "model-id",
96 device_map="sequential"
99# A complete one-device map; split maps must name real model modules and cover all weights.
100model = AutoModel.from_pretrained("model-id", device_map={"": "cpu"})
101```
103Manual device placement:
104```python
105import torch
106model = AutoModel.from_pretrained("model-id")
107model.to("cuda:0") # Move to GPU 0
108model.to(torch.device("cuda" if torch.cuda.is_available() else "cpu"))
109```

Device Management

device_map: Automatic device allocation for large models

# Automatically distribute across GPUs and CPU
model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen2.5-1.5B",
    device_map="auto"
)

# Accelerate device maps are for inference, not distributed Trainer training.
# Sequential placement
model = AutoModelForCausalLM.from_pretrained(
    "model-id",
    device_map="sequential"
)

# A complete one-device map; split maps must name real model modules and cover all weights.
model = AutoModel.from_pretrained("model-id", device_map={"": "cpu"})

Manual device placement:

import torch
model = AutoModel.from_pretrained("model-id")
model.to("cuda:0")  # Move to GPU 0
model.to(torch.device("cuda" if torch.cuda.is_available() else "cpu"))
Raw lines 82 to 110
111### Precision Control
113**dtype**: Set model precision (preferred in v5; `torch_dtype` still works but is deprecated)
114```python
115import torch
117# Float16 (half precision)
118model = AutoModel.from_pretrained("model-id", dtype=torch.float16)
120# BFloat16 (better range than float16)
121model = AutoModel.from_pretrained("model-id", dtype=torch.bfloat16)
123# Auto (use original dtype)
124model = AutoModel.from_pretrained("model-id", dtype="auto")
125```

Precision Control

dtype: Set model precision (preferred in v5; torch_dtype still works but is deprecated)

import torch

# Float16 (half precision)
model = AutoModel.from_pretrained("model-id", dtype=torch.float16)

# BFloat16 (better range than float16)
model = AutoModel.from_pretrained("model-id", dtype=torch.bfloat16)

# Auto (use original dtype)
model = AutoModel.from_pretrained("model-id", dtype="auto")
Raw lines 111 to 126
127### Attention Implementation
129**attn_implementation**: Choose attention mechanism
130```python
131# SDPA (supported architectures; backend/shape determine speed)
132model = AutoModel.from_pretrained("model-id", attn_implementation="sdpa")
134# Flash Attention 2 (requires flash-attn package)
135model = AutoModel.from_pretrained("model-id", attn_implementation="flash_attention_2")
137# Eager (explicit reference implementation; SDPA is often selected by default)
138model = AutoModel.from_pretrained("model-id", attn_implementation="eager")
139```

Attention Implementation

attn_implementation: Choose attention mechanism

# SDPA (supported architectures; backend/shape determine speed)
model = AutoModel.from_pretrained("model-id", attn_implementation="sdpa")

# Flash Attention 2 (requires flash-attn package)
model = AutoModel.from_pretrained("model-id", attn_implementation="flash_attention_2")

# Eager (explicit reference implementation; SDPA is often selected by default)
model = AutoModel.from_pretrained("model-id", attn_implementation="eager")
Raw lines 127 to 140
141### Memory Optimization
143Transformers v5 manages efficient loading internally; legacy `low_cpu_mem_usage` is ignored. `device_map="auto"` can dispatch to accelerators/CPU/disk according to available memory; supply `max_memory` and `offload_folder` when needed, inspect `model.hf_device_map`, and keep inputs on the entry device. Do not call `.to(...)` on an already dispatched model.
145**BitsAndBytesConfig**: 8-bit and 4-bit quantization (requires optional `bitsandbytes`; `uv pip install bitsandbytes==0.50.2`)
146```python
147from transformers import BitsAndBytesConfig
149quantization_config = BitsAndBytesConfig(load_in_8bit=True)
151model = AutoModelForCausalLM.from_pretrained(
152 "model-id",
153 device_map="auto",
154 quantization_config=quantization_config
156```
158Bitsandbytes is not CUDA-only: release 0.50.2 supplies Linux, Windows, and macOS ARM64 wheels, with backend/feature-specific support. CPU quantization was smoke-tested on this review host; CUDA, ROCm, XPU, Gaudi, and MPS paths were not. Check the [release installation matrix](https://huggingface.co/docs/bitsandbytes/v0.50.2/installation). Quantized inference does not itself train adapters.
160**4-bit QLoRA-style loading**: use `BitsAndBytesConfig` instead of direct `load_in_4bit` arguments
161```python
162import torch
163from transformers import BitsAndBytesConfig
165quantization_config = BitsAndBytesConfig(
166 load_in_4bit=True,
167 bnb_4bit_compute_dtype=torch.bfloat16,
168 bnb_4bit_quant_type="nf4"
171model = AutoModelForCausalLM.from_pretrained(
172 "model-id",
173 quantization_config=quantization_config,
174 device_map="auto"
176```

Memory Optimization

Transformers v5 manages efficient loading internally; legacy low_cpu_mem_usage is ignored. device_map="auto" can dispatch to accelerators/CPU/disk according to available memory; supply max_memory and offload_folder when needed, inspect model.hf_device_map, and keep inputs on the entry device. Do not call .to(...) on an already dispatched model.

BitsAndBytesConfig: 8-bit and 4-bit quantization (requires optional bitsandbytes; uv pip install bitsandbytes==0.50.2)

from transformers import BitsAndBytesConfig

quantization_config = BitsAndBytesConfig(load_in_8bit=True)

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

Bitsandbytes is not CUDA-only: release 0.50.2 supplies Linux, Windows, and macOS ARM64 wheels, with backend/feature-specific support. CPU quantization was smoke-tested on this review host; CUDA, ROCm, XPU, Gaudi, and MPS paths were not. Check the release installation matrix. Quantized inference does not itself train adapters.

4-bit QLoRA-style loading: use BitsAndBytesConfig instead of direct load_in_4bit arguments

import torch
from transformers import BitsAndBytesConfig

quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.bfloat16,
    bnb_4bit_quant_type="nf4"
)

model = AutoModelForCausalLM.from_pretrained(
    "model-id",
    quantization_config=quantization_config,
    device_map="auto"
)
Raw lines 141 to 177
Starts an agent dispatch :143
Starts an agent dispatched :143
178## Model Configuration

Model Configuration

Raw lines 178 to 179
180### Loading with Custom Config
182```python
183from transformers import AutoConfig, AutoModel
185# Load and modify config
186config = AutoConfig.from_pretrained("google-bert/bert-base-uncased")
187config.hidden_dropout_prob = 0.2
188config.attention_probs_dropout_prob = 0.2
190# Initialize model with custom config
191model = AutoModel.from_pretrained("google-bert/bert-base-uncased", config=config)
192```

Loading with Custom Config

from transformers import AutoConfig, AutoModel

# Load and modify config
config = AutoConfig.from_pretrained("google-bert/bert-base-uncased")
config.hidden_dropout_prob = 0.2
config.attention_probs_dropout_prob = 0.2

# Initialize model with custom config
model = AutoModel.from_pretrained("google-bert/bert-base-uncased", config=config)
Raw lines 180 to 193
194### Initializing from Config Only
196```python
197config = AutoConfig.from_pretrained("openai-community/gpt2")
198model = AutoModelForCausalLM.from_config(config) # Random weights
199```

Initializing from Config Only

config = AutoConfig.from_pretrained("openai-community/gpt2")
model = AutoModelForCausalLM.from_config(config)  # Random weights
Raw lines 194 to 200
201## Model Modes
203### Training vs Evaluation Mode
205Models load in evaluation mode by default:
207```python
208model = AutoModel.from_pretrained("model-id")
209print(model.training) # False
211# Switch to training mode
212model.train(True)
214# Switch back to evaluation mode (equivalent to eval mode on nn.Module)
215model.train(False)
216```
218Evaluation mode disables dropout and uses stored batch norm statistics where those layers exist. It does not disable autograd; use `torch.inference_mode()` for inference. `model.train(False)` is equivalent to `model.eval()` in PyTorch.

Training vs Evaluation Mode

Models load in evaluation mode by default:

model = AutoModel.from_pretrained("model-id")
print(model.training)  # False

# Switch to training mode
model.train(True)

# Switch back to evaluation mode (equivalent to eval mode on nn.Module)
model.train(False)

Evaluation mode disables dropout and uses stored batch norm statistics where those layers exist. It does not disable autograd; use torch.inference_mode() for inference. model.train(False) is equivalent to model.eval() in PyTorch.

Raw lines 203 to 219
220## Saving Models
222### Save Locally
224```python
225model.save_pretrained("./my_model")
226```
228This creates:
229- `config.json`: Model configuration
230- `model.safetensors` (or shards plus an index): Model weights
232Save the matching tokenizer/processor too. v5 saves safetensors; `safe_serialization` is no longer a public control. Legacy pickle-based loading is a separate compatibility/security consideration.

Save Locally

model.save_pretrained("./my_model")

This creates:

  • config.json: Model configuration
  • model.safetensors (or shards plus an index): Model weights

Save the matching tokenizer/processor too. v5 saves safetensors; safe_serialization is no longer a public control. Legacy pickle-based loading is a separate compatibility/security consideration.

Raw lines 222 to 233
234### Save to Hugging Face Hub
236```python
237model.push_to_hub("username/model-name")
239# With custom commit message
240model.push_to_hub("username/model-name", commit_message="Update model")
242# Private repository
243model.push_to_hub("username/model-name", private=True)
244```

Save to Hugging Face Hub

model.push_to_hub("username/model-name")

# With custom commit message
model.push_to_hub("username/model-name", commit_message="Update model")

# Private repository
model.push_to_hub("username/model-name", private=True)
Raw lines 234 to 245
246## Model Inspection

Model Inspection

Raw lines 246 to 247
248### Parameter Count
250```python
251# Total parameters
252total_params = model.num_parameters()
254# Trainable parameters only
255trainable_params = model.num_parameters(only_trainable=True)
257print(f"Total: {total_params:,}")
258print(f"Trainable: {trainable_params:,}")
259```

Parameter Count

# Total parameters
total_params = model.num_parameters()

# Trainable parameters only
trainable_params = model.num_parameters(only_trainable=True)

print(f"Total: {total_params:,}")
print(f"Trainable: {trainable_params:,}")
Raw lines 248 to 260
261### Memory Footprint
263```python
264memory_bytes = model.get_memory_footprint()
265memory_mb = memory_bytes / 1024**2
266print(f"Memory: {memory_mb:.2f} MB")
267```

Memory Footprint

memory_bytes = model.get_memory_footprint()
memory_mb = memory_bytes / 1024**2
print(f"Memory: {memory_mb:.2f} MB")
Raw lines 261 to 268
269### Model Architecture
271```python
272print(model) # Print full architecture
274# Access specific components
275print(model.config)
276print(model.base_model)
277```

Model Architecture

print(model)  # Print full architecture

# Access specific components
print(model.config)
print(model.base_model)
Raw lines 269 to 278
279## Forward Pass
281Basic inference:
283```python
284from transformers import AutoTokenizer
286tokenizer = AutoTokenizer.from_pretrained("model-id")
287model = AutoModelForSequenceClassification.from_pretrained("model-id")
289import torch
290inputs = tokenizer("Sample text", return_tensors="pt").to(model.device)
291model.eval()
292with torch.inference_mode():
293 outputs = model(**inputs)
295logits = outputs.logits
296predictions = logits.argmax(dim=-1)
297```

Forward Pass

Basic inference:

from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("model-id")
model = AutoModelForSequenceClassification.from_pretrained("model-id")

import torch
inputs = tokenizer("Sample text", return_tensors="pt").to(model.device)
model.eval()
with torch.inference_mode():
    outputs = model(**inputs)

logits = outputs.logits
predictions = logits.argmax(dim=-1)
Raw lines 279 to 298
299## Model Formats
301### SafeTensors vs PyTorch
303SafeTensors is faster and safer:
305```python
306# Save as safetensors (recommended)
307model.save_pretrained("./model")
309# Reload this local safetensors export
310model = AutoModel.from_pretrained("./model")
311```

SafeTensors vs PyTorch

SafeTensors is faster and safer:

# Save as safetensors (recommended)
model.save_pretrained("./model")

# Reload this local safetensors export
model = AutoModel.from_pretrained("./model")
Raw lines 301 to 312
313### ONNX Export
315The legacy `transformers.onnx` exporter is removed. Use the separate [Optimum ONNX exporter](https://huggingface.co/docs/optimum-onnx/onnx/usage_guides/export_a_model) in its own compatible environment. Illustrative CLI (export/runtime not executed in this review):
317```bash
318uv pip install "optimum-onnx[onnxruntime]"
319optimum-cli export onnx --model distilbert/distilbert-base-uncased-finetuned-sst-2-english --task text-classification ./onnx-model
320```
322Check that the chosen architecture/opset is supported and compare ONNX outputs with the original model on representative inputs; successful conversion alone does not validate numerical equivalence.

ONNX Export

The legacy transformers.onnx exporter is removed. Use the separate Optimum ONNX exporter in its own compatible environment. Illustrative CLI (export/runtime not executed in this review):

uv pip install "optimum-onnx[onnxruntime]"
optimum-cli export onnx --model distilbert/distilbert-base-uncased-finetuned-sst-2-english --task text-classification ./onnx-model

Check that the chosen architecture/opset is supported and compare ONNX outputs with the original model on representative inputs; successful conversion alone does not validate numerical equivalence.

Raw lines 313 to 323
324## Best Practices
3261. **Use AutoModel classes**: Automatic architecture detection
3272. **Specify `dtype` explicitly**: Control precision and memory (avoid deprecated `torch_dtype` in new code)
3283. **Use device_map="auto"**: For large models
3294. **Inspect dispatch**: Bound `max_memory` and disk offload; do not use inference dispatch as a training strategy
3305. **Use safetensors format**: Faster and safer serialization
3316. **Check model.training**: Ensure correct mode for task
3327. **Consider quantization**: For deployment on resource-constrained devices
3338. **Cache models locally**: Set `HF_HOME` (Hub cache at `$HF_HOME/hub`)

Best Practices

  1. Use AutoModel classes: Automatic architecture detection
  2. **Specify dtype explicitly**: Control precision and memory (avoid deprecated torch_dtype in new code)
  3. Use device_map="auto": For large models
  4. Inspect dispatch: Bound max_memory and disk offload; do not use inference dispatch as a training strategy
  5. Use safetensors format: Faster and safer serialization
  6. Check model.training: Ensure correct mode for task
  7. Consider quantization: For deployment on resource-constrained devices
  8. Cache models locally: Set HF_HOME (Hub cache at $HF_HOME/hub)
Raw lines 324 to 334
Starts an agent dispatch :329
335## Common Issues
337**CUDA out of memory:**
338```python
339import torch
340from transformers import BitsAndBytesConfig
342# Use smaller precision
343model = AutoModel.from_pretrained("model-id", dtype=torch.float16)
345# Or use quantization
346quantization_config = BitsAndBytesConfig(load_in_8bit=True)
347model = AutoModel.from_pretrained("model-id", quantization_config=quantization_config)
349# Or use CPU
350model = AutoModel.from_pretrained("model-id", device_map="cpu")
351```
353**Slow loading:** Reuse an existing cached snapshot, inspect download/disk/dispatch costs, and avoid repeatedly initializing the model. `low_cpu_mem_usage` does not change v5 loading.
355**Model not found:**
356```python
357# Verify the exact repository ID on huggingface.co
358# Check authentication for private models
359from huggingface_hub import login
360login()
361```

Common Issues

CUDA out of memory:

import torch
from transformers import BitsAndBytesConfig

# Use smaller precision
model = AutoModel.from_pretrained("model-id", dtype=torch.float16)

# Or use quantization
quantization_config = BitsAndBytesConfig(load_in_8bit=True)
model = AutoModel.from_pretrained("model-id", quantization_config=quantization_config)

# Or use CPU
model = AutoModel.from_pretrained("model-id", device_map="cpu")

Slow loading: Reuse an existing cached snapshot, inspect download/disk/dispatch costs, and avoid repeatedly initializing the model. low_cpu_mem_usage does not change v5 loading.

Model not found:

# Verify the exact repository ID on huggingface.co
# Check authentication for private models
from huggingface_hub import login
login()
Raw lines 335 to 361
Starts an agent dispatch :353