HuggingFace Transformers 提供对数千个预训练模型的访问,覆盖 NLP、视觉、音频和多模态任务。文档地址为 https://huggingface.co/docs/transformers,模型库为 https://huggingface.co/models,课程为 https://huggingface.co/course。
用途与适用场景:快速推理可选用 pipeline;文本生成、分类、问答、NER;图像分类、目标检测;在自定义数据集上微调;从 HuggingFace Hub 加载预训练模型。NLP pipeline 包括 text-generation、text-classification、question-answering、summarization、translation_en_to_fr、ner、fill-mask;视觉包括 image-classification、object-detection、image-segmentation;音频包括 automatic-speech-recognition、audio-classification。
模型加载常用 Auto 类:AutoModel(嵌入)、AutoModelForCausalLM(GPT 式生成)、AutoModelForSeq2SeqLM(T5、BART 等编码器-解码器)、AutoModelForSequenceClassification、AutoModelForTokenClassification、AutoModelForQuestionAnswering。建议优先用 Auto 类以自动识别模型结构。
生成参数:max_new_tokens 常用 50–500;temperature 0.1–1.0(0 为确定性);top_p 0.9–0.95;top_k 50;num_beams 4–8(启用后关闭采样);repetition_penalty 1.1–1.3。事实类任务建议低温度(0.1–0.3)。
显存管理:device_map 可取 "auto"、"cuda:0"、"cpu"。量化方式包括 8-bit(约减少 50% 显存,质量影响极小)、4-bit(约 75%,多数任务影响小)、GPTQ、AWQ(约 75%)。可用 torch_dtype="auto" 采用模型原生精度。
微调:Trainer 参数有 num_train_epochs(3–5)、per_device_train_batch_size(8–32)、learning_rate(微调常用 2e-5)、weight_decay(0.01)、warmup_ratio(0.1)、evaluation_strategy("epoch" 或 "steps")。策略包括全量微调、LoRA、QLoRA、prefix tuning。分词需设置 padding、truncation、max_length、return_tensors("pt"、"tf"、"np"),且分词器必须与模型匹配。
最佳实践:推理用 pipeline;用 device_map="auto" 优化 GPU 分配;批处理提升吞吐;大模型用量化;微调用 Trainer。限制方面,除上述资料外的收费、价格或具体性能数据暂未提供。