DeepSeek Data Engineering Tutorial
From data collection to quality evaluation, fully master the LLM data engineering pipeline. Covers core aspects such as SFT dataset construction, RLHF preference data preparation, data cleaning and deduplication, data augmentation, and large-scale data processing, with Python practical code.
Start LearningData is the Soul of LLM
In large model training, data quality directly determines the upper limit of model capability. High-quality datasets can enable small models to surpass large models, while low-quality data can make trillion-parameter models perform mediocrely. Data engineering covers the entire chain from raw data collection to final training data delivery.
Data Engineering Overview
Understand the central role of data in LLM training, grasp the trade-off between data quality and quantity, and build a comprehensive understanding of the data engineering pipeline.
The Central Role of Data in LLM Training
Among the three elements of LLM training (algorithm, compute, data), data is often underestimated, but its importance far exceeds the other two. A widely held view is that the marginal returns of model architecture diminish, while the marginal returns of data quality increase. Here are three interrelated core facts:
- Data quality determines the upper bound of model capability: Even with the most advanced model architecture (e.g., MoE), if the training data quality is poor, the model cannot produce high-quality responses. The strong capabilities of DeepSeek-V3 and R1 are largely attributed to carefully constructed training data.
- Data diversity determines generalization ability: Data from a single domain can cause the model to overfit, while diverse data enables the model to perform well on unseen tasks. DeepSeek's data mixing strategy covers multiple domains such as mathematics, code, reasoning, dialogue, and creative writing.
- Data scale determines the knowledge boundary: The model's knowledge scope does not exceed the coverage of the training data. To make the model understand medicine, high-quality medical data is necessary; to make the model capable of programming, sufficient code data is required.
Data Quality vs. Data Quantity
Under limited computational resources, data quality is more important than data quantity. Here is a trade-off analysis of the two:
| Dimension | Pursuing Quantity | Pursuing Quality |
|---|---|---|
| Training Efficiency | Longer training time, slower convergence | Faster training, more stable convergence |
| Model Performance | More noise, unstable outputs | Accurate outputs, fewer hallucinations |
| Cost | High GPU cost, long cycle | Higher data cleaning cost, but lower total cost |
| Typical Strategy | Crawl web data, coarse filtering | Curated data sources, multiple filtering, human annotation |
The DeepSeek team found in practice that models trained on 1/10 of high-quality data often outperform models trained on the full set of coarse data in instruction following and reasoning capabilities. This also explains why data engineering is the most critical part of LLM development.
Data Engineering Pipeline Overview
A complete data engineering pipeline includes the following stages:
- Data Collection: Obtain raw data from public datasets, web crawling, API calls, synthetic generation, and other channels
- Data Cleaning: Remove duplicates, filter low quality, handle missing values, filter sensitive information
- Data Annotation: Construct data in different formats for different training stages such as SFT, RLHF, DPO
- Data Augmentation: Expand data using techniques like Self-Instruct, Evol-Instruct, back-translation
- Quality Evaluation: Evaluate data quality from dimensions such as diversity, difficulty, instruction complexity
- Data Mixing: Mix data from different domains in proportions to form the final training dataset
- Version Management: Use tools like DVC to manage data versions, ensuring reproducibility
Data Collection and Sources
Learn about the main sources of LLM training data, including public datasets, web crawling, synthetic data generation, and data compliance considerations.
Common Public Datasets
| Dataset Name | Size | Type | Use Case |
|---|---|---|---|
| Alpaca | 52K | SFT instruction data | Instruction fine-tuning basics |
| ShareGPT | 90K | Multi-turn dialogue | Dialogue capability training |
| UltraChat | 1.5M | Multi-turn dialogue | Large-scale dialogue training |
| OpenOrca | 4M | SFT instruction data | Large-scale instruction fine-tuning |
| CodeAlpaca | 20K | Code generation | Code capability training |
| MathInstruct | 260K | Mathematical reasoning | Mathematical capability training |
Loading Public Datasets from Hugging Face
Web Scraping and Data Collection
For domain-specific data, web scraping is an important supplementary method. Below is an example crawler for documentation and tutorials:
Synthetic Data Generation
When public data is insufficient to cover a specific domain, synthetic data generation techniques can be used. High-quality training data can be generated using strong models like DeepSeek:
Data Compliance Notes
When using public datasets and web-scraped data, be sure to check the data license agreement. Some datasets (such as ShareGPT) have specific usage restrictions. Web scraping should comply with the robots.txt protocol, control the scraping frequency, and avoid burdening the target website. Data involving personal privacy information needs to be desensitized.
Data Cleaning and Deduplication
Data cleaning is the most time-consuming but crucial step in data engineering. High-quality data cleaning can significantly improve model training results, including quality filtering, deduplication, and sensitive information filtering.
Quality Filtering Pipeline
A complete quality filtering pipeline includes filtering from multiple dimensions:
MinHash LSH Deduplication
MinHash + LSH (Locality-Sensitive Hashing) is an industry-standard large-scale deduplication solution that efficiently detects near-duplicate documents:
Semantic Deduplication
MinHash is suitable for literal-level deduplication, but for data that is semantically similar but expressed differently, embedding vectors are needed for semantic deduplication:
Sensitive Information Filtering
In training data, personal privacy information and sensitive content must be filtered out:
Data Formats and Annotation
Different training stages require different data formats. SFT uses the Instruction-Input-Output format, ChatML is used for dialogue scenarios, and RLHF/DPO requires preference comparison data. Understanding these formats is the foundation for building high-quality datasets.
SFT Data Format (Instruction-Input-Output)
SFT (Supervised Fine-Tuning) data is the most basic training data format. Each data point contains an instruction, optional input, and expected output:
ChatML Conversation Format
ChatML (Chat Markup Language) is a conversation format defined by OpenAI, also widely used in SFT training. It structures multi-turn conversations into a standard format:
RLHF Preference Data Format
RLHF (Reinforcement Learning from Human Feedback) and DPO (Direct Preference Optimization) require preference comparison data, i.e., for the same prompt, annotate which response is better:
Data Format Selection Recommendations
For basic SFT training, the Instruction-Input-Output format is sufficient; for multi-turn dialogue scenarios, the ChatML format is recommended; if RLHF or DPO training is needed, preference comparison data must be prepared. DeepSeek series models support both Alpaca format and ChatML format.
Data Augmentation Techniques
When existing data is insufficient, data augmentation techniques can help you generate large amounts of high-quality training data from a small set of seed data. Self-Instruct and Evol-Instruct are the two most popular methods.
Self-Instruct Self-Generation Method
The core idea of Self-Instruct is to use a strong model to automatically generate new instruction-output pairs from seed tasks:
Evol-Instruct Evolutionary Generation
Evol-Instruct generates more challenging data by gradually increasing the complexity of instructions. The DeepSeek team used similar evolutionary strategies extensively in training:
Back Translation Data Augmentation
Back Translation is a classic method for multilingual data augmentation, generating semantically equivalent but differently expressed data through translation and back-translation:
DeepSeek Specific Data Preparation
DeepSeek-R1's reasoning data has special format requirements, including thinking tags and CoT (Chain of Thought) reasoning chains. This chapter details how to prepare data for DeepSeek models.
DeepSeek-R1 Reasoning Data Format
The key innovation of DeepSeek-R1 is that the training data includes explicit thinking/reasoning processes. The following is the standard R1 reasoning data format:
CoT Data Construction
The key to constructing Chain of Thought data is to let the model learn to "think first, then answer." The following code automatically generates CoT reasoning chains for math problems:
Code Data Preparation
Code data is an important part of DeepSeek training data. High-quality code data should include problem descriptions, code implementations, and comments:
Math Data Preparation
Math reasoning data needs to include formulas, derivation steps, and final answers. LaTeX format is the standard for mathematical expressions:
Data Quality Evaluation
Data quality evaluation is the last line of defense in data engineering. Evaluate dataset quality from multiple dimensions such as diversity, difficulty, instruction complexity, and automatic scoring to ensure training data meets expected standards.
Diversity Evaluation
Diversity evaluation ensures the dataset covers a sufficiently wide range of domains and task types:
Difficulty Evaluation
Evaluate the difficulty of each instruction in the dataset to ensure a reasonable difficulty distribution:
Instruction Complexity Scoring
Instruction complexity scoring evaluates the quality of instructions from multiple dimensions:
| Scoring Dimension | Description | Scoring Method |
|---|---|---|
| Clarity | Whether the instruction is clear and unambiguous | LLM score 1-5 |
| Completeness | Whether the instruction contains sufficient context | Information density calculation |
| Executability | Whether the instruction can be completed | LLM executability judgment |
| Creativity | Whether the instruction encourages creative thinking | LLM score 1-5 |
Automatic Quality Scoring
Use LLM as a judge to automatically score data quality:
Data Mixing Strategy
Data from different domains needs to be mixed in specific proportions to train a comprehensive and balanced model. The data mixing strategy directly affects the model's general capabilities and specialized abilities.
Typical Data Mixing Ratios
The following are reference data mixing ratios commonly used in DeepSeek-like model training:
| Data Category | Suggested Ratio | Description |
|---|---|---|
| General Conversation | 30-40% | Daily conversation, Q&A, chit-chat, ensuring basic conversational ability |
| Code Generation | 15-20% | Code in mainstream languages like Python/JS/Java/C++ |
| Mathematical Reasoning | 10-15% | Algebra, geometry, calculus, probability and statistics |
| Logical Reasoning | 10-15% | Logic puzzles, reasoning chains, multi-step reasoning |
| Creative Writing | 5-10% | Poetry, stories, copywriting, scripts |
| Professional Domains | 5-10% | Vertical domains such as medicine, law, finance |
| Safety Alignment | 3-5% | Rejecting harmful requests, value alignment |
Code Implementation for Data Mixing
Data Annealing Strategy
Data annealing is a training strategy that dynamically adjusts data mixing ratios during training. Early on, diverse data is used to train basic capabilities, and later, the proportion of high-quality, high-difficulty data is gradually increased:
- Warm-up phase (first 20% of training steps): General chat data accounts for 50%, mainly simple instructions, helping the model build basic conversational abilities.
- Main training phase (20%-80% of training steps): Gradually increase the proportion of code and reasoning data, introducing medium-difficulty tasks.
- Annealing phase (last 20% of training steps): Substantially increase high-quality, high-difficulty data, reduce general chat data, and improve the model's performance on complex tasks.
The DeepSeek team used a similar annealing strategy in their training, which is one of the important reasons why DeepSeek-R1 excels in reasoning capabilities.
Large-scale Data Processing
When data volume reaches millions or even hundreds of millions, single-machine processing is no longer feasible. This chapter introduces distributed frameworks like Spark and Ray for large-scale data processing, as well as data version management.
Parallel Processing with Ray
Ray is a lightweight distributed computing framework, particularly suitable for data processing tasks in the Python ecosystem:
Distributed Processing with PySpark
PySpark is the standard tool for processing TB-level large-scale data, supporting DataFrame API and SQL operations:
Stream Processing Large Files
For extremely large JSONL files, use stream processing to avoid memory overflow:
Data Version Control (DVC)
DVC (Data Version Control) is the Git for data science, used to manage dataset versions:
Production-Grade Data Pipeline
Integrate all previous steps into a complete production-grade data pipeline, including continuous data collection, automated quality monitoring, data drift detection, and complete pipeline code.
Complete Data Pipeline Architecture
- Data Collection Layer: Scheduled tasks to fetch public dataset updates, crawl new content, call synthetic data APIs
- Data Cleaning Layer: Quality filtering, deduplication, sensitive information filtering, format standardization
- Data Augmentation Layer: Self-Instruct generation, Evol-Instruct evolution, back-translation
- Quality Evaluation Layer: Diversity scoring, difficulty assessment, automatic quality scoring
- Data Mixing Layer: Proportional mixing, data annealing strategy, version management
- Monitoring and Alerting Layer: Data drift detection, quality trend monitoring, anomaly alerting
Complete Pipeline Code
Data Drift Detection
Data drift refers to changes in the data distribution over time. In production environments, it is necessary to continuously monitor whether data quality deviates from expectations:
Automated Quality Monitoring
Use scheduled tasks to continuously monitor data quality metrics:
Running the Pipeline
Production Environment Recommendations
- Use Apache Airflow or Prefect to orchestrate pipeline tasks
- Push quality metrics to Prometheus + Grafana for visual monitoring
- Configure alert rules: data quality pass rate below threshold, abnormal data volume fluctuations, etc.
- Use DVC or LakeFS for data version management to ensure reproducibility
- Regularly manually sample data quality and cross-validate with automatic scoring
DeepSeek Data Engineering FAQ
DeepSeek Related Tutorials
Dive deeper into DeepSeek model usage, deployment, and ecosystem tools.
How to Use DeepSeek Models
Four usage methods, zero-basics tutorial.
DeepSeek Fine-tuning Tutorial
LoRA/QLoRA fine-tuning, SFT, RLHF full pipeline.
DeepSeek RAG Knowledge Base
Vector databases, retrieval-augmented generation, document Q&A.
DeepSeek Deployment Tutorial
Ollama, Docker, vLLM, K8s deployment solutions.
DeepSeek Model Architecture
Technical architecture, benchmarks, model selection comparison.
DeepSeek Ecosystem Tools
WebUI, IDE plugins, Agent frameworks, RAG platforms.