第三章:微调 - 为特定任务定制模型 目录 微调简介 为什么微调很重要 微调的类型 使用 Microsoft Olive 进行微调 实践示例 最佳实践和指导原则 高级技术 评估与监控 常见挑战与解决方案 总结 微调简介 微调是一种强大的机器学习技术,用于将预训练模型调整为执行特定任务或处理专业数据集。与从头开始训练模型不同,微调利用预训练模型已经学习到的知识,并根据您的具体使用场景进行调整。 什么是微调? 微调是一种迁移学习形式,其过程包括: 使用从大型数据集中学习到一般模式的预训练模型作为起点 使用您的特定数据集调整模型的内部参数 保留已有的宝贵知识,同时使模型专注于您的任务 可以将其比作教一位经验丰富的厨师学习一种新菜系——他们已经掌握了烹饪的基本技能,但需要学习新的技巧和风味。
微调是一种强大的机器学习技术,用于将预训练模型调整为执行特定任务或处理专业数据集。与从头开始训练模型不同,微调利用预训练模型已经学习到的知识,并根据您的具体使用场景进行调整。
微调是一种迁移学习形式,其过程包括:
可以将其比作教一位经验丰富的厨师学习一种新菜系——他们已经掌握了烹饪的基本技能,但需要学习新的技巧和风味。
微调在许多场景中至关重要:
1. 领域适配
2. 任务专精
3. 企业应用
在全参数微调中,所有模型参数都会在训练过程中更新。这种方法:
PEFT 方法仅更新一小部分参数,使过程更加高效:
专注于为特定的下游任务调整模型:
Microsoft Olive 是一个全面的模型优化工具包,简化了微调过程,同时提供企业级功能。
Microsoft Olive 是一个开源的模型优化工具,具有以下特点:
# Create a virtual environment python -m venv olive-env source olive-env/bin/activate # On Windows: olive-env\Scripts\activate # Install Olive with auto-optimization features pip install olive-ai[auto-opt] # Install additional dependencies pip install transformers onnxruntime-genai
# For CPU optimization pip install olive-ai[cpu] # For GPU optimization pip install olive-ai[gpu] # For DirectML (Windows) pip install olive-ai[directml] # For Azure ML integration pip install olive-ai[azureml]
# Check Olive CLI is available olive --help # Verify installation python -c "import olive; print('Olive installed successfully')"
此示例展示了如何微调一个小型语言模型以进行短语分类:
# Set up the environment mkdir fine-tuning-project cd fine-tuning-project # Download sample data (optional - Olive can fetch data automatically) huggingface-cli login # If using private datasets
# Basic fine-tuning command olive finetune \ --model_name_or_path meta-llama/Llama-3.2-1B-Instruct \ --trust_remote_code \ --output_path models/llama/ft \ --data_name xxyyzzz/phrase_classification \ --text_template "<|start_header_id|>user<|end_header_id|>\n{phrase}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n{tone}" \ --method lora \ --max_steps 100 \ --log_level 1
# Convert to ONNX format for optimized inference olive auto-opt \ --model_name_or_path models/llama/ft/model \ --adapter_path models/llama/ft/adapter \ --device cpu \ --provider CPUExecutionProvider \ --use_ort_genai \ --output_path models/llama/onnx \ --log_level 1
创建一个包含训练数据的 JSON 文件:
[ { "input": "What is machine learning?", "output": "Machine learning is a subset of artificial intelligence that enables computers to learn and improve from experience without being explicitly programmed." }, { "input": "Explain neural networks", "output": "Neural networks are computing systems inspired by biological neural networks that learn from data through interconnected nodes or neurons." } ]
# olive-config.yaml model: type: PyTorchModel config: model_path: "microsoft/DialoGPT-medium" task: "text-generation" data_configs: - name: "custom_dataset" type: "HuggingfaceContainer" load_dataset_config: data_files: "path/to/your/dataset.json" split: "train" pre_process_data_config: text_template: "User: {input}\nAssistant: {output}" passes: lora: type: LoRA config: r: 16 lora_alpha: 32 target_modules: ["c_attn", "c_proj"] modules_to_save: ["ln_f", "lm_head"]
# Run with custom configuration olive run --config olive-config.yaml --setup
# Fine-tune with QLoRA for better memory efficiency olive finetune \ --method qlora \ --model_name_or_path meta-llama/Meta-Llama-3-8B \ --data_name nampdn-ai/tiny-codes \ --train_split "train[:4096]" \ --eval_split "train[4096:4224]" \ --text_template "### Language: {programming_language} \n### Question: {prompt} \n### Answer: {response}" \ --per_device_train_batch_size 16 \ --per_device_eval_batch_size 16 \ --max_steps 150 \ --logging_steps 50 \ --output_path adapters/tiny-codes
1. 数据质量优先于数量
2. 数据格式与模板
3. 数据集划分
1. 学习率选择
2. 批量大小优化
3. 训练时长
1. 基础模型选择
2. 微调方法选择
1. 硬件优化
2. 内存管理
为不同任务训练多个适配器,同时共享基础模型:
# Train multiple LoRA adapters olive finetune --method lora --task_name "classification" --output_path adapters/classifier olive finetune --method lora --task_name "generation" --output_path adapters/generator # Generate multi-adapter ONNX model olive generate-adapter \ --base_model_path models/base \ --adapter_paths adapters/classifier,adapters/generator \ --output_path models/multi-adapter
实施系统化的超参数调优:
# hyperparameter-search.yaml search_strategy: type: "random" num_trials: 20 search_space: learning_rate: type: "float" low: 1e-6 high: 1e-3 log: true lora_r: type: "int" low: 8 high: 64 batch_size: type: "choice" values: [8, 16, 32]
实现领域专属的损失函数:
# custom_loss.py import torch import torch.nn as nn class CustomContrastiveLoss(nn.Module): def __init__(self, margin=1.0): super(CustomContrastiveLoss, self).__init__() self.margin = margin def forward(self, output1, output2, label): euclidean_distance = nn.functional.pairwise_distance(output1, output2) loss_contrastive = torch.mean((1-label) * torch.pow(euclidean_distance, 2) + (label) * torch.pow(torch.clamp(self.margin - euclidean_distance, min=0.0), 2)) return loss_contrastive
1. 标准指标
2. 领域专属指标
3. 评估设置
# evaluation_script.py from transformers import AutoTokenizer, AutoModelForCausalLM from datasets import load_dataset import torch def evaluate_model(model_path, test_dataset, metric_type="accuracy"): """ Evaluate fine-tuned model performance """ tokenizer = AutoTokenizer.from_pretrained(model_path) model = AutoModelForCausalLM.from_pretrained(model_path) # Evaluation logic here results = {} for example in test_dataset: # Process example and calculate metrics pass return results
1. 损失跟踪
# Enable detailed logging olive finetune \ --logging_steps 10 \ --eval_steps 50 \ --save_steps 100 \ --logging_dir ./logs \ --report_to tensorboard
2. 验证监控
3. 资源监控
症状:
解决方案:
# Regularization techniques passes: lora: type: LoRA config: r: 16 # Reduce rank to prevent overfitting lora_alpha: 16 # Lower alpha value lora_dropout: 0.1 # Add dropout weight_decay: 0.01 # L2 regularization
解决方案:
# Memory-efficient training olive finetune \ --method qlora \ --gradient_checkpointing true \ --per_device_train_batch_size 1 \ --gradient_accumulation_steps 16
解决方案:
# Performance optimization training_config: fp16: true # Mixed precision dataloader_num_workers: 4 optim: "adamw_torch" lr_scheduler_type: "cosine"
诊断步骤:
解决方案:
微调是一种强大的技术,使得最先进的 AI 能力变得触手可及。通过使用像 Microsoft Olive 这样的工具,组织可以高效地将预训练模型调整为满足其特定需求,同时优化性能和资源使用。
免责声明:
本文档使用AI翻译服务Co-op Translator进行翻译。尽管我们努力确保翻译的准确性,但请注意,自动翻译可能包含错误或不准确之处。原始语言的文档应被视为权威来源。对于关键信息,建议使用专业人工翻译。我们不对因使用此翻译而产生的任何误解或误读承担责任。