litgpt:基于 PyTorch 的大语言模型训练部署项目

20+ high-performance LLMs with recipes to pretrain, finetune and deploy at scale.

分支11Tags30
文件最后提交记录最后更新时间
1 年前
14 天前
4 个月前
4 个月前
3 个月前
15 天前
15 天前
4 个月前
4 个月前
2 个月前
1 年前
14 天前
14 天前
14 天前
14 天前
14 天前

⚡ LitGPT

20+ 高性能大语言模型,附带大规模预训练、微调与部署方案。

✅ 从零开始实现          ✅ 无抽象封装         ✅ 对新手友好
   ✅ Flash 注意力机制               ✅ FSDP 分布式训练              ✅ LoRA、QLoRA、Adapter 微调
✅ 降低 GPU 内存占用(fp4/8/16/32)   ✅ 支持 1-1000+ GPU/TPU       ✅ 20+ 大语言模型         

PyPI - Python Version cpu-tests license Discord

快速开始模型微调部署所有工作流特性训练方案(YAML)Lightning AI教程

 

Get started

 

需要 GPU 资源?

超过 340,000 名开发者正在使用 Lightning Cloud——专为 PyTorch 和 PyTorch Lightning 打造的云平台。

快速微调、预训练和推理大型语言模型 ⚡⚡

每个大型语言模型均从零开始实现,无抽象封装完全可控,确保其在企业级规模下实现极速、精简且高性能的运行。

企业级就绪 - 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.

 

✅ 针对快速推理优化
✅ 量化
✅ 可在低内存 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 余款大语言模型中选择

每个模型均从零开始编写,以最大限度地提升性能并减少抽象层级:

模型 模型规模 作者 参考文献
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 余款模型的完整列表

 

所有模型

模型 模型规模 作者 参考文献
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 命令列出所有可用模型。

 


工作流程

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

 

使用命令行界面运行高级工作流程,例如在您自己的数据上进行预训练或微调。

所有工作流程

安装 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

 


微调大语言模型

 

微调是指以预训练 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"])

阅读完整部署文档

 


评估大语言模型

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

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

阅读完整的评估文档

 


测试 LLM

 

通过交互式聊天测试模型的性能。使用 chat 命令进行聊天、提取嵌入等操作。

以下是使用 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?

某些模型的下载需要额外的访问令牌。你可以在下载文档中了解更多相关信息。

阅读完整的对话文档

 


预训练大语言模型

 

预训练是在人工智能模型针对特定任务进行微调之前,通过让其接触大量数据来对其进行训练的过程。

显示代码:

 

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

阅读完整的预训练文档

 


继续预训练大语言模型

 

继续预训练是另一种微调方式,通过在自定义数据上训练来专门优化已预训练的模型:

显示代码:

 

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、通过完全分片数据并行实现的多 GPU 支持、可选的 CPU 卸载 以及 TPU 和 XLA 支持
预训练微调部署
✅ 通过低精度设置降低计算需求:FP16、BF16 以及 FP16/FP32 混合精度。
✅ 通过 量化 降低内存需求:4 位浮点数、8 位整数和双重量化。
配置文件 确保出色的开箱即用性能。
✅ 参数高效微调: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 项目、计划、挑战赛乃至企业提供支持。如果您希望自己的项目被展示,请提交拉取请求。

📊 SAMBA:用于高效无限上下文语言建模的简单混合状态空间模型

微软研究人员开发的 Samba 项目基于 LitGPT 代码库构建,它将状态空间模型与滑动窗口注意力相结合,性能优于纯状态空间模型。

🏆 NeurIPS 2023 大型语言模型效率挑战赛:1 个 LLM + 1 块 GPU + 1 天

LitGPT 仓库是 NeurIPS 2023 LLM 效率挑战赛 的官方入门工具包。该竞赛的重点是在单块 GPU 上对现有的非指令微调 LLM 进行 24 小时的微调。

🦙 TinyLlama:开源小型语言模型

LitGPT 为 TinyLlama 项目 以及研究论文《TinyLlama:An Open-Source Small Language Model》(https://arxiv.org/abs/2401.02385) 提供了支持。

🍪 MicroLlama:MicroLlama-300M

MicroLlama 是一个 3 亿参数的 Llama 模型,在 500 亿 tokens 上进行预训练,由 TinyLlama 和 LitGPT 提供支持。

🔬 使用更少 Tokens 预训练小型基础语言模型

研究论文《Pre-training Small Base LMs with Fewer Tokens》(https://arxiv.org/abs/2404.08634) 利用 LitGPT,通过从大型模型继承少量 transformer 块并在大型模型所用数据的一小部分上进行训练,来开发更小的基础语言模型。该论文表明,尽管使用的训练数据和资源显著减少,这些小型模型仍能取得与大型模型相当的性能。

 


社区

我们欢迎所有个人贡献者,无论其经验水平或硬件条件如何。您的贡献非常宝贵,我们期待在这个协作互助的环境中看到您的成就。

 

教程

🚀 快速开始
⚡️ 微调,包括 LoRA、QLoRA 和适配器
🤖 预训练
💬 模型评估
📘 支持的数据集与自定义数据集
🧹 量化
🤯 处理内存不足(OOM)错误的技巧
🧑🏽‍💻 使用云 TPU

 


致谢

本实现基于 Lit-LLaMAnanoGPT 进行了扩展,并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},
}

 

项目介绍

在您的数据上预训练、微调并部署20余个大型语言模型。采用前沿技术:闪光注意力机制、全场景分布式训练、4位量化、LoRA等。【此简介由AI生成】

定制我的领域
11813.47 K1.47 K访问 GitHub