production ready deepseek R1 and v3.2 implementation in rust and python programming from scratch
production ready deepseek R1 and v3.2 implementation in rust and python programming 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:
…# 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| 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 |
cd DeepSeek-From-Scratch
# Install with UV (fastest)
uv sync
# Or install with all optional extras
uv sync --all-extras # Includes MLX, CoreML, dev toolsAlternative (pip):
pip install torch numpy einops transformers
pip install mlx # Optional: Apple Silicon only
pip install coremltools # Optional: CoreML exportcd 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 testThe easiest way to get started is with VS Code Dev Containers:
# 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# 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# Download TinyStories dataset
uv run python scripts/download_tinystories.py
# Data saved to: data/stories/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.
Best for: Local development, quick iterations on Mac
# 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 5000Best for: Linux with CUDA, debugging
uv run python -m deepseek.pipeline.cli run --backend pytorch --model-size tiny --max-steps 1000The 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 |
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 ◀───────────┘# 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.pyuv run python scripts/inference.py --checkpoint checkpoints/final --prompt "Once upon a time"We provide comprehensive ablation study infrastructure to analyze component contributions.
# 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| 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 |
| 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 |
Test Config: batch_size=4, seq_len=64, d_model=512
| 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 |
| Component | Rust (Metal) | Python (MPS) | MLX |
|---|---|---|---|
| Standard MoE | 5.94ms | 134.87ms | - |
| DeepSeek MoE | 4.97ms | 49.85ms | 2.53ms |
| 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 |
# 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…The docs/ directory contains in-depth explanations of all architectural components:
No open issues yet, or sync has not completed.