Runoob Tutorial ArchiveEnglish

Hugging Face Transformers

Hugging Face Transformers

Hugging Face Transformers is currently the most popular open-source NLP/AI library, providing thousands of pre-trained models covering almost all AI tasks such as text, image, audio, and multimodal.

Its core value is encapsulating complex model loading, inference, and training processes into a few lines of code.

Hugging Face Ecosystem Overview Hub 400k+ models 100k+ datasets Transformers Pre-trained model inference With fine-tuning framework Datasets Massive datasets Efficient loading and processing PEFT Parameter-efficient fine-tuning LoRA / QLoRA Accelerate Multi-GPU/TPU training Distributed acceleration Tokenizers High-performance tokenizer (Rust implementation) Evaluate Model evaluation metrics (BLEU/F1, etc.)

Supported task types

Task categories supported by Transformers NLP natural language processing Text classification (sentiment analysis) Named entity recognition (NER) Question answering system (QA) Text summarization generation Machine translation Text generation (dialogue) Fill-in-the-blank / language model CV computer vision Image classification Object detection Image segmentation Depth estimation Image generation Video classification Key point detection Audio & multimodal Speech recognition (ASR) Audio classification Text-to-speech (TTS) Image-text matching (VQA) Image caption generation Document QA (DOC QA) Zero-shot classification

Core principles of the Transformer architecture

Understanding the underlying architecture before using the library will help you know why certain hyperparameters are tuned the way they are.

Overall architecture: Encoder-Decoder

runoob cf 8ae6f a6fc 4a1b 8977 364df

Three major model families

Three major model families: architecture × use case × representative model. Encoder-only models Bidirectional attention, understands global context Suitable for: classification, NER, QA (understanding tasks) Representative: BERT, RoBERTa, ALBERT Chinese: BERT-wwm, MacBERT Feature: can see all inputs simultaneously Input -> [CLS] represents the whole sequence, [MASK] is used for pre-training Decoder-only models Causal attention (looks only left), autoregressive generation Suitable for: text generation, dialogue, code generation Representative: GPT series, LLaMA, Qwen Chinese: ChatGLM, Baichuan Feature: predict the next word word by word Input → predict the next word → concatenate and predict again → loop Encoder-Decoder models Sequence-to-sequence (Seq2Seq) tasks Suitable for: translation, summarization, QA generation Representative: T5, BART, mT5 Chinese: mT5, PEGASUS-Chinese Feature: encode input, decode to generate output Source sequence -> Encoder -> Decoder -> target sequence

Installation and environment configuration

Installation

Original prompt (Chinese, left untranslated)



# Basic installation

pip install transformers



# Full installation (including training dependencies)

pip install transformers[torch]       # PyTorch 后端(推荐)

pip install transformers[tf-cpu]      # TensorFlow 后端

pip install transformers[flax]        # JAX/Flax 后端



# Common supporting libraries

pip install datasets          # HuggingFace 数据集库

pip install evaluate          # 模型评估指标

pip install accelerate        # 多GPU/混合精度训练

pip install peft              # 参数高效微调(LoRA等)

pip install tokenizers        # 高性能分词器

pip install sentencepiece     # 部分模型(T5/LLaMA)需要



# Verify installation

python -c "import transformers; print(transformers.__version__)"

Environment variable configuration

Original prompt (Chinese, left untranslated)



# Set model cache directory (models are cached here after download, default ~/.cache/huggingface)

export HF_HOME=/data/huggingface_cache



# Domestic users: Use mirror site for faster download (hf-mirror.com recommended)

export HF_ENDPOINT=https://hf-mirror.com



# Offline mode (when network is unavailable, only use cached models)

export TRANSFORMERS_OFFLINE=1



# Disable progress bar (CI/CD environment)

export DISABLE_TQDM=1

Instance

Can also be set in code

import

os

os

.

environ

[

"HF_ENDPOINT"

]

=

"https://hf-mirror.com"

View the current cache directory

from

transformers.

utils

import

TRANSFORMERS_CACHE

print

(

TRANSFORMERS_CACHE

)


Pipeline: Running AI with Five Elements Code

Pipeline is the highest level of abstraction in Transformers, encapsulating model loading, preprocessing, inference, and postprocessing, allowing inference to be completed in just three to five lines of code.

Pipeline internal workflow Raw input Text / image Audio / and other data Preprocessing Tokenizer (tokenization) Convert to token IDs Padding/Truncation Model inference Forward propagation Output logits Or hidden-layer vector Post-processing Softmax/Argmax Decode token -> text Formatted output Result Label / score Generate text The pipeline automatically completes all steps; the user only needs to provide the raw input and receive formatted results.

Pipeline Quick Examples Collection

Example

from

transformers

import

pipeline

1. Sentiment Analysis (Text Classification)

classifier

=

pipeline

(

"sentiment-analysis"

)

result

=

classifier

(

"I love using Hugging Face Transformers!"

)

-> [{'label': 'POSITIVE', 'score': 0.9998}]

2. Text Generation

generator

=

pipeline

(

"text-generation"

,

model

=

"gpt2"

)

result

=

generator

(

"Once upon a time in a land far away,"

,

max_new_tokens

=

50

,

num_return_sequences

=

1

,

temperature

=

0.8

)

3. Fill in the blank (Masked Language Model)

unmasker

=

pipeline

(

"fill-mask"

,

model

=

"bert-base-uncased"

)

result

=

unmasker

(

"The capital of France is [MASK]."

)

-> [{'token_str': 'paris', 'score': 0.9823}, ...]

4. Named Entity Recognition (NER)

ner

=

pipeline

(

"ner"

,

aggregation_strategy

=

"simple"

)

result

=

ner

(

"My name is John and I work at Google in New York."

)

-> [{'entity_group': 'PER', 'word': 'John', 'score': 0.998}, ...]

5. Extractive Question Answering

qa

=

pipeline

(

"question-answering"

)

result

=

qa

(

question

=

"Who invented Python?"

,

context

=

"Python was created by Guido van Rossum in 1991."

)

-> {'answer': 'Guido van Rossum', 'score': 0.9887}

6. Text Summarization

summarizer

=

pipeline

(

"summarization"

,

model

=

"facebook/bart-large-cnn"

)

result

=

summarizer

(

article

,

max_length

=

60

,

min_length

=

20

)

7. Machine Translation

translator

=

pipeline

(

"translation"

,

model

=

"Helsinki-NLP/opus-mt-en-zh"

)

result

=

translator

(

"Hello, how are you today?"

)

-> [{'translation_text': 'Hello, how are you today?'}]

8. Zero-shot classification (no specialized training required)

zero_shot

=

pipeline

(

"zero-shot-classification"

)

result

=

zero_shot

(

"I love playing football"

,

candidate_labels

=

[

"sports"

,

"politics"

,

"technology"

]

)

-> {'labels': ['sports', ...], 'scores': [0.972, ...]}

Advanced Pipeline Configuration

Instance

import

torch

from

transformers

import

pipeline

Specify GPU

pipe

=

pipeline

(

"text-generation"

,

model

=

"gpt2"

,

device

=

0

)

Specify precision (save VRAM)

pipe

=

pipeline

(

"text-generation"

,

model

=

"meta-llama/Llama-2-7b-hf"

,

torch_dtype

=

torch.

float16

,

device_map

=

"auto"

)

Batch processing (increase throughput)

pipe

=

pipeline

(

"sentiment-analysis"

,

batch_size

=

32

)

results

=

pipe

(

large_text_list

)

   

Automatic batch inference

Large text chunk processing

asr

=

pipeline

(

"automatic-speech-recognition"

,

    model

=

"openai/whisper-large-v2"

,

chunk_length_s

=

30

,

stride_length_s

=

5

)

result

=

asr

(

"long_audio.wav"

,

return_timestamps

=

True

)


In-depth analysis of Tokenizer

Tokenizer is the first step in NLP: converting raw text into a numerical sequence that the model can understand.

Complete Tokenization Process

Complete Tokenization process: text -> model input Step 1 raw text: "Hello, I'm learning Transformers! It's great." Step 2 tokenize: ["Hello", ",", "I", "'m", "learning", "Transform", "##ers", "!", ...] WordPiece/BPE subword tokenization: rare words are split (Transformers -> Transform + ##ers) Step 3 add special tokens: ["[CLS]", "Hello", ",", "I", "'m", "learning", "Transform", "##ers", ... "[SEP]"] [CLS] classification token, [SEP] separator, [PAD] padding; special tokens differ across models. Step 4 convert to Token IDs: [101, 7592, 1010, 1045, 1005, 1049, 4083, 19081, 2121, ... 102] Each token is mapped to an integer index in the vocabulary and fed into the model's embedding layer.

Core Usage of Tokenizer

Example

from

transformers

import

AutoTokenizer

Load Tokenizer

tokenizer

=

AutoTokenizer.

from_pretrained

(

"bert-base-uncased"

)

Complete encoding in one step

encoding

=

tokenizer

(

   

"Hello, I'm learning Transformers!"

,

return_tensors

=

"pt"

,

       

Returns PyTorch tensor

padding

=

True

,

             

Pad to the longest sequence

truncation

=

True

,

           

Truncate when exceeding length

max_length

=

128

,

           

Maximum length

)

print

(

encoding.

keys

(

)

)

-> dict_keys(['input_ids', 'token_type_ids', 'attention_mask'])

print

(

encoding

[

"input_ids"

]

[

0

]

[

:

8

]

)

-> tensor([101, 7592, 1010, 1045, 1005, 1049, 4083, 19081])

print

(

encoding

[

"attention_mask"

]

[

0

]

[

:

8

]

)

-> tensor([1, 1, 1, 1, 1, 1, 1, 1]) # 1=real token, 0=padding

Decode (ID -> text)

decoded

=

tokenizer.

decode

(

encoding

[

"input_ids"

]

[

0

]

,

skip_special_tokens

=

True

)

print

(

decoded

)

 

-> "hello, i'm learning transformers!"

Batch encoding (automatic padding alignment)

texts

=

[

"Short."

,

"This is a much longer sentence for testing."

]

batch

=

tokenizer

(

texts

,

padding

=

True

,

truncation

=

True

,

return_tensors

=

"pt"

)

print

(

batch

[

"input_ids"

]

.

shape

)

 

-> torch.Size([2, 10])

Vocabulary information

print

(

f

"Vocabulary size: {tokenizer.vocab_size}"

)

     

-> 30522

print

(

f

"[CLS] ID: {tokenizer.cls_token_id}"

)

   

-> 101

print

(

f

"[SEP] ID: {tokenizer.sep_token_id}"

)

   

-> 102

print

(

f

"Max length: {tokenizer.model_max_length}"

)

 

-> 512

Comparison of common Tokenizer types

Comparison of three mainstream tokenization algorithms Algorithm Principle Example tokenization Representative models BPE Byte Pair Encoding Count high-frequency character pairs and merge Learn the optimal subword vocabulary "transformers" -> ["transform", "ers"] GPT / RoBERTa WordPiece Maximize language model probability ## prefix token subtoken "transformers" -> ["transform", "##ers"] BERT / DistilBERT SentencePiece Unigram / BPE variants Language-agnostic, process directly Raw bytes, leading marker at word start "transformers" -> ["_transform", "ers"] T5 / LLaMA / Qwen

Model loading and inference

AutoClass: Automatically select the correct model class

How AutoClass works: it automatically matches the correct model architecture. Model name "bert-base-uncased" Or local path AutoClass Read config.json Match architecture type AutoModel / AutoTokenizer / ... Automatically return the correct class BertForSequenceClassification GPT2LMHeadModel T5ForConditionalGeneration ... Common AutoClass cheat sheet: AutoTokenizer Automatic tokenizer AutoModel Base model (outputs hidden layer) AutoModelForSeqClass Text classification task AutoModelForCausalLM Text generation task

Instance

import

torch

from

transformers

import

AutoTokenizer

,

AutoModelForSequenceClassification

model_name

=

"bert-base-uncased"

tokenizer

=

AutoTokenizer.

from_pretrained

(

model_name

)

model

=

AutoModelForSequenceClassification.

from_pretrained

(

model_name

,

num_labels

=

2

,

torch_dtype

=

torch.

float16

,

device_map

=

"auto"

)

Manual inference complete process

text

=

"Transformers is an amazing library!"

1. Encoding

inputs

=

tokenizer

(

text

,

return_tensors

=

"pt"

,

truncation

=

True

,

max_length

=

512

)

inputs

=

{

k: v.

to

(

model.

device

)

for

k

,

v

in

inputs.

items

(

)

}

2. Forward Propagation

with

torch.

no_grad

(

)

:

outputs

=

model

(

**inputs

)

3. Parse output

logits

=

outputs.

logits

                     

shape: [1, 2]

probs

=

torch.

softmax

(

logits

,

dim

=

1

)

pred

=

torch.

argmax

(

probs

,

dim

=

1

)

.

item

(

)

id2label

=

model.

config

.

id2label

             

{0: 'LABEL_0', 1: 'LABEL_1'}

print

(

f

"Predicted class: {id2label[pred]}, Confidence: {probs[0][pred]:.4f}"

)

Extract sentence vector

Instance

from

transformers

import

AutoModel

,

AutoTokenizer

import

torch

model

=

AutoModel.

from_pretrained

(

"bert-base-uncased"

)

tokenizer

=

AutoTokenizer.

from_pretrained

(

"bert-base-uncased"

)

def

get_sentence_embedding

(

text:

str

)

torch.

Tensor

:

inputs

=

tokenizer

(

text

,

return_tensors

=

"pt"

,

max_length

=

512

,

truncation

=

True

)

   

with

torch.

no_grad

(

)

:

outputs

=

model

(

**inputs

)

   

Perform mean pooling on all tokens

token_embeddings

=

outputs.

last_hidden_state

         

[1, seq_len, 768]

attention_mask

=

inputs

[

"attention_mask"

]

.

unsqueeze

(

1

)

mean_embedding

=

(

token_embeddings * attention_mask

)

.

sum

(

1

)

/ attention_mask.

sum

(

1

)

   

return

mean_embedding

[1, 768]

vec

=

get_sentence_embedding

(

"Hello world"

)

print

(

vec.

shape

)

 

-> torch.Size([1, 768])


Ten Common Tasks Practical Implementation

Text Classification (Sentiment Analysis)

Instance

from

transformers

import

AutoTokenizer

,

AutoModelForSequenceClassification

import

torch

model_name

=

"cardiffnlp/twitter-roberta-base-sentiment-latest"

tokenizer

=

AutoTokenizer.

from_pretrained

(

model_name

)

model

=

AutoModelForSequenceClassification.

from_pretrained

(

model_name

)

def

predict_sentiment

(

texts

)

:

inputs

=

tokenizer

(

texts

,

return_tensors

=

"pt"

,

padding

=

True

,

truncation

=

True

,

max_length

=

512

)

   

with

torch.

no_grad

(

)

:

logits

=

model

(

**inputs

)

.

logits

    probs

=

torch.

softmax

(

logits

,

dim

=

1

)

results

=

[

]

   

for

i

,

t

in

enumerate

(

texts

)

:

pid

=

probs

[

i

]

.

argmax

(

)

.

item

(

)

results.

append

(

{

"text"

: t

,

"label"

: model.

config

.

id2label

[

pid

]

,

                         

"score"

:

round

(

probs

[

i

]

[

pid

]

.

item

(

)

,

4

)

}

)

   

return

results

print

(

predict_sentiment

(

[

"I love this!"

,

"This is terrible."

]

)

)

-> [{'text': 'I love this!', 'label': 'positive', 'score': 0.9756}, ...]

Text Generation (Dialogue / Continuation)

Example

from

transformers

import

AutoTokenizer

,

AutoModelForCausalLM

import

torch

model_name

=

"Qwen/Qwen2-1.5B-Instruct"

   

Alibaba Tongyi Qianwen (supports Chinese)

tokenizer

=

AutoTokenizer.

from_pretrained

(

model_name

)

model

=

AutoModelForCausalLM.

from_pretrained

(

    model_name

,

torch_dtype

=

torch.

float16

,

device_map

=

"auto"

)

messages

=

[

   

{

"role"

:

"system"

,

"content"

:

"You are a useful AI assistant."

}

,

   

{

"role"

:

"user"

,

"content"

:

"Please explain what a Transformer is in three sentences?"

}

,

]

text

=

tokenizer.

apply_chat_template

(

messages

,

tokenize

=

False

,

add_generation_prompt

=

True

)

inputs

=

tokenizer

(

text

,

return_tensors

=

"pt"

)

.

to

(

model.

device

)

with

torch.

no_grad

(

)

:

output_ids

=

model.

generate

(

        **inputs

,

max_new_tokens

=

300

,

temperature

=

0.7

,

top_p

=

0.9

,

do_sample

=

True

,

repetition_penalty

=

1.1

,

pad_token_id

=

tokenizer.

eos_token_id

,

   

)

new_tokens

=

output_ids

[

0

]

[

inputs

[

"input_ids"

]

.

shape

[

1

]

:

]

response

=

tokenizer.

decode

(

new_tokens

,

skip_special_tokens

=

True

)

print

(

response

)

Named Entity Recognition (NER)

instance

from

transformers

import

pipeline

ner

=

pipeline

(

"ner"

,

model

=

"dslim/bert-base-NER"

,

aggregation_strategy

=

"simple"

)

result

=

ner

(

"Elon Musk founded SpaceX in 2002 and Tesla Motors in 2003."

)

for

entity

in

result:

   

print

(

f

"{entity['word']:<20} -> {entity['entity_group']} ({entity['score']:.3f})"

)

Chinese NER

ner_cn

=

pipeline

(

"ner"

,

model

=

"hfl/chinese-bert-wwm-ext-ner-msra"

,

aggregation_strategy

=

"simple"

)

result

=

ner_cn

(

"Xiao Ming studied at Peking University and later worked at Alibaba."

)

Machine translation

Instance

from

transformers

import

pipeline

English to Chinese

translator

=

pipeline

(

"translation"

,

model

=

"Helsinki-NLP/opus-mt-en-zh"

)

result

=

translator

(

"Artificial intelligence is transforming the world."

)

print

(

result

[

0

]

[

"translation_text"

]

)

 

-> Artificial intelligence is changing the world.

Chinese to English

translator_zh

=

pipeline

(

"translation"

,

model

=

"Helsinki-NLP/opus-mt-zh-en"

)

result

=

translator_zh

(

"Artificial intelligence is changing the world."

)

print

(

result

[

0

]

[

"translation_text"

]

)

Text summarization

Example

from

transformers

import

pipeline

summarizer

=

pipeline

(

"summarization"

,

model

=

"facebook/bart-large-cnn"

)

result

=

summarizer

(

long_text

,

max_length

=

80

,

min_length

=

30

,

do_sample

=

False

,

no_repeat_ngram_size

=

3

)

print

(

result

[

0

]

[

"summary_text"

]

)


Fine-tuning

Fine-tuning adapts a pre-trained model to your specific task and data, which is the most important application scenario for Transformers.

Fine-tuning process overview

Complete Transformers fine-tuning process Prepare data Dataset loading HF datasets or custom CSV Tokenize encoding Padding alignment DataLoader Key: data quality > data quantity Load model AutoModelForTask Specify num_labels Freeze bottom layers' parameters (optional) Fine-tune only the top layer Tip: small datasets Freeze the bottom layers first Training configuration TrainingArguments Learning rate: 2e-5 Batch:32 Epochs:3~5 Warmup steps Weight decay Tip: learning rate Most important Training & evaluation Trainer.train() Monitor the loss curve Validation set evaluation Early stopping Save the best checkpoint Note: overfitting Compare against baseline Save save_model() save_pretrained Push to Hub Production deployment Quantized inference ONNX export Using the HuggingFace Trainer greatly simplifies the training pipeline, automatically handling gradient accumulation, mixed precision, distributed training, and more.

Complete fine-tuning example: text classification

Example

from

datasets

import

load_dataset

from

transformers

import

(

AutoTokenizer

,

AutoModelForSequenceClassification

,

TrainingArguments

,

Trainer

,

DataCollatorWithPadding

,

EarlyStoppingCallback

,

)

import

evaluate

,

numpy

as

np

1. Load dataset

dataset

=

load_dataset

(

"imdb"

)

 

HF Hub Public Datasets

2. Tokenizer + Preprocessing

MODEL_NAME

=

"bert-base-uncased"

tokenizer

=

AutoTokenizer.

from_pretrained

(

MODEL_NAME

)

def

tokenize_fn

(

examples

)

:

   

return

tokenizer

(

examples

[

"text"

]

,

truncation

=

True

,

max_length

=

512

)

tokenized_ds

=

dataset.

map

(

tokenize_fn

,

batched

=

True

,

remove_columns

=

[

"text"

]

)

tokenized_ds

=

tokenized_ds.

rename_column

(

"label"

,

"labels"

)

tokenized_ds.

set_format

(

"torch"

)

data_collator

=

DataCollatorWithPadding

(

tokenizer

=

tokenizer

)

3. Load model

model

=

AutoModelForSequenceClassification.

from_pretrained

(

MODEL_NAME

,

num_labels

=

2

,

id2label

=

{

0

:

"NEGATIVE"

,

1

:

"POSITIVE"

}

,

label2id

=

{

"NEGATIVE"

:

0

,

"POSITIVE"

:

1

}

,

)

4. Evaluation Metrics

accuracy

=

evaluate.

load

(

"accuracy"

)

f1

=

evaluate.

load

(

"f1"

)

def

compute_metrics

(

eval_pred

)

:

    logits

,

labels

=

eval_pred

preds

=

np.

argmax

(

logits

,

axis

=

1

)

   

return

{

"accuracy"

: accuracy.

compute

(

predictions

=

preds

,

references

=

labels

)

[

"accuracy"

]

,

           

"f1"

: f1.

compute

(

predictions

=

preds

,

references

=

labels

,

average

=

"binary"

)

[

"f1"

]

}

5. Training Parameters

training_args

=

TrainingArguments

(

output_dir

=

"./results"

,

num_train_epochs

=

3

,

per_device_train_batch_size

=

16

,

per_device_eval_batch_size

=

32

,

gradient_accumulation_steps

=

2

,

learning_rate

=

2e-5

,

weight_decay

=

0.01

,

warmup_ratio

=

0.1

,

evaluation_strategy

=

"steps"

,

eval_steps

=

500

,

save_strategy

=

"steps"

,

save_steps

=

500

,

load_best_model_at_end

=

True

,

metric_for_best_model

=

"f1"

,

fp16

=

True

,

logging_steps

=

100

,

seed

=

42

,

)

6. Create Trainer and train

trainer

=

Trainer

(

model

=

model

,

args

=

training_args

,

    train_dataset

=

tokenized_ds

[

"train"

]

,

eval_dataset

=

tokenized_ds

[

"test"

]

,

tokenizer

=

tokenizer

,

data_collator

=

data_collator

,

compute_metrics

=

compute_metrics

,

callbacks

=

[

EarlyStoppingCallback

(

early_stopping_patience

=

3

)

]

,

)

trainer.

train

(

)

7. Evaluate and save

eval_result

=

trainer.

evaluate

(

)

print

(

f

"Accuracy: {eval_result['eval_accuracy']:.4f}"

)

print

(

f

"F1: {eval_result['eval_f1']:.4f}"

)

trainer.

save_model

(

"./my-sentiment-model"

)

tokenizer.

save_pretrained

(

"./my-sentiment-model"

)

LoRA Parameter Efficient Fine-Tuning (Recommended)

LoRA principle: train only the low-rank matrices while freezing the original weights. Full fine-tuning W + ΔW Update all weight matrices Params trained: all (e.g., full fine-tuning of 7B params) VRAM requirement: extremely high (needs 4× the model size) Cost: expensive, requires lots of GPU LoRA fine-tuning W (frozen) Not involved in training + B x A r << d (low-rank matrix) Train only here Parameter count: 0.1%–1% of the original VRAM requirement: low (only stores low-rank matrix gradients) Cost: a single 24GB card can fine-tune 7B LoRA decomposes ΔW into two low-rank matrices, where r is much smaller than d (typically r=8~64), greatly reducing training cost.

Example

from

peft

import

LoraConfig

,

get_peft_model

,

TaskType

from

transformers

import

AutoModelForCausalLM

,

AutoTokenizer

,

TrainingArguments

import

torch

model_name

=

"meta-llama/Llama-2-7b-hf"

model

=

AutoModelForCausalLM.

from_pretrained

(

    model_name

,

torch_dtype

=

torch.

float16

,

device_map

=

"auto"

,

load_in_4bit

=

True

,

       

4-bit quantization loading (QLoRA), further saving VRAM

)

Configure LoRA

lora_config

=

LoraConfig

(

    task_type

=

TaskType.

CAUSAL_LM

,

r

=

16

,

lora_alpha

=

32

,

lora_dropout

=

0.05

,

target_modules

=

[

"q_proj"

,

"v_proj"

,

"k_proj"

,

"o_proj"

]

,

)

model

=

get_peft_model

(

model

,

lora_config

)

model.

print_trainable_parameters

(

)

-> trainable: 4,194,304 || all: 6,742,609,920 || 0.0622%

LoRA advantages: only trains less than 1% of parameters, reduces VRAM by 60-70%, is 2-3 times faster, and the weight file is only a few MB, allowing multiple LoRA adapters to be saved for different tasks on the same base model.


Model Saving, Loading, and Publishing

Instance

Local Saving

model.

save_pretrained

(

"./my-model"

)

tokenizer.

save_pretrained

(

"./my-model"

)

Load locally

model

=

AutoModelForSequenceClassification.

from_pretrained

(

"./my-model"

)

tokenizer

=

AutoTokenizer.

from_pretrained

(

"./my-model"

)

Publish to HuggingFace Hub

from

huggingface_hub

import

login

login

(

token

=

"your_hf_token"

)

 

huggingface.co/settings/tokens

model.

push_to_hub

(

"your-username/my-sentiment-model"

)

tokenizer.

push_to_hub

(

"your-username/my-sentiment-model"

)

Publish directly through Trainer

training_args

=

TrainingArguments

(

output_dir

=

"your-username/my-model"

,

push_to_hub

=

True

,

hub_strategy

=

"every_save"

,

)


Performance optimization tips

Inference acceleration panorama

Inference acceleration stack: from simple to deep optimization Level 1 - Zero-cost optimization torch.no_grad() inference | fp16/bf16 half precision | batch inference | device_map="auto" automatic device allocation Speedup: 1.5~2x Level 2 - Quantization (model compression) bitsandbytes 4-bit/8-bit quantization | GPTQ (post-training quantization) | AWQ (activation-aware quantization) Speedup: 2~4x, VRAM halved Level 3 - compilation and runtime optimization torch.compile()(PyTorch 2.0)| FlashAttention-2 | xFormers | Optimum(TensorRT/ONNX) Speedup: 3~10x Level 4 - Dedicated inference engine vLLM (high-throughput LLM inference) | TGI | TensorRT-LLM | llama.cpp (CPU) Production-grade, highest performance

Instance

4-bit quantization loading (13B model requires only about 7GB of VRAM)

from

transformers

import

BitsAndBytesConfig

,

AutoModelForCausalLM

import

torch

quant_config

=

BitsAndBytesConfig

(

    load_in_4bit

=

True

,

bnb_4bit_compute_dtype

=

torch.

float16

,

bnb_4bit_use_double_quant

=

True

,

bnb_4bit_quant_type

=

"nf4"

,

)

model

=

AutoModelForCausalLM.

from_pretrained

(

   

"meta-llama/Llama-2-13b-hf"

,

    quantization_config

=

quant_config

,

device_map

=

"auto"

,

)

FlashAttention-2 acceleration (requires pip install flash-attn)

model

=

AutoModelForCausalLM.

from_pretrained

(

   

"mistralai/Mistral-7B-v0.1"

,

attn_implementation

=

"flash_attention_2"

,

torch_dtype

=

torch.

bfloat16

,

device_map

=

"auto"

,

)

torch.compile (PyTorch 2.0+)

model

=

torch.

compile

(

model

,

mode

=

"reduce-overhead"

)


Common Issue Troubleshooting

Quick reference of common errors and solutions Error message Cause and solution CUDA out of memory Insufficient VRAM Reduce batch_size; add gradient_accumulation_steps; use fp16/4-bit; use a smaller model OSError: model not found Wrong model name or network issue Check spelling; set the HF_ENDPOINT mirror; if already downloaded, use the local path. ValueError: num_labels mismatch When loading the model, explicitly specify num_labels=your number of classes. tensors on different devices inputs = {k: v.to(model.device) for k, v in inputs.items()} loss = NaN / loss not decreasing Check learning rate (too high causes NaN); check label range (0~N-1); add gradient_clipping slow tokenizer / slow speed pip install tokenizers to install the Rust fast version; use use_fast=True (default)

Summary and Learning Path

Transformers learning path and core knowledge Stage 1 Getting started (1 week) pip install to set up environment Run 5 tasks end-to-end with Pipeline Understand the Tokenizer flow Manual inference with AutoModel Understand Encoder/Decoder Understand the model output structure Stage 2 Advanced (2 weeks) Load models from the Hub Text classification fine-tuning in practice Master the Trainer API Custom dataset processing Evaluate with compute_metrics Save and publish to the Hub Stage 3 Advanced (3 weeks) LoRA / PEFT fine-tuning Quantization (4-bit/8-bit) Multimodal model usage Custom training loop Multi-GPU with Accelerate FlashAttention acceleration Stage 4 Expert (continuous) Custom model architecture Pre-training from scratch vLLM production deployment RLHF/DPO alignment Contribute open-source models Research frontier papers You should practice hands-on at every stage: find a real dataset and run through the complete training → evaluation → deployment pipeline.

Key API Quick Reference

Examples

1. Load Tokenizer

tokenizer

=

AutoTokenizer.

from_pretrained

(

"model_name"

)

2. Encode text

inputs

=

tokenizer

(

text

,

return_tensors

=

"pt"

,

truncation

=

True

,

max_length

=

512

)

3. Load model

model

=

AutoModelForSequenceClassification.

from_pretrained

(

"model_name"

,

num_labels

=

N

)

4. Inference

with

torch.

no_grad

(

)

:

outputs

=

model

(

**inputs

)

5. Pipeline

pipe

=

pipeline

(

"task_name"

,

model

=

"model_name"

)

6. Training Configuration

args

=

TrainingArguments

(

output_dir

=

"./out"

,

num_train_epochs

=

3

,

learning_rate

=

2e-5

)

7. Training

trainer

=

Trainer

(

model

=

model

,

args

=

args

,

train_dataset

=

ds

,

compute_metrics

=

fn

)

8. Save

model.

save_pretrained

(

"./my-model"

)

tokenizer.

save_pretrained

(

"./my-model"

)

9. Dataset

dataset

=

load_dataset

(

"dataset_name"

)

dataset

=

dataset.

map

(

tokenize_fn

,

batched

=

True

)

10. LoRA

config

=

LoraConfig

(

r

=

16

,

lora_alpha

=

32

,

target_modules

=

[

"q_proj"

,

"v_proj"

]

)

model

=

get_peft_model

(

model

,

config

)


Reference resources