llama3入门训练和部署

教程一

https://www.youtube.com/watch?v=oxTVzGwKeoU

https://www.youtube.com/watch?v=oxTVzGwKeoU

  1. 下载 alpaca 数据集(斯坦福大学的数据集,通过gpt 转换成)
    https://huggingface.co/datasets/shibing624/alpaca-zh
  2. 将自己的数据集json 添加到上面下载的数据集中
  3. 使用 unsloth 进行微调 python app.py
    训练后的模型训练为 gguf 格式
python 复制代码
from unsloth import FastLanguageModel
import torch

from trl import SFTTrainer
from transformers import TrainingArguments




max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.

# 4bit pre quantized models we support for 4x faster downloading + no OOMs.
fourbit_models = [
    "unsloth/mistral-7b-bnb-4bit",
    "unsloth/mistral-7b-instruct-v0.2-bnb-4bit",
    "unsloth/llama-2-7b-bnb-4bit",
    "unsloth/gemma-7b-bnb-4bit",
    "unsloth/gemma-7b-it-bnb-4bit", # Instruct version of Gemma 7b
    "unsloth/gemma-2b-bnb-4bit",
    "unsloth/gemma-2b-it-bnb-4bit", # Instruct version of Gemma 2b
    "unsloth/llama-3-8b-bnb-4bit", # [NEW] 15 Trillion token Llama-3
] # More models at https://huggingface.co/unsloth

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name = "unsloth/llama-3-8b-bnb-4bit",
    max_seq_length = max_seq_length,
    dtype = dtype,
    load_in_4bit = load_in_4bit,
    # token = "hf_...", # use one if using gated models like meta-llama/Llama-2-7b-hf
)

model = FastLanguageModel.get_peft_model(
    model,
    r = 16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
    target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
                      "gate_proj", "up_proj", "down_proj",],
    lora_alpha = 16,
    lora_dropout = 0, # Supports any, but = 0 is optimized
    bias = "none",    # Supports any, but = "none" is optimized
    # [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes!
    use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context
    random_state = 3407,
    use_rslora = False,  # We support rank stabilized LoRA
    loftq_config = None, # And LoftQ
)

alpaca_prompt = """Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.

### Instruction:
{}

### Input:
{}

### Response:
{}"""

EOS_TOKEN = tokenizer.eos_token # Must add EOS_TOKEN
def formatting_prompts_func(examples):
    instructions = examples["instruction"]
    inputs       = examples["input"]
    outputs      = examples["output"]
    texts = []
    for instruction, input, output in zip(instructions, inputs, outputs):
        # Must add EOS_TOKEN, otherwise your generation will go on forever!
        text = alpaca_prompt.format(instruction, input, output) + EOS_TOKEN
        texts.append(text)
    return { "text" : texts, }
pass

from datasets import load_dataset

file_path = "/home/Ubuntu/alpaca_gpt4_data_zh.json"


dataset = load_dataset("json", data_files={"train": file_path}, split="train")

dataset = dataset.map(formatting_prompts_func, batched = True,)




trainer = SFTTrainer(
    model = model,
    tokenizer = tokenizer,
    train_dataset = dataset,
    dataset_text_field = "text",
    max_seq_length = max_seq_length,
    dataset_num_proc = 2,
    packing = False, # Can make training 5x faster for short sequences.
    args = TrainingArguments(
        per_device_train_batch_size = 2,
        gradient_accumulation_steps = 4,
        warmup_steps = 5,
        max_steps = 60,
        learning_rate = 2e-4,
        fp16 = not torch.cuda.is_bf16_supported(),
        bf16 = torch.cuda.is_bf16_supported(),
        logging_steps = 1,
        optim = "adamw_8bit",
        weight_decay = 0.01,
        lr_scheduler_type = "linear",
        seed = 3407,
        output_dir = "outputs",
    ),
)

trainer_stats = trainer.train()

model.save_pretrained_gguf("dir", tokenizer, quantization_method = "q4_k_m")
model.save_pretrained_gguf("dir", tokenizer, quantization_method = "q8_0")
model.save_pretrained_gguf("dir", tokenizer, quantization_method = "f16") 
  1. 本地加载微调好的大模型
    使用工具: Ollama / LM Studio
    先安装 ollama
    创建一个空文件,Modelfile ,输入:

使用:

在这里插入图片描述

教程二

https://www.bilibili.com/video/BV1AH4y137tR/

1.准备数据 json 格式 数据集文件可以是多个json 文件

2.官网下载模型已微调的中文模型

https://huggingface.co/shenzhi-wang/Llama3-8B-Chinese-Chat-GGUF-8bit/tree/v1

  1. 微调工具: peft / llamafactory /unsloth

  2. 微调方式: lora 微调之后并不是模型的所有,需要再合并上原始的模型 (官网有脚本案例)

  3. 量化 llama.cpp (github) 注意: 进入llama.cpp 文件的格式都必须是.gguf 的格式,有工具可以进行转换

1)格式转化

  1. quantize.exe
  1. 部署 ollama lmstudio

ollama: modefile文件里修改模型路径

  1. phidata 做本地知识库
相关推荐
蹦蹦跳跳真可爱589几秒前
Python----目标检测(训练YOLOV8网络)
人工智能·python·yolo·目标检测
张较瘦_3 分钟前
[论文阅读] 人工智能+项目管理 | 当 PMBOK 遇见 AI:传统项目管理框架的破局之路
论文阅读·人工智能
Leinwin7 分钟前
行业案例 | ASOS 借助 Azure AI Foundry(国际版)为年轻时尚爱好者打造惊喜体验
人工智能·microsoft·azure
用户849137175471614 分钟前
🚀 为什么猫和狗更像?用“向量思维”教会 AI 懂语义!
人工智能·llm
AI大模型知识16 分钟前
Qwen3+Ollama本地部署MCP初体验
人工智能·llm
柠檬味拥抱17 分钟前
基于语言与视觉多模态的医疗智能体系统设计与实现
人工智能
coderCatIce17 分钟前
刘二大人第5讲-pytorch实现线性回归-有代码
人工智能·机器学习
激动滴西瓜19 分钟前
🚀 三小时!我用AI流水线“组装”了一个SaaS,还闯进了InfoQ千余项目的复赛!
人工智能
俞凡22 分钟前
AI编码工具:面向现代开发者的分层指南
人工智能
张较瘦_35 分钟前
[论文阅读] 人工智能 | 大语言模型计划生成的新范式:基于过程挖掘的技能学习
论文阅读·人工智能·语言模型