Appearance
實驗紀錄
編譯與執行
環境需求
- C 編譯器(gcc / clang / MSVC)
- GNU Make(可選)
- 可選:OpenMP(平行加速)
編譯方式
基本編譯
bash
gcc -O3 -o run run.c -lm快速編譯(推薦)
bash
gcc -Ofast -o run run.c -lmOpenMP 平行加速
bash
clang -Ofast -fopenmp -march=native run.c -lm -o runWindows (MSVC)
bash
# 使用 Visual Studio Command Prompt
build_msvc.bat下載模型
bash
# 15M 參數模型 (~60MB)
wget https://huggingface.co/karpathy/tinyllamas/resolve/main/stories15M.bin
# 42M 參數模型
wget https://huggingface.co/karpathy/tinyllamas/resolve/main/stories42M.bin
# 110M 參數模型
wget https://huggingface.co/karpathy/tinyllamas/resolve/main/stories110M.bin執行推理
bash
# 基本使用
./run stories15M.bin
# 指定溫度、步數、prompt
./run stories42M.bin -t 0.8 -n 256 -i "Once upon a time"
# Top-p 採樣(推薦設定)
./run stories42M.bin -t 1.0 -p 0.9
# 使用 OpenMP 多執行緒
OMP_NUM_THREADS=4 ./run stories15M.bin預期輸出範例
使用 stories15M.bin 的預期輸出:
Once upon a time, there was a little girl named Lily. She loved playing with her toys. One day, she found a magic wand...使用 stories42M.bin 的預期輸出更連貫、更多樣化。
量化推理 (int8)
編譯
bash
gcc -Ofast -o runq runq.c -lm匯出量化模型
bash
python export.py model_q80.bin --version 2 --checkpoint out/model.pt執行量化推理
bash
./runq model_q80.bin -n 40完整訓練流程
1. 下載與前處理資料
bash
python tinystories.py download
python tinystories.py pretokenize2. 訓練(單 GPU debug 模式)
bash
python train.py --compile=False --eval_iters=10 --batch_size=83. 訓練(多 GPU DDP)
bash
torchrun --standalone --nproc_per_node=4 train.py4. C 推理驗證
bash
make run
./run out/model.bin5. Python 推理驗證(比對結果)
bash
python sample.py --checkpoint=out/model.pt自訂 Tokenizer
bash
# 訓練自訂 tokenizer(vocab_size=4096)
python tinystories.py train_vocab --vocab_size=4096
# 使用自訂 tokenizer 前處理
python tinystories.py pretokenize --vocab_size=4096
# 訓練模型
python train.py --vocab_source=custom --vocab_size=4096
# 匯出 tokenizer
python tokenizer.py --tokenizer-model=data/tok4096.model
# C 推理時指定 tokenizer
./run out/model.bin -z data/tok4096.bin執行 Meta Llama 2 7B
bash
# 1. 下載 Meta 官方權重(需申請)
# 2. 轉換為 llama2.c 格式
python export.py llama2_7b.bin --meta-llama /path/to/llama/model/7B
# 3. 推理(建議使用 OpenMP)
make runomp
OMP_NUM_THREADS=64 ./run llama2_7b.bin -n 40
# 4. Chat 模式
python export.py llama2_7b_chat.bin --meta-llama /path/to/7B-chat
./run llama2_7b_chat.bin -m chat測試
bash
# Python 測試
pip install pytest
pytest
# C 測試
make testcc
make testcc VERBOSITY=1常見問題
Q: 編譯時出現 sqrtf 未定義?
A: 連結 -lm(math library):gcc -O3 -o run run.c -lm
Q: Windows 下 mmap 失敗?
A: 使用 build_msvc.bat 或安裝 WSL。
Q: 執行時出現「Couldn't open file」?
A: 確保 .bin 檔案路徑正確。模型檔案需在當前目錄或使用完整路徑。
Q: 如何獲得更好的生成品質?
A: 使用更大的模型(42M > 15M),設定 -t 1.0 -p 0.9,或使用 OpenMP 加速(允許即時互動)。