当前位置: 首页 > article >正文

LitGPT - 20多个高性能LLM,具有预训练、微调和大规模部署的recipes

文章目录

    • 一、关于 LitGPT
    • 二、快速启动
      • 安装LitGPT
        • 高级安装选项
      • 从20多个LLM中进行选择
    • 三、工作流程
      • 1、所有工作流程
      • 2、微调LLM
      • 3、部署LLM
      • 4、评估LLM
      • 5、测试LLM
      • 6、预训练LLM
      • 7、继续预训练LLM
    • 四、最先进的功能
    • 五、训练方法
      • 示例
    • 六、项目亮点
    • 教程


一、关于 LitGPT

LitGPT 用于 使用、微调、预训练和部署LLM Lightning快速⚡⚡

每个LLM都是从头开始实现的,没有抽象和完全控制,使它们在企业规模上非常快速、最小化和高性能。

  • github : https://github.com/Lightning-AI/litgpt
  • 快速启动•模型•Finetune•部署•所有工作流程•功能•配方(YAML)•闪电AI•教程

✅**企业就绪-**Apache 2.0可无限企业使用。

✅**开发人员友好-**无需抽象层和单个文件实现即可轻松调试。

✅**优化性能-**旨在最大化性能、降低成本和加快训练速度的模型。

✅**经过验证的配方-**在企业规模测试的高度优化的训练/微调配方。

✅ From scratch implementations     ✅ No abstractions    ✅ Beginner friendly   
✅ Flash attention                  ✅ FSDP               ✅ LoRA, QLoRA, Adapter
✅ Reduce GPU memory (fp4/8/16/32)  ✅ 1-1000+ GPUs/TPUs  ✅ 20+ LLMs            

二、快速启动

安装LitGPT

pip install 'litgpt[all]'

加载和使用20+LLM中的任何一个:

from litgpt import LLM

llm = LLM.load("microsoft/phi-2")
text = llm.generate("Fix the spelling: Every fall, the familly 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
pip install -e '.[all]'

探索完整的Python API文档。


从20多个LLM中进行选择

每个模型都是从头开始编写的,以最大限度地提高性能并删除抽象层:

ModelModel sizeAuthorReference
Llama 3, 3.1, 3.21B, 3B, 8B, 70B, 405BMeta AIMeta AI 2024
Code Llama7B, 13B, 34B, 70BMeta AIRozière et al. 2023
Mixtral MoE8x7B, 8x22BMistral AIMistral AI 2023
Mistral7B, 123BMistral AIMistral AI 2023
CodeGemma7BGoogleGoogle Team, Google Deepmind
Gemma 22B, 9B, 27BGoogleGoogle Team, Google Deepmind
Phi 3 & 3.53.8BMicrosoftAbdin et al. 2024

三、工作流程

Finetune•预训练•持续预训练•评估•部署•测试

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


1、所有工作流程

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

# ligpt [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


2、微调LLM

Run on Studios : https://lightning.ai/lightning-ai/studios/litgpt-finetune

微调是采用预训练的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

阅读完整的微调文档



3、部署LLM

Deploy on Studios : https://lightning.ai/lightning-ai/studios/litgpt-serve

部署预训练或微调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: Exampel input"}
)
print(response.json()["output"])

阅读完整的部署文档。



4、评估LLM

评估一个LLM来测试它在各种任务上的表现,看看它理解和生成文本的程度。简单地说,我们可以评估它在大学水平的化学、编码等方面的表现…(MMLU、真实质量保证等…)

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

阅读完整的评估文档。



5、测试LLM

Run on Studios : <https://lightning.ai/lightning-ai/studios/litgpt-chat)

通过交互式聊天测试模型的工作情况。使用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?

某些型号的下载需要额外的访问令牌。您可以在下载文档中信息。

阅读完整的聊天文档。



6、预训练LLM

Run on Studios : https://lightning.ai/lightning-ai/studios/litgpt-pretrain

预训练是在针对特定任务进行微调之前通过将AI模型暴露于大量数据来教授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

阅读完整的预训练文档



7、继续预训练LLM

Run on Studios : <https://lightning.ai/lightning-ai/studios/litgpt-continue-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

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


四、最先进的功能

✅最先进的优化:闪存注意力v2、通过完全分片数据并行支持多GPU、可选CPU卸载以及TPU和XLA支持。

✅预训练、微调和部署

✅通过低精度设置降低计算要求:FP16、BF16和FP16/FP32混合。

✅通过量化降低内存需求:4位浮点数、8位整数和双重量化。

✅配置文件具有出色的开箱即用性能。

✅参数高效微调:LoRA、QLoRA、Adapter和Adapter 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:开源小语言模型研究论文。
  • 🍪MicroLlama:MicroLlama-300M
    MicroLlama是在TinyLlama和LitGPT支持的50Btoken 上预训练的300M骆驼模型。
  • 🔬预训练较少token 的小型基本LM

研究论文“预训练具有更少令牌的小型基本LM”利用LitGPT,通过从较大模型继承一些转换器块并对较大模型使用的一小部分数据进行训练来开发较小的基本语言模型。它证明,尽管使用的训练数据和资源明显较少,但这些较小的模型可以与较大的模型相比。


教程

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


2025-01-27(一)


http://www.kler.cn/a/526767.html

相关文章:

  • (动态规划基础 打家劫舍)leetcode 198
  • origin如何在已经画好的图上修改数据且不改变原图像的画风和格式
  • UE5.3 C++ CDO的初步理解
  • GitHub Actions定时任务配置完全指南:从Cron语法到实战示例
  • 中国股市“慢牛”行情的实现路径与展望
  • Vuex中的getter和mutation有什么区别
  • 电子电气架构 --- 在智能座舱基础上定义人机交互
  • 题单:冒泡排序1
  • Java根据端口范围关闭Appium服务
  • Java设计模式:行为型模式→责任链模式
  • 什么是Maxscript?为什么要学习Maxscript?
  • 数据结构之单链表(超详解)
  • 穷举vs暴搜vs深搜vs回溯vs剪枝系列一>解数独
  • 《一文读懂!Q-learning状态-动作值函数的直观理解》
  • win32汇编环境,窗口程序中使用滚动条控件的一般操作
  • AI 模型优化与性能调优
  • 芯片AI深度实战:进阶篇之vim内verilog实时基于AST的自定义检视
  • springboot集成钉钉,发送钉钉日报
  • 【Block总结】高效多尺度注意力EMA,超越SE、CBAM、SA、CA等注意力|即插即用
  • RK3568 opencv播放视频
  • 第23节课:前端调试技巧—掌握浏览器开发者工具与性能优化
  • 理解PLT表和GOT表
  • 新春登蛇山:告别岁月,启航未来
  • LeetCode 0219.存在重复元素 II:哈希表
  • 【Leetcode刷题记录】166. 分数到小数
  • [EAI-022] FuSe,在VLA模型基础上,融合触觉和语音等异构模态信息