百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
D

deepseek-from-scratch

> 编程语言
开源

从头开始编写 DeepSeek R1 和 v3.2 实现,并进行生产就绪的 Rust 和 Python 编程

198 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

从头开始编写 DeepSeek R1 和 v3.2 实现,并进行生产就绪的 Rust 和 Python 编程

DeepSeek from Scratch

Educational implementations of DeepSeek-V3.2 and DeepSeek-R1 architectures in Rust (using Candle) and Python (using PyTorch/MLX).

This repository provides from-scratch implementations of the key innovations that make DeepSeek models state-of-the-art:

Attention Mechanisms

  • Multi-Query Attention (MQA) - Single KV head for memory-efficient inference
  • Grouped-Query Attention (GQA) - Balanced KV sharing across head groups
  • Multi-Head Latent Attention (MLA) - Compressed KV cache for efficient inference
  • DeepSeek Sparse Attention (DSA) - Hybrid local + dilated global attention patterns

Mixture of Experts

  • Standard MoE - Top-k expert routing with load balancing
  • DeepSeek MoE - Fine-grained experts with shared expert isolation
  • 256-Expert MoE - Hierarchical routing for massive expert scaling

Prediction & Quantization

  • Multi-Token Prediction (MTP) - Predict multiple future tokens simultaneously
  • FP8 Mixed-Precision - Low-precision training with dynamic scaling
  • FP8 Quantization - Simulated 8-bit inference for deployment

️ Training & Alignment

  • GRPO Training - Group Relative Policy Optimization for RL
  • DPO Training - Direct Preference Optimization
  • SFT Pipeline - Supervised Fine-Tuning infrastructure
  • Knowledge Distillation - Teacher-student model compression
  • Agent & Tool-Use Training - Function calling and tool integration

Infrastructure

  • 5D Parallelism - Tensor, Pipeline, Data, Expert, and Sequence parallelism
  • ZeRO Optimization - Memory-efficient distributed training
  • DeepSeek-R1 Reasoning - Chain-of-thought reasoning with `` tags
  • Modal Cloud GPUs - Distributed training on A100/H100 GPUs

Table of Contents

  • Quick Start
  • Prerequisites
  • Installation
  • Docker Setup
  • Training Guide
  • Ablation Studies
  • Performance Benchmarks
  • Project Structure
  • Architecture Documentation
  • Reproducibility
  • Development
  • FAQ
  • Contributing
  • License
  • References

Quick Start

Train a Model in 5 Minutes

…

Run Demos & Benchmarks

bash
# PyTorch demos (CUDA/MPS/CPU)
uv run python -m deepseek.torch.main

# MLX demos (Apple Silicon native)
uv run python -m deepseek.mlx.main
uv run python -m deepseek.mlx.benchmark

# Rust demos (Metal)
cd rust-src
cargo run --release

️ Prerequisites

System Requirements

  • macOS 12.3+ (for Metal/MPS) or Linux with CUDA
  • Apple Silicon (M1/M2/M3/M4) recommended for best local performance
  • 8GB+ RAM recommended (16GB+ for larger models)

Required Tools

Tool Purpose Installation
Python 3.10+ Python implementation python.org
UV Fast Python package manager curl -LsSf https://astral.sh/uv/install.sh | sh
Rust Rust implementation rustup.rs
Modal (optional) Cloud GPU training pip install modal && modal setup

Installation

Python Setup (Recommended)

bash
cd DeepSeek-From-Scratch

# Install with UV (fastest)
uv sync

# Or install with all optional extras
uv sync --all-extras  # Includes MLX, CoreML, dev tools

Alternative (pip):

bash
pip install torch numpy einops transformers
pip install mlx  # Optional: Apple Silicon only
pip install coremltools  # Optional: CoreML export

Rust Setup

bash
cd rust-src

# Build in release mode (Metal backend on macOS)
cargo build --release

# Build with CUDA support (Linux with NVIDIA GPU)
cargo build --release --features cuda

# Run tests
cargo test

Docker Setup

Development Container (VS Code)

The easiest way to get started is with VS Code Dev Containers:

  1. Install Docker Desktop
  2. Install VS Code Remote - Containers extension
  3. Open this folder in VS Code
  4. Click "Reopen in Container" when prompted

Docker Compose (Multi-Container)

bash
# Development environment
docker compose up deepseek-dev

# Training with GPU
docker compose up deepseek-training

# Multi-GPU training (4 GPUs)
docker compose up deepseek-multi-gpu

# TensorBoard monitoring
docker compose up tensorboard
# Visit http://localhost:6006

# Jupyter notebooks
docker compose up jupyter
# Visit http://localhost:8888

Manual Docker Build

bash
# Build the image
docker build -t deepseek-from-scratch .

# Run with GPU support
docker run --gpus all -it deepseek-from-scratch

# Run with volume mounts
docker run --gpus all -v $(pwd)/data:/app/data -v $(pwd)/checkpoints:/app/checkpoints deepseek-from-scratch

Training Guide

Training Data Setup

bash
# Download TinyStories dataset
uv run python scripts/download_tinystories.py
# Data saved to: data/stories/

Training Options

Option 1: Modal Cloud GPUs (Production Recommended)

Best for: Production training, large-scale experiments

…

GPU Configuration: Standard config uses 8 A100-40GB GPUs with DualPipe (TP=2, PP=2, DP=2). For scaled runs (>8 GPUs), the framework automatically orchestrates sequential 8-GPU batches with checkpointing for fault tolerance.

Option 2: Local MLX (Apple Silicon)

Best for: Local development, quick iterations on Mac

bash
# Memory-conscious config
uv run python -m deepseek.pipeline.cli run --backend mlx --max-steps 1500 --batch-size 2 --d-model 128

# Full config
uv run python -m deepseek.pipeline.cli run --backend mlx --model-size tiny --max-steps 5000

Option 3: Local PyTorch (CPU/CUDA)

Best for: Linux with CUDA, debugging

bash
uv run python -m deepseek.pipeline.cli run --backend pytorch --model-size tiny --max-steps 1000

Training Pipeline Stages

The pipeline orchestrates a complete training workflow:

DATA_PREP → PRETRAIN → SFT → GRPO → DISTILLATION → EXPORT
Stage Description
DATA_PREP Tokenize and shard dataset
PRETRAIN MTP + MoE pretraining
SFT Supervised Fine-Tuning (instruction tuning)
GRPO Group Relative Policy Optimization (alignment)
DISTILLATION Knowledge distillation (optional)
EXPORT Save final model + config

5D Parallelism Configuration

The framework implements DeepSeek-style 5D parallelism:

Dimension Description Default
PP (Pipeline) Splits model layers across GPUs 3
DP (Data) Replicates model, splits data 1
TP (Tensor) Splits layers horizontally 1
EP (Expert) Distributes MoE experts 1
SP (Sequence) Splits long sequences 1

Pipeline Parallelism Architecture (PP=3):

┌──────────────┐   ┌──────────────┐   ┌──────────────┐
│    GPU 0     │──▶│    GPU 1     │──▶│    GPU 2     │
│ Embed+L1-4   │   │   L5-8       │   │ L9-12+Head   │
└──────────────┘   └──────────────┘   └──────────────┘
       ▲                                     │
       └────────── Gradient Flow ◀───────────┘

Model Export

bash
# Export to GGUF format
uv run python scripts/export_gguf.py --checkpoint checkpoints/final

# Export to CoreML (iOS/macOS)
uv run python deepseek-from-scratch-python/export_coreml.py

Run Inference

bash
uv run python scripts/inference.py --checkpoint checkpoints/final --prompt "Once upon a time"

Ablation Studies

We provide comprehensive ablation study infrastructure to analyze component contributions.

Running Ablations

bash
# Run all ablations
uv run python scripts/ablation/run_all_ablations.py --output-dir results/ablations

# Individual ablations
uv run python scripts/ablation/run_attention_ablation.py    # MLA vs GQA vs MHA
uv run python scripts/ablation/run_expert_ablation.py       # 8 vs 64 vs 256 experts
uv run python scripts/ablation/run_balancing_ablation.py    # Aux-loss-free vs aux loss
uv run python scripts/ablation/run_mtp_ablation.py          # MTP depth D=0,1,2,3
uv run python scripts/ablation/run_precision_ablation.py    # FP8 vs BF16 vs FP16

Ablation Results Summary

Study Best Configuration Key Finding
Attention MLA 14× KV cache compression, no quality loss
Experts 256 with K=8 Diminishing returns beyond 256
Balancing Aux-loss-free Cleaner gradients, better convergence
MTP Depth D=1 1.4× speculative decoding speedup
Precision FP8 per-block 2.4× throughput, minimal accuracy loss

Performance Benchmarks

Training Benchmarks (3000 steps)

Backend Hardware Time Steps/sec Final Loss
Rust+GPU 3× H100 80GB ~4 min 13.5 1.18
Python+GPU 3× H100 80GB ~5 min 10.2 1.37
MLX Apple M1/M2/M3 ~15 min 3.3 1.85

Component Benchmarks (Apple Silicon)

Test Config: batch_size=4, seq_len=64, d_model=512

Attention Mechanisms

Component Rust (Metal) Python (MPS) MLX
MQA 11.75ms 0.95ms 0.73ms
GQA 11.00ms 0.54ms 0.82ms
MLA 10.74ms 0.96ms 0.97ms

Mixture of Experts

Component Rust (Metal) Python (MPS) MLX
Standard MoE 5.94ms 134.87ms -
DeepSeek MoE 4.97ms 49.85ms 2.53ms

Training Operations

Component Rust (Metal) Python (MPS) MLX
GRPO Loss 0.04ms 0.73ms 0.66ms
DPO Loss 0.01ms 0.28ms 1.08ms
KD Loss 0.05ms 0.61ms 0.32ms

Running Benchmarks

bash
# PyTorch benchmarks (CUDA/MPS/CPU)
cd deepseek-from-scratch-python
uv run python -m pytest tests/ -v

# MLX benchmarks (Apple Silicon native)
uv run python mlx_impl/benchmark.py

# Rust benchmarks (Metal)
cd Deepseek-from-scratch-in-rust
cargo run --release

Project Structure

…

Architecture Documentation

The docs/ directory contains in-depth explanations of all architectural components:

Attention Mechanisms

  • Multi-Query Attention (MQA)
  • Grouped-Query Attention (GQA)
  • Multi-Head Latent Attention (MLA)
  • DeepSeek Attention

Mixture of Experts

  • Standard MoE
  • DeepSeek MoE

Prediction & Quantization

  • Multi-Token Prediction (MTP)
  • FP8 Quantization

Training & Alignment

  • GRPO
  • Training Infrastructure
  • Training Pipeline
  • Post-Training: SFT & RLHF
  • Knowledge Distillation

Advanced Topics

  • V3.2 Architecture Summary
  • 5D Parallelism
  • ZeRO Optimization
  • Sparse Attention

Blog Posts (Technical Deep-Dives)

  • Multi-Latent Attention Deep Dive
  • Auxiliary-Loss-Free Load Balancing
  • DualPipe Pipeline Parallelism
  • [Expert Specializa

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Python

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言