匠人学院 JR Academy
Skip to article
Learning guide
Hugging Face Guide

Explore models, datasets, inference, and open-source AI workflows with Hugging Face.

2 chapters·4 guides·Access varies by chapter
Transformers Library
On this page

Transformers Library

Transformers provides common interfaces for tokenization, model loading, inference and training. A tokenizer produces model inputs, the model holds architecture/weights, and configuration describes model settings.

#Pipeline examples

python
from transformers import pipeline classifier = pipeline("sentiment-analysis") print(classifier("I enjoyed this course.")) generator = pipeline("text-generation", model="gpt2") print(generator("In this course, we will", max_new_tokens=20))

These examples download and run models; review the model/license, installed versions and hardware before execution.

#Auto classes for more control

python
import torch from transformers import AutoTokenizer, AutoModelForSequenceClassification checkpoint = "distilbert-base-uncased-finetuned-sst-2-english" tokenizer = AutoTokenizer.from_pretrained(checkpoint) model = AutoModelForSequenceClassification.from_pretrained(checkpoint) inputs = tokenizer( ["I enjoyed this course.", "I disliked it."], padding=True, truncation=True, return_tensors="pt", ) model.eval() with torch.no_grad(): probabilities = torch.softmax(model(**inputs).logits, dim=-1) print(probabilities)

#Match the task head

Use a suitable causal-language, masked-language, sequence-classification, token-classification or question-answering model class. A base checkpoint and a task-specific head are not interchangeable.

#Save and reload

python
tokenizer.save_pretrained("./my_saved_model") model.save_pretrained("./my_saved_model") tokenizer = AutoTokenizer.from_pretrained("./my_saved_model") model = AutoModelForSequenceClassification.from_pretrained("./my_saved_model")

#Training and optimization

Trainer/TrainingArguments can organize training with prepared train/evaluation datasets. Configure epochs, batch sizes and evaluation using the installed version's API; the source's parameter names may differ in newer releases.

Quantization, attention implementations and device mapping depend on compatible models, packages and hardware. Measure memory, latency and quality instead of treating every optimization as an automatic improvement. Framework support also depends on the specific model and library version.

Published by
JR Academy
Learning resources

Individual authors and reviewers are credited where recorded.

System Design

Core system design concepts and practical case studies

Learn the trade-offs and patterns that matter in technical interviews.

Open System Design →

Related Roadmaps

Done reading? Next steps