DeepSeek Model Fine-tuning Tutorial
Customize DeepSeek models into your own AI assistant. From data preparation to model deployment, complete fine-tuning workflow with ready-to-run code and configurations.
Start LearningFine-tuning Overview
Before starting fine-tuning, understand what fine-tuning is, when it's needed, and the types of fine-tuning.
What is Model Fine-tuning?
Model fine-tuning refers to additional training of a pre-trained large language model on domain-specific data to improve its performance on specific tasks. DeepSeek models already have strong general capabilities, but if you need them to be more professional in vertical domains such as medical diagnosis, legal consultation, financial analysis, code review, etc., fine-tuning is the most effective approach.
When to Fine-tune vs. When to Use Prompt Engineering?
This is a common question among developers. Here are the criteria:
- Need the model to master domain-specific knowledge (medicine, law, finance, etc.)
- Need specific output formats (JSON structure, specific templates)
- Need to mimic a specific writing style or tone
- Prompts are too long to fully describe requirements in context
- Need to reduce inference cost (fine-tuned smaller models can replace larger ones)
- Need to reduce latency (no complex prompts after fine-tuning)
- Task is simple and can be described in a few sentences
- Insufficient data (fewer than 100 high-quality samples)
- Requirements change frequently, don't want to retrain repeatedly
- Only need it temporarily, no long-term maintenance
- Worried about degradation of other capabilities due to fine-tuning
Main Types of Fine-tuning
LoRA Fine-tuning
Low-Rank Adaptation adds small parameter matrices alongside the original model, training only these new parameters. Low VRAM requirement, fast training speed, and can fine-tune a 7B model on a single GPU. It is the most mainstream and recommended fine-tuning method.
- VRAM requirement: ~16GB for 7B model
- Training speed: Fast (hours)
- Model quality: Close to full fine-tuning
- Can be merged back into the original model
QLoRA Fine-tuning
Adds 4-bit quantization on top of LoRA, compressing model parameters to 4-bit precision. Further reduces VRAM requirements, allowing fine-tuning of 7B models on consumer GPUs (e.g., RTX 3090 24GB). Slightly slower than LoRA but with comparable results.
- VRAM requirement: ~8-10GB for 7B model
- Training speed: Medium (hours)
- Model quality: Comparable to LoRA
- Suitable for consumer GPUs
Full Fine-tuning
Updates all model parameters, theoretically the best results, but requires large GPU memory. A 7B model requires about 60-80GB VRAM, typically requiring multi-GPU training or DeepSpeed ZeRO optimization. Suitable for teams with ample compute resources.
- VRAM requirement: ~60-80GB for 7B model
- Training speed: Slow (days)
- Model quality: Optimal
- Requires multi-GPU/A100
Special Advantages of Fine-tuning DeepSeek Models
DeepSeek models use the MoE (Mixture of Experts) architecture, offering the following advantages for fine-tuning:
- Dense models (e.g., DeepSeek-Coder-6.7B): Standard architecture, well-supported for LoRA/QLoRA, rich community resources
- MoE models (e.g., DeepSeek-V2-Lite): Only activate a subset of experts per inference, high inference efficiency, can target specific experts during fine-tuning
- Official code support: DeepSeek's official GitHub repository provides complete fine-tuning code, ready to use
- MIT open-source license: Fine-tuned models can be used commercially without restrictions
For more information about DeepSeek model architecture, please see DeepSeek Model Architecture Details and DeepSeek Open Source Model List.
Environment Preparation
Before starting fine-tuning, you need to install the necessary Python dependencies and configure the GPU environment.
Hardware Requirements
| Fine-tuning Method | 1.5B Model | 7B Model | 16B Model | Recommended GPU |
|---|---|---|---|---|
| QLoRA (4-bit) | ~4GB | ~8-10GB | ~16-20GB | RTX 3060 12GB or higher |
| LoRA (FP16/BF16) | ~8GB | ~16-20GB | ~32-40GB | RTX 3090/4090 24GB |
| Full Parameter Fine-tuning | ~20GB | ~60-80GB | ~120-160GB | A100 80GB / Multi-GPU |
Install Dependencies
Create a new Python virtual environment and install the following dependencies:
Verify Environment
After installation, run the following Python script to verify the environment is working:
Environment Notes
- bitsandbytes installation: Windows users may need to compile from source; WSL2 or Linux environment is recommended
- CUDA version matching: PyTorch's CUDA version must be compatible with the system-installed CUDA driver version
- Cloud GPU recommendation: If you don't have a local GPU, we recommend domestic GPU cloud platforms such as AutoDL and Hengyuan Cloud
Dataset Preparation
High-quality data is the key to successful fine-tuning. This section introduces data formats, data quality requirements, and best practices for data preparation.
Data Format
Fine-tuning data typically uses JSON or JSONL format. Each data entry contains an instruction and the corresponding output, with an optional input field.
Alpaca Format (Recommended)
The Alpaca format is the most commonly used data format in the fine-tuning community and has the best compatibility with DeepSeek models:
Chat Format (Conversation Data)
If you have conversation data, you can use the ShareGPT format or the conversations format:
Data Quality Recommendations
- Minimum 100-200 high-quality samples
- Recommended 500-2000 samples
- Simple tasks: 500 samples is enough
- Complex tasks: recommend 2000+ samples
- Cover different difficulty levels and scenarios
- Avoid duplicate or highly similar samples
- Mix long and short texts
- Include edge cases
- Output must be accurate
- Code examples must be runnable
- Professional domain knowledge needs verification
- Keep format consistent
- Unified output format
- Consistent tone and style
- Consistent terminology
- Unified punctuation standards
Data quality matters more than quantity
500 high-quality data points are far more effective than 5000 low-quality ones. Each sample should be manually reviewed to ensure accurate output and proper formatting. If data quality is poor, fine-tuning can actually damage the model's original capabilities.
Using DeepSeek to Generate Training Data
You can leverage DeepSeek itself to generate high-quality training data. Here is a practical data generation strategy:
For more DeepSeek API usage, please refer to DeepSeek Usage Tutorial.
LoRA Fine-tuning (Recommended)
LoRA is currently the most recommended and practical fine-tuning method. This section provides complete QLoRA fine-tuning code and detailed parameter explanations.
LoRA Fine-tuning Principle
The core idea of LoRA (Low-Rank Adaptation) is to add low-rank matrices alongside the weights of a pre-trained model, training only these newly added matrix parameters while keeping the original model weights unchanged. This significantly reduces the number of trainable parameters and memory requirements.
Specifically, for the original weight matrix W (d x k), LoRA decomposes its update into the product of two small matrices: W + delta_W = W + B * A, where A is an r x k matrix, B is a d x r matrix, and r is the rank, typically 8-64. Since r is much smaller than d and k, the number of trainable parameters is greatly reduced.
Complete QLoRA Fine-tuning Code
The following is a complete Python script for fine-tuning a DeepSeek model using QLoRA (4-bit quantization + LoRA):
Key Parameter Explanations
| Parameter | Recommended Value | Description |
|---|---|---|
| r (rank) | 8-64 | The larger the rank, the stronger the expressiveness, but the more training parameters and GPU memory are required. For simple tasks, r=8 is sufficient; for complex tasks, r=32-64 can be used. |
| lora_alpha | 2 times r | Scaling factor that controls the influence of LoRA weights on the original model. Usually set to 2 times r. |
| learning_rate | 1e-4 ~ 5e-4 | Learning rate. LoRA typically uses a higher learning rate than full fine-tuning; 2e-4 is recommended. |
| num_train_epochs | 2-5 | Number of training epochs. If the dataset is small, you can increase the number of epochs; if large, 2-3 epochs suffice. Watch the loss curve to prevent overfitting. |
| max_seq_length | 2048-4096 | Maximum sequence length. Longer texts require more GPU memory. DeepSeek-Coder supports 16K context. |
Running Training
Save the above code as train_lora.py and run:
Training Acceleration Tips
- Use gradient_checkpointing: Trade computation for memory; set
gradient_checkpointing=Truein TrainingArguments. - Adjust batch_size: If GPU memory is insufficient, reduce per_device_train_batch_size and increase gradient_accumulation_steps.
- Use Flash Attention 2: Install the flash-attn library and set
use_flash_attention_2=Truewhen loading the model; this can speed up training by 2-3x.
For more model download and deployment information, see DeepSeek Model Download and DeepSeek Deployment Tutorial.
Full Parameter Fine-tuning
Full parameter fine-tuning theoretically yields the best results, but requires a large amount of GPU memory. This section introduces how to perform full parameter fine-tuning using DeepSpeed ZeRO.
Requirements for Full Parameter Fine-tuning
Full parameter fine-tuning updates all parameters of the model, requiring the entire model to be loaded into GPU memory. For a 7B model, just the model weights require about 14GB (FP16), plus optimizer states and gradients, totaling about 60-80GB of GPU memory. Therefore, multi-GPU training or GPUs with large memory such as A100/H100 are typically needed.
DeepSpeed ZeRO Configuration
DeepSpeed ZeRO distributes optimizer states, gradients, and model parameters across multiple GPUs, significantly reducing the memory requirement per GPU. Below is the DeepSpeed configuration for full parameter fine-tuning of DeepSeek models:
Full Parameter Fine-tuning Training Script
Start Multi-GPU Training
Full Parameter Fine-tuning vs LoRA Selection Recommendations
- Prefer LoRA: In most scenarios, LoRA's performance is very close to full fine-tuning (typically < 2% difference), but at a much lower cost
- Full fine-tuning is suitable when: You need to significantly change model behavior in a new domain, have ample computational resources, and pursue ultimate performance
- Hybrid strategy: Start with LoRA for quick experiments to find optimal data and hyperparameters, then use full fine-tuning for the final version
Using DeepSeek Official Fine-Tuning Code
DeepSeek provides complete fine-tuning code on GitHub, which can be used directly without writing training scripts from scratch.
Get Official Fine-Tuning Code
The official DeepSeek GitHub repository contains all the code needed for training and fine-tuning. Take DeepSeek-Coder as an example:
Official Fine-Tuning Commands
DeepSeek provides a simple command-line interface that supports LoRA and full-parameter fine-tuning:
The official DeepSeek fine-tuning code expects data in JSONL format, with each line containing instruction and output fields:
Advantages of Official Code
- Optimized for DeepSeek model architecture, higher training efficiency
- Automatically handles DeepSeek-specific tokenizer and model configuration
- Built-in data processing and evaluation logic
- Continuously updated, compatible with the latest model versions
For more DeepSeek ecosystem tools, please see DeepSeek Ecosystem Tools.
Training Monitoring
Monitor loss curves, learning rate changes, and GPU usage in real-time during training to help you detect anomalies and adjust parameters promptly.
TensorBoard Monitoring
TensorBoard is PyTorch's built-in training visualization tool. After setting report_to="tensorboard" in your training code, launch TensorBoard:
Wandb Monitoring
Wandb (Weights & Biases) provides richer cloud-based training monitoring features and supports team collaboration:
Key Monitoring Metrics
- Training loss should continuously decrease
- If loss doesn't decrease, check learning rate
- If loss oscillates violently, reduce learning rate
- If loss plateaus after rapid decline, it's normal
- GPU utilization should be close to 90-100%
- Low utilization = data loading bottleneck
- Increase num_workers to speed up data loading
- Use nvidia-smi to view in real-time
- Use cosine scheduler for automatic decay
- Gradually increase learning rate during warmup
- If loss doesn't decrease, try increasing learning rate
- If loss oscillates, try decreasing learning rate
- Save checkpoints periodically
- save_total_limit controls the number of saved checkpoints
- Training can resume from a checkpoint after interruption
- Keep the checkpoint with the lowest loss
Resume Training from Checkpoint
If training is unexpectedly interrupted, you can resume from the most recent checkpoint:
Overfitting Warning Signs
If training loss continues to decrease but validation loss starts to increase, the model is overfitting. In this case, you should: reduce the number of training epochs, increase the amount of data, increase lora_dropout, or use a smaller learning_rate.
Model Evaluation
After fine-tuning, it is necessary to evaluate the model's performance on the target task to ensure that the fine-tuning has achieved the expected results.
Evaluation Methods
Model evaluation is divided into two methods: automatic evaluation and manual evaluation.
Quantitative Metrics
- Perplexity
- ROUGE / BLEU scores
- Accuracy / F1 score
- HumanEval (code tasks)
- MMLU (knowledge Q&A)
Qualitative Evaluation
- Output quality scoring
- Instruction following
- Answer accuracy
- Style consistency
- A/B comparison testing
Test Set Evaluation Script
Benchmark Comparison
It is recommended to compare the outputs of the model before and after fine-tuning on the same test set to evaluate the improvements brought by fine-tuning:
- Horizontal comparison: Fine-tuned model vs. original model vs. other similar models
- Longitudinal comparison: Differences in performance between different checkpoints
- Ablation experiments: Comparison of effects of different hyperparameter combinations
- Boundary testing: Test the model's performance under extreme inputs
Evaluation Recommendations
Don't just look at automatic evaluation metrics. Be sure to test the model in real-world scenarios, especially edge cases and error-prone situations. If the fine-tuned model degrades significantly in general capabilities, consider retraining with a mix of original data and fine-tuning data.
Model Merging and Export
After fine-tuning, you need to merge the LoRA weights back into the original model and export it in different formats for deployment.
Merging LoRA Weights
LoRA training produces adapter weights, which need to be merged back into the original model to be used as a standalone model:
Export to GGUF Format (Ollama / llama.cpp)
GGUF is the model format used by llama.cpp and Ollama, allowing efficient local execution after export:
Creating an Ollama Modelfile
After exporting GGUF, create a Modelfile to use it in Ollama:
Push to Hugging Face
Share the fine-tuned model with the Hugging Face community:
For more deployment options, see the DeepSeek Deployment Tutorial.
Deployment
The final step after fine-tuning: deploy the model to production and provide API services.
Deployment Options Comparison
Ollama Local Deployment
Suitable for personal use and small teams, one-click deployment of the fine-tuned model. After exporting to GGUF format, run it via Ollama, supporting API calls.
- Start with one command
- Compatible with OpenAI API format
- Low resource usage
- Suitable for single-machine deployment
vLLM Deployment
Suitable for production environments, high-performance inference engine. Supports PagedAttention, continuous batching, multi-GPU parallel inference, with throughput far exceeding Ollama.
- High throughput
- Compatible with OpenAI API
- Supports multiple GPUs
- Production-grade stability
Hugging Face Inference
After pushing the model to Hugging Face, you can directly use Inference Endpoints for deployment without managing servers.
- No maintenance
- Automatic scaling
- Pay-as-you-go
- Global nodes
vLLM Deployment Commands
vLLM is currently the most recommended high-performance inference engine for production environments:
Docker Deployment
Using Docker deployment ensures environment consistency, making it easy to migrate and scale:
API Call Example (Python)
Production Environment Considerations
- Health Check: Configure the /health endpoint to ensure service availability monitoring
- Rate Limiting: Set request frequency limits via Nginx or API gateway
- Concurrency Control: vLLM supports the max_num_seqs parameter to control the number of concurrent requests
- Logging: Log all API requests and responses for troubleshooting
- Model Hot Update: Use blue-green deployment strategy for zero-downtime model updates
For more deployment details, see DeepSeek Deployment Tutorial and DeepSeek Usage Tutorial.
DeepSeek Model Fine-tuning FAQ
DeepSeek Complete Tutorial Index
Here are all our DeepSeek-related tutorials, from beginner to advanced, for one-stop learning.
How to Use DeepSeek Models
Zero-basics tutorial, four ways to use DeepSeek models with step-by-step guidance.
View TutorialDeepSeek Model Download
One-click download via Ollama, original weights from Hugging Face, official GitHub repository.
View DownloadDeepSeek Open-Source Model List
All open-source model specs, parameters, download links, and use cases at a glance.
View ListDeepSeek Deployment Tutorial
Local deployment with Ollama, Docker containerization, vLLM high-performance inference.
View DeploymentDeepSeek Model Architecture
In-depth analysis of MoE architecture, MLA attention, multi-head latent attention, and more.
View ArchitectureDeepSeek Ecosystem Tools
A collection of third-party tools, plugins, and integration solutions around DeepSeek.
View Tools