LLaMaFactory 微调QwenCoder模型

步骤一:准备LLamaFactory环境

首先,让我们尝试使用github的方式克隆仓库:

python 复制代码
git config --global http.sslVerify false && git clone --depth 1 https://github.com/hiyouga/LLaMA-Factory.git
python 复制代码
# 创建新环境,指定 Python 版本(以 3.10 为例)
conda create -n llamafactory python=3.10 -y

# 激活环境
conda activate llamafactory

仓库已经成功克隆下来了。现在让我们进入项目目录并查看一下环境要求:

python 复制代码
cd LLaMA-Factory && cat requirements.txt

现在让我们安装所需的依赖:

python 复制代码
pip3 install -r requirements.txt

将CLI 工具(如有)注册到你的环境变量中

python 复制代码
pip install -e .

步骤二:准备模型

下载QwenCoder模型

python 复制代码
#模型下载
from modelscope import snapshot_download
model_dir = snapshot_download('XGenerationLab/XiYanSQL-QwenCoder-3B-2504')

步骤三:准备数据集

编辑 dataset_info.json

dataset_info.json 文件(一般在 LLaMA-Factory/data/ 目录下),添加以下内容:

python 复制代码
  "code_train.json": {
    "file_name": "code_train.json",
    "columns": {
      "prompt": "instruction",
      "query": "input",
      "response": "output"
    },
    "format": "alpaca"
  }

步骤四:编写微调命令

LlamaFactory 的微调命令如下:

python 复制代码
python src/train.py \
  --stage sft \
  --model_name_or_path /root/.cache/modelscope/hub/models/XGenerationLab/XiYanSQL-QwenCoder-3B-2504 \
  --do_train \
  --dataset_dir data \
  --dataset code_train.json \
  --output_dir output/qwencoder-sft \
  --per_device_train_batch_size 2 \
  --per_device_eval_batch_size 2 \
  --num_train_epochs 3 \
  --learning_rate 2e-5 \
  --fp16

步骤五:检查输出结果

  • 微调完成后,模型权重和配置会保存在 output/qwencoder-sft 目录下。
  • 你可以在该目录下找到如 pytorch_model.bin、adapter_model.bin、config.json、tokenizer_config.json 等文件。

步骤六:用 HuggingFace Transformers 代码推理

python 复制代码
import argparse
import json
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig
from tqdm import tqdm


def parse_args():
    parser = argparse.ArgumentParser(description="自动评测微调模型的推理效果")
    parser.add_argument('--model_dir', type=str, default='output/qwencoder-sft', help='模型目录')
    parser.add_argument('--test_file', type=str, default='code_test.json', help='测试集文件')
    parser.add_argument('--max_new_tokens', type=int, default=128, help='生成最大新token数')
    parser.add_argument('--device', type=str, default=None, help='推理设备,默认自动检测')
    parser.add_argument('--strict', action='store_true', help='是否严格匹配输出')
    return parser.parse_args()


def main():
    args = parse_args()
    device = args.device or ('cuda' if torch.cuda.is_available() else 'cpu')
    print(f"加载模型到 {device} ...")
    model = AutoModelForCausalLM.from_pretrained(args.model_dir, trust_remote_code=True).to(device)
    tokenizer = AutoTokenizer.from_pretrained(args.model_dir, trust_remote_code=True)
    model.eval()

    print(f"加载测试集 {args.test_file} ...")
    with open(args.test_file, "r", encoding="utf-8") as f:
        test_data = json.load(f)

    correct = 0
    total = 0
    results = []

    for item in tqdm(test_data, desc="推理中"):
        prompt = item["instruction"]
        if item.get("input"):
            prompt += "\n" + item["input"]
        inputs = tokenizer(prompt, return_tensors="pt").to(device)
        with torch.no_grad():
            outputs = model.generate(**inputs, max_new_tokens=args.max_new_tokens)
        pred = tokenizer.decode(outputs[0], skip_special_tokens=True).strip()
        gt = item["output"].strip()
        # 评测方式
        if args.strict:
            is_correct = (pred == gt)
        else:
            is_correct = (gt in pred)
        correct += int(is_correct)
        total += 1
        results.append({
            "prompt": prompt,
            "prediction": pred,
            "ground_truth": gt,
            "is_correct": is_correct
        })
        print(f"Prompt: {prompt}\nPred: {pred}\nGT: {gt}\nCorrect: {is_correct}\n---")

    acc = correct / total if total > 0 else 0
    print(f"\n总数: {total},正确: {correct},准确率: {acc:.2%}")

    # 保存详细结果
    with open("eval_results.json", "w", encoding="utf-8") as f:
        json.dump(results, f, ensure_ascii=False, indent=2)
    print("详细评测结果已保存到 eval_results.json")

if __name__ == "__main__":
    main()

使用方法

在 LLaMA-Factory 目录下运行:

python 复制代码
python t.py \
  --model_dir output/qwencoder-sft \
  --test_file code_test.json \
  --max_new_tokens 128 \
  --strict   # 可选,严格匹配时加
相关推荐
漂流瓶jz11 小时前
【AI】大模型LoRA微调原理与实验:基于CMRC2018与Qwen3-0.6B训练实测
人工智能·算法·llm
对你无可奈何12 小时前
用 AI 开发一套 AIOps 平台:接入工具、编排 Agent,追踪任务和资源
人工智能
羲云网络12 小时前
GPT Image 2.6 海报改横竖版:文字安全区、排版分离与交付验收
图像处理·人工智能·python·aigc
weixin_4187727213 小时前
公司年会年年办,AI 日历一年翻不了几页
人工智能·数字化转型·企业信息化
明川15 小时前
RAG 到底是什么
人工智能·llm
罗西的思考16 小时前
【轻量化复刻大模型 / KIMI K3】K3 PostTrain 后训练交互式演示
人工智能·算法·机器学习
ZhengEnCi16 小时前
黄仁勋回归英伟达:没有欢迎仪式,员工自发拥抱说明了什么
人工智能·nvidia
陆枫Larry17 小时前
从一头雾水到自己开发一个 MCP Server 来加深理解
人工智能
Csvn17 小时前
模型被「忽略指令」劫持怎么办?双层防线:输入过滤 + 输出校验(S02)
人工智能
Flynn Liang18 小时前
AI Agent Redis 生产踩坑实录:13 类故障的根因、复现与调优
数据库·人工智能·redis·缓存·ai agent·故障分析