Chapter 02
安装与最小依赖
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.4 | checkpoint |
| 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这章你需要带走的
- nanotron 装机一行
pip install -e .; - 无外部分布式库(自家用 PyTorch 实现);
- 核心代码 ~5500 行,比同类框架小 10×;
- 可选 flash-attn / wandb。