Chapter 02

安装与最小依赖

📌 commit 2411b02HF 的极简预训练库

nanotron 的设计就是"最小依赖"。本章把它装起来——比绝大多数训练框架都简单。

2.1装机

git clone https://github.com/huggingface/nanotron
cd nanotron
git checkout 2411b02         # 本书基线

# 安装
pip install -e .

# 可选:flash-attn / wandb
pip install flash-attn --no-build-isolation
pip install wandb

2.2依赖矩阵

版本角色
torch>= 2.1底座
transformers>= 4.40仅 tokenizer + 模型 config 读取
datasets>= 2.20数据加载
safetensors>= 0.4checkpoint
flash-attn可选性能
wandb可选日志

无 Megatron-Core、无 Apex、无 DeepSpeed、无 ColossalAI。所有分布式由 nanotron 自己用 PyTorch 原生 API 实现。

2.3仓库结构

nanotron/                          https://github.com/huggingface/nanotron
├── src/nanotron/
│   ├── trainer.py                 ★ 主训练 loop
│   ├── config/                     ★ dataclass 配置
│   │   ├── config.py
│   │   └── ...
│   ├── parallel/
│   │   ├── context.py             ★ ParallelContext
│   │   ├── parameters.py
│   │   ├── pipeline_parallel/
│   │   ├── tensor_parallel/
│   │   ├── data_parallel/
│   │   └── ...
│   ├── models/                     模型实现(Llama / Starcoder2)
│   ├── data/                       Nanoset / blended dataset
│   ├── optim/                      DistributedOptimizer
│   ├── helpers.py
│   └── serialize/                  checkpoint
├── examples/                       配置 + 启动脚本
├── docs/
└── tests/

2.4仓库代码量

$ tokei src/nanotron --exclude tests
================================================================
 Language       Files    Lines     Code  Comments    Blanks
================================================================
 Python           ~80    ~9000    ~5500     ~2000     ~1500
================================================================

核心 Python 代码约 5500 行。比 Megatron 的 50K 小一个数量级。

2.5验证

python -c "import nanotron; print(nanotron.__version__)"

# 跑最小 toy example
torchrun --nproc_per_node=1 run_train.py --config-file examples/config_tiny_llama.yaml

2.6常见装机问题

现象处理
flash-attn 编译失败装预编译 wheel;或先 pip install ninja
torch 太老升 torch ≥ 2.1
datasets 版本冲突pip install -U datasets

2.7这章你需要带走的