首次使用 LLM.load 会从 Hugging Face 下载模型权重,需联网并预留磁盘空间;完整功能需安装 extra 依赖,从源码安装还需额外 compiler、test 等 extras。
litgpt
Lightning-AIApache-2.0活跃维护提供 20 多个高性能大语言模型的训练配方,覆盖预训练、微调和规模化部署全流程,适合想快速上手 LLM 训练与推理的开发者。
20+ high-performance LLMs with recipes to pretrain, finetune and deploy at scale.
pip install 'litgpt[extra]'README 未给出具体显存数值;支持 GPU 与 TPU,可扩展至 1-1000+ 设备,并称可在低显存 GPU 上运行(含量化)。
从零实现 20+ 主流 LLM 的预训练、微调与部署工具,无抽象层、可读可控
提供 20 多个高性能大语言模型的训练配方,覆盖预训练、微调和规模化部署全流程,适合想快速上手 LLM 训练与推理的开发者。
核心能力
- 从零实现 20+ LLM,单文件无抽象层便于调试
- 支持 LoRA、QLoRA、Adapter 等参数高效微调
- 集成 Flash Attention 与 FSDP,支持 1 到 1000+ GPU/TPU
- 支持 fp4/8/16/32 量化以降低显存占用
- 提供 YAML 训练配方与 Python API 直接加载生成
容易踩的坑
- v0.5.13最新正式版2026-06-29 · 2026-06-29 15:53 UTC
What's Changed
- chore: fetch transformers version from lightning-thunder requirements, for gpu test by @bhimrazy in https://github.com/Lightning-AI/litgpt/pull/2184
- build(deps): update huggingface-hub requirement from >=0.30,<0.35 to >=0.30,<1.3 by @dependabot[bot] in https://github.com/Lightning-AI/litgpt/pull/2139
- build(deps-dev): bump litdata from 0.2.51 to 0.2.59 by @dependabot[bot] in https://github.com/Lightning-AI/litgpt/pull/2176
- [pre-commit.ci] pre-commit suggestions by @pre-commit-ci[bot] in https://github.com/Lightning-AI/litgpt/pull/2180
- Doc: add uv options advanced installation fix by @sanggusti in https://github.com/Lightning-AI/litgpt/pull/2185
- Fix rope_cache_length computation for models with rope_local_base_freq by @adi776borate in https://github.com/Lightning-AI/litgpt/pull/2179
- feat: add generate_strategy option to litgpt serve by @adi776borate in https://github.com/Lightning-AI/litgpt/pull/2188
- fix: gemma-3 checkpoint conversion from litgpt to hf by @adi776borate in https://github.com/Lightning-AI/litgpt/pull/2195
- Allow train.max_steps for profiling runs by @MukeshK17 in https://github.com/Lightning-AI/litgpt/pull/2193
- build(deps-dev): update bitsandbytes requirement from <0.43,>=0.42 to >=0.42,<0.50 by @dependabot[bot] in https://github.com/Lightning-AI/litgpt/pull/2199
- build(deps): update huggingface-hub requirement from <1.3,>=0.30 to >=0.30,<1.4 by @dependabot[bot] in https://github.com/Lightning-AI/litgpt/pull/2200
- feat(logger) : Add LitLogger Support for Lightning.ai Experiment Tracking by @bhimrazy in https://github.com/Lightning-AI/litgpt/pull/2198
- fix: correct LoRA index computation uses wrong feature size by @Mr-Neutr0n in https://github.com/Lightning-AI/litgpt/pull/2201
- fix: default val_split_fraction to 0.05 for single-file JSON data by @dario-fumarola in https://github.com/Lightning-AI/litgpt/pull/2204
- fix: flaky
test_litgpt_chat_endtoendby @bhimrazy in https://github.com/Lightning-AI/litgpt/pull/2209 - chore(workflows): Sync GPU CI workflow image with lightning-thunder repo by @bhimrazy in https://github.com/Lightning-AI/litgpt/pull/2208
- Add YaRN rope adjustment + DeepSeekV3 rope_interleave by @ysjprojects in https://github.com/Lightning-AI/litgpt/pull/2202
- fix: handle empty prompt list in R1Base.apply() by @LincolnBurrows2017 in https://github.com/Lightning-AI/litgpt/pull/2216
- Added correct rope_base to all Mistral configs by @adi776borate in https://github.com/Lightning-AI/litgpt/pull/2218
- chore(ruff): bump target-version to py310 and update type annotations by @bhimrazy in https://github.com/Lightning-AI/litgpt/pull/2221
- fix: raise error when prefill exceeds sliding window KV cache size by @alvinttang in https://github.com/Lightning-AI/litgpt/pull/2215
- LoRAQKVLinear.lora_ind does not cache index by @mseeger in https://github.com/Lightning-AI/litgpt/pull/2225
- feat: Introduce a pre-flight validation script for LitGPT checkpoints… by @OnePunchMonk in https://github.com/Lightning-AI/litgpt/pull/2214
- build(deps): bump psutil from 7.1.3 to 7.2.2 by @dependabot[bot] in https://github.com/Lightning-AI/litgpt/pull/2226
- [pre-commit.ci] pre-commit suggestions by @pre-commit-ci[bot] in https://github.com/Lightning-AI/litgpt/pull/2229
- fix(finetune): run generate_example only on rank 0 in multi-GPU training by @Br1an67 in https://github.com/Lightning-AI/litgpt/pull/2213
- fix(tests): Fix 3 test failures introduced by the validate PR by @bhimrazy in https://github.com/Lightning-AI/litgpt/pull/2233
- fix: make sample() produce greedy decoding when temperature=0 by @CrepuscularIRIS in https://github.com/Lightning-AI/litgpt/pull/2239
- fix(tests): xfail DynamoThunder tests with torch>=2.12 by @bhimrazy in https://github.com/Lightning-AI/litgpt/pull/2254
- security: remove
pull_request_targettrigger from CPU tests workflow by @bhimrazy in https://github.com/Lightning-AI/litgpt/pull/2253 - chore: pin GitHub Actions to veri
- v0.5.122025-12-18 · 2025-12-18 15:51 UTC
查看更新说明
What's Changed
- fix: update TinyStories optimize to use
item_loader=TokensLoader()by @bhimrazy in https://github.com/Lightning-AI/litgpt/pull/2148 - [FEAT] Add Grouped Topk Routing to LLaMAMoE (Based on DeepseekV3MoE) by @ysjprojects in https://github.com/Lightning-AI/litgpt/pull/2134
- Add
timeoutparameter to run_server. by @hv10 in https://github.com/Lightning-AI/litgpt/pull/2157 - fix: chat prompt lowercasing bug by @bhimrazy in https://github.com/Lightning-AI/litgpt/pull/2155
- chore: Drop Python 3.9 support from ci by @bhimrazy in https://github.com/Lightning-AI/litgpt/pull/2161
- fix: handle gemma 3 weights prefix during hf conversion by @scascar in https://github.com/Lightning-AI/litgpt/pull/2156
- Fix to avoid RuntimeError by @mseeger in https://github.com/Lightning-AI/litgpt/pull/2138
- fix: pin
lm-eval<0.4.9.1for trust_remote_code issue by @bhimrazy in https://github.com/Lightning-AI/litgpt/pull/2168 - Small refactorings by @mseeger in https://github.com/Lightning-AI/litgpt/pull/2166
- docs: enhance Python API tutorial with fixes and new section by @carsch18 in https://github.com/Lightning-AI/litgpt/pull/2169
- fix: sliding window KV cache for Gemma-3 models (issue #2145) by @Chelsi-create in https://github.com/Lightning-AI/litgpt/pull/2153
New Contributors
- @lianakoleva made their first contribution in https://github.com/Lightning-AI/litgpt/pull/2132
- @hv10 made their first contribution in https://github.com/Lightning-AI/litgpt/pull/2157
- @scascar made their first contribution in https://github.com/Lightning-AI/litgpt/pull/2156
- @carsch18 made their first contribution in https://github.com/Lightning-AI/litgpt/pull/2169
- @Chelsi-create made their first contribution in https://github.com/Lightning-AI/litgpt/pull/2153
Full Changelog: https://github.com/Lightning-AI/litgpt/compare/v0.5.11...v0.5.12
- fix: update TinyStories optimize to use
- v0.5.112025-09-09 · 2025-09-09 18:15 UTC
查看更新说明
What's Changed
- Add Qwen3 2507 Thinking models by @ysjprojects in https://github.com/Lightning-AI/litgpt/pull/2110
- Add MLA by @ysjprojects in https://github.com/Lightning-AI/litgpt/pull/2113
- Add Qwen3 2507 Instruct models by @ysjprojects in https://github.com/Lightning-AI/litgpt/pull/2125
- finetune_lora upgrades by @ysjprojects in https://github.com/Lightning-AI/litgpt/pull/2086
- Use torch autograd integration for backward testing by @t-vi in https://github.com/Lightning-AI/litgpt/pull/2123
- bump PT 2.8 & install with
--upgrade-strategy greedyby @Borda in https://github.com/Lightning-AI/litgpt/pull/2107 - build(deps): update transformers requirement from <4.54,>=4.51.3 to >=4.51.3,<4.57 by @dependabot[bot] in https://github.com/Lightning-AI/litgpt/pull/2120
- build(deps): update huggingface-hub requirement from <0.33,>=0.30 to >=0.30,<0.35 by @dependabot[bot] in https://github.com/Lightning-AI/litgpt/pull/2119
- build(deps): update bitsandbytes requirement from <0.43,>=0.42 to >=0.42,<0.47 by @dependabot[bot] in https://github.com/Lightning-AI/litgpt/pull/2069
Full Changelog: https://github.com/Lightning-AI/litgpt/compare/v0.5.10...v0.5.11
- v0.5.102025-08-13 · 2025-08-13 13:26 UTC
查看更新说明
What's Changed
- qwen2.5 long context by @ysjprojects in https://github.com/Lightning-AI/litgpt/pull/1933
- debug installing
torchfor Thunder by @Borda in https://github.com/Lightning-AI/litgpt/pull/2072 - Fix in
convert_hf_checkpointrelated to Gemma 3 by @mseeger in https://github.com/Lightning-AI/litgpt/pull/2062 - debug some failing standalone tests with compiler by @Borda in https://github.com/Lightning-AI/litgpt/pull/2075
- Qwen3 MoE by @ysjprojects in https://github.com/Lightning-AI/litgpt/pull/2060
- Deferring import of torch in config to allow faster import by @JackUrb in https://github.com/Lightning-AI/litgpt/pull/2079
- update bug-report/issue with reproducing in Studio by @Borda in https://github.com/Lightning-AI/litgpt/pull/2081
- ci: show the longest tests for improvement by @Borda in https://github.com/Lightning-AI/litgpt/pull/2083
- docs: Add documentation for OpenAI-compatible API in LitGPT deployment by @bhimrazy in https://github.com/Lightning-AI/litgpt/pull/2082
- doc: add
n_query_groupsto attention notation table by @raishish in https://github.com/Lightning-AI/litgpt/pull/2092 - doc: add comments for clarifying query / KV groups by @raishish in https://github.com/Lightning-AI/litgpt/pull/2093
- Complete pending todos in testing by @raishish in https://github.com/Lightning-AI/litgpt/pull/2088
- pin: restrict datasets version to <4.0.0 for compatibility by @Borda in https://github.com/Lightning-AI/litgpt/pull/2095
- add/debug Lit CI by @Borda in https://github.com/Lightning-AI/litgpt/pull/2094
- add
api_pathparameter to cli options to allow custom API endpoint configuration by @botirk38 in https://github.com/Lightning-AI/litgpt/pull/2080 - Fix commands in pretrain.md by @H4kor in https://github.com/Lightning-AI/litgpt/pull/2097
New Contributors
- @JackUrb made their first contribution in https://github.com/Lightning-AI/litgpt/pull/2079
- @raishish made their first contribution in https://github.com/Lightning-AI/litgpt/pull/2092
- @botirk38 made their first contribution in https://github.com/Lightning-AI/litgpt/pull/2080
- @H4kor made their first contribution in https://github.com/Lightning-AI/litgpt/pull/2097
Full Changelog: https://github.com/Lightning-AI/litgpt/compare/v0.5.9...v0.5.10
- v0.5.92025-06-12 · 2025-06-12 20:51 UTC
查看更新说明
What's Changed
- input_pos_maxp1 as a Python integer by @Andrei-Aksionov in https://github.com/Lightning-AI/litgpt/pull/2016
- add testing for py3.12 & py3.13 by @Borda in https://github.com/Lightning-AI/litgpt/pull/2025
- ci: update guardian for PRs by @Borda in https://github.com/Lightning-AI/litgpt/pull/2043
- Add devcontainer by @twsl in https://github.com/Lightning-AI/litgpt/pull/2035
- Remove dependency from config to utils by @lukemerrick in https://github.com/Lightning-AI/litgpt/pull/2034
- fix: Add fallback chat template by @andyland in https://github.com/Lightning-AI/litgpt/pull/2040
- Add optional sys prompt by @twsl in https://github.com/Lightning-AI/litgpt/pull/2036
- fix: Pretraining text files with recent litdata versions by @andyland in https://github.com/Lightning-AI/litgpt/pull/2048
- tests: mark
test_evaluate_scriptas flaky by @Borda in https://github.com/Lightning-AI/litgpt/pull/2049 - simplify the GPU testing flow by @Borda in https://github.com/Lightning-AI/litgpt/pull/2053
- ci: extend testing with
ubuntu-24.04by @Borda in https://github.com/Lightning-AI/litgpt/pull/2056 - Remove litserve version constraint by @twsl in https://github.com/Lightning-AI/litgpt/pull/2055
- req: pin
bitsandbytes>=0.45.2,<0.45.5by @Borda in https://github.com/Lightning-AI/litgpt/pull/2057 - ci: use Thunder dev images for testing by @Borda in https://github.com/Lightning-AI/litgpt/pull/2054
- Update spacing in README.md by @Borda in https://github.com/Lightning-AI/litgpt/pull/2058
- Transformers version bump by @KaelanDt in https://github.com/Lightning-AI/litgpt/pull/2029
- Qwen3 Dense by @ysjprojects in https://github.com/Lightning-AI/litgpt/pull/2044
- phi-4 reasoning models by @ysjprojects in https://github.com/Lightning-AI/litgpt/pull/2047
- adding logger args by @ysjprojects in https://github.com/Lightning-AI/litgpt/pull/1973
- Qwen3 MoE Preliminary: add intermediate_size argument to MLP modules by @ysjprojects in https://github.com/Lightning-AI/litgpt/pull/2046
- OLMo 2 by @ysjprojects in https://github.com/Lightning-AI/litgpt/pull/1897
- bump: testing with PT 2.7.1 by @Borda in https://github.com/Lightning-AI/litgpt/pull/2063
- Add Dependabot for Pip & GitHub Actions by @Borda in https://github.com/Lightning-AI/litgpt/pull/2066
- build(deps): bump litdata from 0.2.45 to 0.2.49 by @dependabot in https://github.com/Lightning-AI/litgpt/pull/2068
New Contributors
- @twsl made their first contribution in https://github.com/Lightning-AI/litgpt/pull/2035
- @lukemerrick made their first contribution in https://github.com/Lightning-AI/litgpt/pull/2034
- @prabhuteja12 made their first contribution in https://github.com/Lightning-AI/litgpt/pull/2027
- @andyland made their first contribution in https://github.com/Lightning-AI/litgpt/pull/2040
- @KaelanDt made their first contribution in https://github.com/Lightning-AI/litgpt/pull/2029
Full Changelog: https://github.com/Lightning-AI/litgpt/compare/v0.5.8...v0.5.9
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。
⚡ LitGPT
20+ high-performance LLMs with recipes to pretrain, finetune, and deploy at scale.
Looking for GPUs?
Over 340,000 developers use Lightning Cloud - purpose-built for PyTorch and PyTorch Lightning.
- GPUs from $0.19.
- Clusters: frontier-grade training/inference clusters.
- AI Studio (vibe train): workspaces where AI helps you debug, tune and vibe train.
- AI Studio (vibe deploy): workspaces where AI helps you optimize, and deploy models.
- Notebooks: Persistent GPU workspaces where AI helps you code and analyze.
- Inference: Deploy models as inference APIs.
Finetune, pretrain, and inference LLMs Lightning fast ⚡⚡
Every LLM is implemented from scratch with no abstractions and full control, making them blazing fast, minimal, and performant at enterprise scale.
✅ Enterprise ready - Apache 2.0 for unlimited enterprise use. ✅ Developer friendly - Easy debugging with no abstraction layers and single file implementations. ✅ Optimized performance - Models designed to maximize performance, reduce costs, and speed up training. ✅ Proven recipes - Highly-optimized training/finetuning recipes tested at enterprise scale.
Quick start
Install LitGPT
pip install 'litgpt[extra]'
Load and use any of the 20+ LLMs:
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.
✅ Optimized for fast inference ✅ Quantization ✅ Runs on low-memory GPUs ✅ No layers of internal abstractions ✅ Optimized for production scale
Install from source:
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]"
Explore the full Python API docs.
Choose from 20+ LLMs
Every model is written from scratch to maximize performance and remove layers of abstraction:
| Model | Model size | Author | Reference |
|---|---|---|---|
| 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 Team, Google Deepmind | |
| Gemma 2 | 2B, 9B, 27B | 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 |
| ... | ... | ... | ... |
All models
| Model | Model size | Author | Reference |
|---|---|---|---|
| CodeGemma | 7B | 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 Team, Google Deepmind | |
| Gemma 2 | 9B, 27B | Google Team, Google Deepmind | |
| Gemma 3 | 1B, 4B, 12B, 27B | 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 |
| R1 Distill Qwen | 1.5B, 7B, 14B, 32B | 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 |
Tip: You can list all available models by running the litgpt download list command.
Workflows
Use the command line interface to run advanced workflows such as pretraining or finetuning on your own data.
All workflows
After installing LitGPT, select the model and workflow to run (finetune, pretrain, evaluate, deploy, etc...):
# 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
Finetune an LLM
Finetuning is the process of taking a pretrained AI model and further training it on a smaller, specialized dataset tailored to a specific task or application.
# 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
Deploy an LLM
Deploy a pretrained or finetuned LLM to use it in real-world applications. Deploy automatically sets up a web server that can be accessed by a website or app.
# 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
Test the server in a separate terminal and integrate the model API into your AI product:
# 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"])
Evaluate an LLM
Evaluate an LLM to test its performance on various tasks to see how well it understands and generates text. Simply put, we can evaluate things like how well it would do in college-level chemistry, coding, etc... (MMLU, Truthful QA, etc...)
litgpt evaluate microsoft/phi-2 --tasks 'truthfulqa_mc2,mmlu'
Read the full evaluation docs.
Test an LLM
Test how well the model works via an interactive chat. Use the chat command to chat, extract embeddings, etc...
Here's an example showing how to use the 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?
The download of certain models requires an additional access token. You can read more about this in the download documentation.
Pretrain an LLM
Pretraining is the process of teaching an AI model by exposing it to a large amount of data before it is fine-tuned for specific tasks.
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
Read the full pretraining docs
Continue pretraining an LLM
Continued pretraining is another way of finetuning that specializes an already pretrained model by training on custom data:
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
Read the full continued pretraining docs
State-of-the-art features
✅ State-of-the-art optimizations: Flash Attention v2, multi-GPU support via fully-sharded data parallelism, optional CPU offloading, and TPU and XLA support. ✅ Pretrain, finetune, and deploy ✅ Reduce compute requirements with low-precision settings: FP16, BF16, and FP16/FP32 mixed. ✅ Lower memory requirements with quantization: 4-bit floats, 8-bit integers, and double quantization. ✅ Configuration files for great out-of-the-box performance. ✅ Parameter-efficient finetuning: LoRA, QLoRA, Adapter, and Adapter v2. ✅ Exporting to other popular model weight formats. ✅ Many popular datasets for pretraining and finetuning, and support for custom datasets. ✅ Readable and easy-to-modify code to experiment with the latest research ideas.
Training recipes
LitGPT comes with validated recipes (YAML configs) to train models under different conditions. We've generated these recipes based on the parameters we found to perform the best for different training conditions.
Browse all training recipes here.
Example
litgpt finetune \
--config https://raw.githubusercontent.com/Lightning-AI/litgpt/main/config_hub/finetune/llama-2-7b/lora.yaml
Configs let you customize training for all granular parameters like:
# 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
...
# 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
litgpt finetune \
--config https://raw.githubusercontent.com/Lightning-AI/litgpt/main/config_hub/finetune/llama-2-7b/lora.yaml \
--lora_r 4
Project highlights
LitGPT powers many great AI projects, initiatives, challenges and of course enterprises. Please submit a pull request to be considered for a feature.
The Samba project by researchers at Microsoft is built on top of the LitGPT code base and combines state space models with sliding window attention, which outperforms pure state space models.
The LitGPT repository was the official starter kit for the NeurIPS 2023 LLM Efficiency Challenge, which is a competition focused on finetuning an existing non-instruction tuned LLM for 24 hours on a single GPU.
LitGPT powered the TinyLlama project and TinyLlama: An Open-Source Small Language Model research paper.
MicroLlama is a 300M Llama model pretrained on 50B tokens powered by TinyLlama and LitGPT.
The research paper "Pre-training Small Base LMs with Fewer Tokens", which utilizes LitGPT, develops smaller base language models by inheriting a few transformer blocks from larger models and training on a tiny fraction of the data used by the larger models. It demonstrates that these smaller models can perform comparably to larger models despite using significantly less training data and resources.
Community
We welcome all individual contributors, regardless of their level of experience or hardware. Your contributions are valuable, and we are excited to see what you can accomplish in this collaborative and supportive environment.
Tutorials
🚀 Get started ⚡️ Finetuning, incl. LoRA, QLoRA, and Adapters 🤖 Pretraining 💬 Model evaluation 📘 Supported and custom datasets 🧹 Quantization 🤯 Tips for dealing with out-of-memory (OOM) errors 🧑🏽💻 Using cloud TPUs
Acknowledgments
This implementation extends on Lit-LLaMA and nanoGPT, and it's powered by Lightning Fabric ⚡.
- @karpathy for nanoGPT
- @EleutherAI for GPT-NeoX and the Evaluation Harness
- @TimDettmers for bitsandbytes
- @Microsoft for LoRA
- @tridao for Flash Attention 2
License
LitGPT is released under the Apache 2.0 license.
Citation
If you use LitGPT in your research, please cite the following work:
@misc{litgpt-2023,
author = {Lightning AI},
title = {LitGPT},
howpublished = {\url{https://github.com/Lightning-AI/litgpt}},
year = {2023},
}