Files
wehub-resource-sync 816e440ed3
Check hyperlinks / test (push) Has been cancelled
Deploy MkDocs / deploy (push) Has been cancelled
CPU tests / testing-imports (macOS-14, 3.10) (push) Has been cancelled
CPU tests / testing-imports (ubuntu-22.04, 3.10) (push) Has been cancelled
CPU tests / testing-imports (ubuntu-24.04, 3.10) (push) Has been cancelled
CPU tests / testing-imports (windows-2022, 3.10) (push) Has been cancelled
CPU tests / pytester (macOS-14, 3.10, latest) (push) Has been cancelled
CPU tests / pytester (ubuntu-22.04, 3.10, latest) (push) Has been cancelled
CPU tests / pytester (ubuntu-22.04, 3.10, oldest) (push) Has been cancelled
CPU tests / pytester (ubuntu-22.04, 3.11, latest) (push) Has been cancelled
CPU tests / pytester (ubuntu-22.04, 3.12, latest) (push) Has been cancelled
CPU tests / pytester (ubuntu-22.04, 3.13, latest) (push) Has been cancelled
CPU tests / pytester (windows-2022, 3.10, latest) (push) Has been cancelled
CPU tests / testing-guardian (push) Has been cancelled
docs: make Chinese README the default
2026-07-13 10:45:49 +00:00

31 KiB
Raw Permalink Blame History

Note

本文档由 WeHub 基于上游 README 翻译整理,属于社区翻译,非官方中文文档。
English · 原始项目 · 上游 README
原作者、版权与许可证归属以原始项目及本仓库 LICENSE 文件为准。

LitGPT

20+ 款高性能 LLM,配套配方支持大规模预训练、微调与部署。

✅ 从零实现(from scratch)      ✅ 无抽象层         ✅ 对初学者友好
   ✅ Flash attention                   ✅ FSDP                    ✅ LoRA、QLoRA、Adapter
✅ 降低 GPU 显存占用(fp4/8/16/32   ✅ 1-1000+ GPU/TPU       ✅ 20+ LLM         

PyPI - Python Version cpu-tests license Discord

快速开始模型微调部署全部工作流特性配方(YAMLLightning AI教程

 

Get started

 

需要 GPU

超过 340,000 名开发者使用 Lightning Cloud ——专为 PyTorch 与 PyTorch Lightning 打造。

闪电般快速微调、预训练与推理 LLM

每个 LLM 均从零实现,无抽象层完全可控,在企业级规模下实现极速、精简且高性能。

企业级就绪 - Apache 2.0 许可,可无限制用于企业场景。
开发者友好 - 无抽象层、单文件实现,便于调试。
性能优化 - 模型设计旨在最大化性能、降低成本并加速训练。
经过验证的配方 - 在企业级规模下测试过的高度优化训练/微调配方。

 

快速开始

安装 LitGPT

pip install 'litgpt[extra]'

加载并使用任意一款 20+ LLM

from litgpt import LLM

llm = LLM.load("microsoft/phi-2")
text = llm.generate("Fix the spelling: Every fall, the family goes to the mountains.")
print(text)
# Corrected Sentence: Every fall, the family goes to the mountains.

 

针对快速推理优化
量化(Quantization
可在低显存 GPU 上运行
无内部抽象层
针对生产规模优化

高级安装选项

从源码安装:

git clone https://github.com/Lightning-AI/litgpt
cd litgpt
# if using uv
uv sync --all-extras
# if using pip
pip install -e ".[extra,compiler,test]"

浏览完整 Python API 文档

 


从 20+ LLM 中选择

每个模型均从零编写,以最大化性能并去除抽象层:

模型 模型规模 作者 参考文献
Llama 3, 3.1, 3.2, 3.3 1B, 3B, 8B, 70B, 405B Meta AI Meta AI 2024
Code Llama 7B, 13B, 34B, 70B Meta AI Rozière et al. 2023
CodeGemma 7B Google Google Team, Google Deepmind
Gemma 2 2B, 9B, 27B Google Google Team, Google Deepmind
Phi 4 14B Microsoft Research Abdin et al. 2024
Qwen2.5 0.5B, 1.5B, 3B, 7B, 14B, 32B, 72B Alibaba Group Qwen Team 2024
Qwen2.5 Coder 0.5B, 1.5B, 3B, 7B, 14B, 32B Alibaba Group Hui, Binyuan et al. 2024
R1 Distill Llama 8B, 70B DeepSeek AI DeepSeek AI 2025
... ... ... ...
查看 20+ LLM 完整列表

 

全部模型

模型 模型规模 作者 参考文献
CodeGemma 7B Google Google Team, Google Deepmind
Code Llama 7B, 13B, 34B, 70B Meta AI Rozière et al. 2023
Falcon 7B, 40B, 180B TII UAE TII 2023
Falcon 3 1B, 3B, 7B, 10B TII UAE TII 2024
FreeWilly2 (Stable Beluga 2) 70B Stability AI Stability AI 2023
Function Calling Llama 2 7B Trelis Trelis et al. 2023
Gemma 2B, 7B Google Google Team, Google Deepmind
Gemma 2 9B, 27B Google Google Team, Google Deepmind
Gemma 3 1B, 4B, 12B, 27B Google Google Team, Google Deepmind
Llama 2 7B, 13B, 70B Meta AI Touvron et al. 2023
Llama 3.1 8B, 70B Meta AI Meta AI 2024
Llama 3.2 1B, 3B Meta AI Meta AI 2024
Llama 3.3 70B Meta AI Meta AI 2024
Mathstral 7B Mistral AI Mistral AI 2024
MicroLlama 300M Ken Wang MicroLlama repo
Mixtral MoE 8x7B Mistral AI Mistral AI 2023
Mistral 7B, 123B Mistral AI Mistral AI 2023
Mixtral MoE 8x22B Mistral AI Mistral AI 2024
OLMo 1B, 7B Allen Institute for AI (AI2) Groeneveld et al. 2024
OpenLLaMA 3B, 7B, 13B OpenLM Research Geng & Liu 2023
Phi 1.5 & 2 1.3B, 2.7B Microsoft Research Li et al. 2023
Phi 3 3.8B Microsoft Research Abdin et al. 2024
Phi 4 14B Microsoft Research Abdin et al. 2024
Phi 4 Mini Instruct 3.8B Microsoft Research Microsoft 2025
Phi 4 Mini Reasoning 3.8B Microsoft Research Xu, Peng et al. 2025
Phi 4 Reasoning 3.8B Microsoft Research Abdin et al. 2025
Phi 4 Reasoning Plus 3.8B Microsoft Research Abdin et al. 2025
Platypus 7B, 13B, 70B Lee et al. Lee, Hunter, and Ruiz 2023
Pythia {14,31,70,160,410}M, {1,1.4,2.8,6.9,12}B EleutherAI Biderman et al. 2023
Qwen2.5 0.5B, 1.5B, 3B, 7B, 14B, 32B, 72B Alibaba Group Qwen Team 2024
Qwen2.5 Coder 0.5B, 1.5B, 3B, 7B, 14B, 32B Alibaba Group Hui, Binyuan et al. 2024
Qwen2.5 1M (Long Context) 7B, 14B Alibaba Group Qwen Team 2025
Qwen2.5 Math 1.5B, 7B, 72B Alibaba Group An, Yang et al. 2024
QwQ 32B Alibaba Group Qwen Team 2025
QwQ-Preview 32B Alibaba Group Qwen Team 2024
Qwen3 0.6B, 1.7B, 4B{Hybrid, Thinking-2507, Instruct-2507}, 8B, 14B, 32B Alibaba Group Qwen Team 2025
Qwen3 MoE 30B{Hybrid, Thinking-2507, Instruct-2507}, 235B{Hybrid, Thinking-2507, Instruct-2507} Alibaba Group Qwen Team 2025
R1 Distill Llama 8B, 70B DeepSeek AI DeepSeek AI 2025
SmolLM2 135M, 360M, 1.7B Hugging Face Hugging Face 2024
Salamandra 2B, 7B Barcelona Supercomputing Centre BSC-LTC 2024
StableCode 3B Stability AI Stability AI 2023
StableLM 3B, 7B Stability AI Stability AI 2023
StableLM Zephyr 3B Stability AI Stability AI 2023
TinyLlama 1.1B Zhang et al. Zhang et al. 2023

提示:运行 litgpt download list 命令即可列出所有可用模型。

 


工作流

微调预训练继续预训练评估部署测试

 

使用命令行界面(CLI)在你自己的数据上运行预训练、微调等高级工作流。

所有工作流

安装 LitGPT 后,选择要运行的模型和工作流(微调、预训练、评估、部署等):

# litgpt [action] [model]
litgpt  serve     meta-llama/Llama-3.2-3B-Instruct
litgpt  finetune  meta-llama/Llama-3.2-3B-Instruct
litgpt  pretrain  meta-llama/Llama-3.2-3B-Instruct
litgpt  chat      meta-llama/Llama-3.2-3B-Instruct
litgpt  evaluate  meta-llama/Llama-3.2-3B-Instruct

 


微调 LLM

 

微调(finetuning)是指在预训练 AI 模型基础上,使用针对特定任务或应用定制的小规模专用数据集进一步训练的过程。

 

# 0) setup your dataset
curl -L https://huggingface.co/datasets/ksaw008/finance_alpaca/resolve/main/finance_alpaca.json -o my_custom_dataset.json

# 1) Finetune a model (auto downloads weights)
litgpt finetune microsoft/phi-2 \
  --data JSON \
  --data.json_path my_custom_dataset.json \
  --data.val_split_fraction 0.1 \
  --out_dir out/custom-model

# 2) Test the model
litgpt chat out/custom-model/final

# 3) Deploy the model
litgpt serve out/custom-model/final

阅读完整的微调文档

 


部署 LLM

 

部署预训练或微调后的 LLM,以便在实际应用中使用。部署会自动设置可通过网站或应用访问的 Web 服务器。

# deploy an out-of-the-box LLM
litgpt serve microsoft/phi-2

# deploy your own trained model
litgpt serve path/to/microsoft/phi-2/checkpoint
显示查询服务器的代码:

 

在单独的终端中测试服务器,并将模型 API 集成到你的 AI 产品中:

# 3) Use the server (in a separate Python session)
import requests, json
response = requests.post(
    "http://127.0.0.1:8000/predict",
    json={"prompt": "Fix typos in the following sentence: Example input"}
)
print(response.json()["output"])

阅读完整的部署文档

 


评估 LLM

评估 LLM 以测试其在各类任务上的表现,了解其理解与生成文本的能力。简单来说,我们可以评估它在大学水平化学、编程等方面的表现等(MMLU、Truthful QA 等)。

litgpt evaluate microsoft/phi-2 --tasks 'truthfulqa_mc2,mmlu'

阅读完整的评估文档

 


测试 LLM

 

通过交互式聊天测试模型效果。使用 chat 命令进行聊天、提取嵌入(embeddings)等。

以下示例展示如何使用 Phi-2 LLM:

litgpt chat microsoft/phi-2

>> Prompt: What do Llamas eat?
完整代码:

 

# 1) List all supported LLMs
litgpt download list

# 2) Use a model (auto downloads weights)
litgpt chat microsoft/phi-2

>> Prompt: What do Llamas eat?

某些模型的下载需要额外的访问令牌(access token)。详情请参阅下载文档。

阅读完整的聊天文档

 


预训练 LLM

 

预训练(pretraining)是指在针对特定任务进行微调之前,通过让 AI 模型接触大量数据来训练模型的过程。

显示代码:

 

mkdir -p custom_texts
curl https://www.gutenberg.org/cache/epub/24440/pg24440.txt --output custom_texts/book1.txt
curl https://www.gutenberg.org/cache/epub/26393/pg26393.txt --output custom_texts/book2.txt

# 1) Download a tokenizer
litgpt download EleutherAI/pythia-160m \
  --tokenizer_only True

# 2) Pretrain the model
litgpt pretrain EleutherAI/pythia-160m \
  --tokenizer_dir EleutherAI/pythia-160m \
  --data TextFiles \
  --data.train_data_path "custom_texts/" \
  --train.max_tokens 10_000_000 \
  --out_dir out/custom-model

# 3) Test the model
litgpt chat out/custom-model/final

阅读完整的预训练文档

 


继续预训练 LLM

 

继续预训练(continued pretraining)是另一种微调方式,通过在自定义数据上训练,使已预训练的模型更加专业化:

显示代码:

 

mkdir -p custom_texts
curl https://www.gutenberg.org/cache/epub/24440/pg24440.txt --output custom_texts/book1.txt
curl https://www.gutenberg.org/cache/epub/26393/pg26393.txt --output custom_texts/book2.txt

# 1) Continue pretraining a model (auto downloads weights)
litgpt pretrain EleutherAI/pythia-160m \
  --tokenizer_dir EleutherAI/pythia-160m \
  --initial_checkpoint_dir EleutherAI/pythia-160m \
  --data TextFiles \
  --data.train_data_path "custom_texts/" \
  --train.max_tokens 10_000_000 \
  --out_dir out/custom-model

# 2) Test the model
litgpt chat out/custom-model/final

阅读完整的继续预训练文档

 


前沿特性

前沿优化:Flash Attention v2、通过全分片数据并行(fully-sharded data parallelism)实现的多 GPU 支持、可选 CPU 卸载,以及 TPU 和 XLA 支持
预训练微调部署
通过低精度设置降低算力需求:FP16、BF16 以及 FP16/FP32 混合精度。
通过量化降低内存需求:4 位浮点数、8 位整数和双重量化(double quantization)。
配置文件带来出色的开箱即用性能。
参数高效微调(parameter-efficient finetuning):LoRAQLoRAAdapterAdapter v2
导出为其他流行的模型权重格式。
丰富的热门数据集,适用于预训练微调,并支持自定义数据集
代码清晰易改,便于试验最新研究思路。

 


训练配方

LitGPT 提供经过验证的训练配方(YAML 配置),可在不同条件下训练模型。我们根据在不同训练条件下表现最佳的参数生成了这些配方。

此处浏览所有训练配方。

示例

litgpt finetune \
  --config https://raw.githubusercontent.com/Lightning-AI/litgpt/main/config_hub/finetune/llama-2-7b/lora.yaml
使用配置自定义训练

配置允许你为所有细粒度参数自定义训练,例如:

# The path to the base model's checkpoint directory to load for finetuning. (type: <class 'Path'>, default: checkpoints/stabilityai/stablelm-base-alpha-3b)
checkpoint_dir: checkpoints/meta-llama/Llama-2-7b-hf

# Directory in which to save checkpoints and logs. (type: <class 'Path'>, default: out/lora)
out_dir: out/finetune/qlora-llama2-7b

# The precision to use for finetuning. Possible choices: "bf16-true", "bf16-mixed", "32-true". (type: Optional[str], default: null)
precision: bf16-true

...
示例:LoRA 微调配置

 

# The path to the base model's checkpoint directory to load for finetuning. (type: <class 'Path'>, default: checkpoints/stabilityai/stablelm-base-alpha-3b)
checkpoint_dir: checkpoints/meta-llama/Llama-2-7b-hf

# Directory in which to save checkpoints and logs. (type: <class 'Path'>, default: out/lora)
out_dir: out/finetune/qlora-llama2-7b

# The precision to use for finetuning. Possible choices: "bf16-true", "bf16-mixed", "32-true". (type: Optional[str], default: null)
precision: bf16-true

# If set, quantize the model with this algorithm. See ``tutorials/quantize.md`` for more information. (type: Optional[Literal['nf4', 'nf4-dq', 'fp4', 'fp4-dq', 'int8-training']], default: null)
quantize: bnb.nf4

# How many devices/GPUs to use. (type: Union[int, str], default: 1)
devices: 1

# How many nodes to use. (type: int, default: 1)
num_nodes: 1

# The LoRA rank. (type: int, default: 8)
lora_r: 32

# The LoRA alpha. (type: int, default: 16)
lora_alpha: 16

# The LoRA dropout value. (type: float, default: 0.05)
lora_dropout: 0.05

# Whether to apply LoRA to the query weights in attention. (type: bool, default: True)
lora_query: true

# Whether to apply LoRA to the key weights in attention. (type: bool, default: False)
lora_key: false

# Whether to apply LoRA to the value weights in attention. (type: bool, default: True)
lora_value: true

# Whether to apply LoRA to the output projection in the attention block. (type: bool, default: False)
lora_projection: false

# Whether to apply LoRA to the weights of the MLP in the attention block. (type: bool, default: False)
lora_mlp: false

# Whether to apply LoRA to output head in GPT. (type: bool, default: False)
lora_head: false

# Data-related arguments. If not provided, the default is ``litgpt.data.Alpaca``.
data:
  class_path: litgpt.data.Alpaca2k
  init_args:
    mask_prompt: false
    val_split_fraction: 0.05
    prompt_style: alpaca
    ignore_index: -100
    seed: 42
    num_workers: 4
    download_dir: data/alpaca2k

# Training-related arguments. See ``litgpt.args.TrainArgs`` for details
train:

  # Number of optimizer steps between saving checkpoints (type: Optional[int], default: 1000)
  save_interval: 200

  # Number of iterations between logging calls (type: int, default: 1)
  log_interval: 1

  # Number of samples between optimizer steps across data-parallel ranks (type: int, default: 128)
  global_batch_size: 8

  # Number of samples per data-parallel rank (type: int, default: 4)
  micro_batch_size: 2

  # Number of iterations with learning rate warmup active (type: int, default: 100)
  lr_warmup_steps: 10

  # Number of epochs to train on (type: Optional[int], default: 5)
  epochs: 4

  # Total number of tokens to train on (type: Optional[int], default: null)
  max_tokens:

  # Limits the number of optimizer steps to run (type: Optional[int], default: null)
  max_steps:

  # Limits the length of samples (type: Optional[int], default: null)
  max_seq_length: 512

  # Whether to tie the embedding weights with the language modeling head weights (type: Optional[bool], default: null)
  tie_embeddings:

  #   (type: float, default: 0.0003)
  learning_rate: 0.0002

  #   (type: float, default: 0.02)
  weight_decay: 0.0

  #   (type: float, default: 0.9)
  beta1: 0.9

  #   (type: float, default: 0.95)
  beta2: 0.95

  #   (type: Optional[float], default: null)
  max_norm:

  #   (type: float, default: 6e-05)
  min_lr: 6.0e-05

# Evaluation-related arguments. See ``litgpt.args.EvalArgs`` for details
eval:

  # Number of optimizer steps between evaluation calls (type: int, default: 100)
  interval: 100

  # Number of tokens to generate (type: Optional[int], default: 100)
  max_new_tokens: 100

  # Number of iterations (type: int, default: 100)
  max_iters: 100

# The name of the logger to send metrics to. (type: Literal['wandb', 'tensorboard', 'csv'], default: csv)
logger_name: csv

# The random seed to use for reproducibility. (type: int, default: 1337)
seed: 1337
在 CLI 中覆盖任意参数:
litgpt finetune \
  --config https://raw.githubusercontent.com/Lightning-AI/litgpt/main/config_hub/finetune/llama-2-7b/lora.yaml \
  --lora_r 4

 


项目亮点

LitGPT 为许多出色的 AI 项目、倡议、挑战赛以及企业级应用提供支持。欢迎提交 pull request 申请展示。

📊 SAMBA: Simple Hybrid State Space Models for Efficient Unlimited Context Language Modeling

微软研究人员开展的 Samba 项目基于 LitGPT 代码库构建,将 state space models(状态空间模型)与 sliding window attention(滑动窗口注意力)相结合,性能优于纯状态空间模型。

🏆 NeurIPS 2023 Large Language Model Efficiency Challenge: 1 LLM + 1 GPU + 1 Day

LitGPT 仓库是 NeurIPS 2023 LLM Efficiency Challenge, 的官方入门套件,该竞赛专注于在单块 GPU 上对现有的非指令微调 LLM 进行 24 小时微调。

🦙 TinyLlama: An Open-Source Small Language Model

LitGPT 为 TinyLlama 项目 以及研究论文 TinyLlama: An Open-Source Small Language Model 提供支持。

🍪 MicroLlama: MicroLlama-300M

MicroLlama 是一个 300M 参数的 Llama 模型,在 50B token 上预训练,由 TinyLlama 和 LitGPT 提供支持。

🔬 Pre-training Small Base LMs with Fewer Tokens

研究论文 "Pre-training Small Base LMs with Fewer Tokens", 使用 LitGPT,通过从更大模型继承少量 transformer 块并在远小于大模型所用数据量的数据上训练,来开发更小的 base language model(基础语言模型)。研究表明,这些更小的模型尽管使用的训练数据和资源显著更少,却能与更大模型达到相当性能。

 


社区

我们欢迎所有个人贡献者,无论经验水平或硬件条件如何。你的贡献十分宝贵,我们期待看到你能在这个协作且互助的环境中取得成就。

 

教程

🚀 入门指南
微调,包括 LoRA、QLoRA 和 Adapters
🤖 预训练
💬 模型评估
📘 支持的与自定义数据集
🧹 量化
🤯 处理显存不足(OOM)错误的技巧
🧑🏽‍💻 使用云端 TPU

 


致谢

本实现在 Lit-LLaMA and nanoGPT, 的基础上进行扩展,并由 Lightning Fabric 提供支持。

许可证

LitGPT 在 Apache 2.0 许可证下发布。

引用

如果你在研究中使用 LitGPT,请引用以下工作:

@misc{litgpt-2023,
  author       = {Lightning AI},
  title        = {LitGPT},
  howpublished = {\url{https://github.com/Lightning-AI/litgpt}},
  year         = {2023},
}