学员闯关手册:https://aicarrier.feishu.cn/wiki/QdhEwaIINietCak3Y1dcdbLJn3e
课程视频:https://www.bilibili.com/video/BV13U1VYmEUr/
课程文档:https://github.com/InternLM/Tutorial/tree/camp4/docs/L0/Python
关卡作业:https://github.com/InternLM/Tutorial/blob/camp4/docs/L0/Python/task.md
开发机平台:https://studio.intern-ai.org.cn/
开发机平台介绍:https://aicarrier.feishu.cn/wiki/GQ1Qwxb3UiQuewk8BVLcuyiEnHe
书生浦语官网:https://internlm.intern-ai.org.cn/
github网站:https://github.com/internLM/
InternThinker: https://internlm-chat.intern-ai.org.cn/internthinker
快速上手飞书文档:https://www.feishu.cn/hc/zh-CN/articles/945900971706-%E5%BF%AB%E9%80%9F%E4%B8%8A%E6%89%8B%E6%96%87%E6%A1%A3
提交作业:https://aicarrier.feishu.cn/share/base/form/shrcnUqshYPt7MdtYRTRpkiOFJd;
作业批改结果:https://aicarrier.feishu.cn/share/base/query/shrcnkNtOS9gPPnC9skiBLlao2c
internLM-Chat 智能体:https://github.com/InternLM/InternLM/blob/main/agent/README_zh-CN.md
lagent:https://lagent.readthedocs.io/zh-cn/latest/tutorials/action.html#id2
github仓库:https://github.com/InternLM/xtuner
动态知识库:https://deepwiki.com/InternLM/xtuner
在这里插入图片描述

XTuner 是一个高效、灵活、全能的轻量化大模型微调工具库。
核心特点:

  1. 高效:支持在有限资源下微调大模型,如在8GB显存上微调7B参数模型,也支持多节点微调70B+模型;自动分发高性能算子加速训练;兼容DeepSpeed优化策略。
  2. 灵活:支持多种大语言模型(如InternLM、Llama、ChatGLM等)和多模态模型;支持多种数据格式;支持QLoRA、LoRA、全量参数微调等多种微调算法。
  3. 全能:支持增量预训练、指令微调与Agent微调;预定义多种对话模板;训练所得模型可无缝接入部署工具LMDeploy和评测工具OpenCompass。

支持的模型图
在这里插入图片描述
工作流
在这里插入图片描述

 #Cuda12.2-conda
 #1、环境安装
conda activate /root/share/pre_envs/pytorch2.3.1cu12.1
pip install 'xtuner[deepspeed]' timm==1.0.9  
pip install transformers==4.48.0
pip install modelscope
mkdir -p /root/finetune && cd /root/finetune #文件夹多了finetune

#2、修改提供的数据
#2.1、创建一个新的文件夹用于存储微调数据
mkdir -p /root/finetune/data && cd /root/finetune/data   #多一个data文件夹,把数据文件sftdata.jsonl放入

#3、复制模型和修改config
#3.1、复制模型
mkdir /root/finetune/models
ln -s /root/share/new_models/Shanghai_AI_Laboratory/internlm2_5-7b-chat /root/finetune/models/internlm2_5-7b-chat
#3.2、修改 Config,pretrained_model_name_or_path alpaca_en_path 只需要注意34和38行模型、数据位置就好了
# cd {path/to/finetune}
cd /root/finetune
mkdir ./config
cd config
#修改 Config的settings,pretrained_model_name_or_path = '/root/finetune/models/internlm2_5-7b-chat'
# alpaca_en_path =  '/root/finetune/data/sftdata.jsonl'


#4、训练
#4.1、启动微调
cd /root/finetune
pip install protobuf #教程中少了这步,因此报错;加上就正确了
xtuner train ./config/internlm2_5_chat_7b_qlora_alpaca_e3_copy.py --deepspeed deepspeed_zero2 --work-dir ./work_dirs/sft
#4.2、权重转换
cd /root/finetune/work_dirs/sft
# 先获取最后保存的一个pth文件
pth_file=`ls -t /root/finetune/work_dirs/sft/*.pth | head -n 1 | sed 's/:$//'`
export MKL_SERVICE_FORCE_INTEL=1
export MKL_THREADING_LAYER=GNU
#xtuner convert pth_to_hf 命令用于进行模型格式转换。该命令需要三个参数:CONFIG 表示微调的配置文件, PATH_TO_PTH_MODEL 表示微调的模型权重文件路径,即要转换的模型权重, SAVE_PATH_TO_HF_MODEL 表示转换后的 HuggingFace 格式文件的保存路径。
xtuner convert pth_to_hf ./internlm2_5_chat_7b_qlora_alpaca_e3_copy.py ${pth_file} ./hf
#此时,hf 文件夹即为我们平时所理解的所谓 “LoRA 模型文件”,可以简单理解:LoRA 模型文件 = Adapter
#4.3、模型合并
#xtuner convert merge命令用于合并模型。该命令需要三个参数:LLM 表示原模型路径,ADAPTER 表示 Adapter 层的路径, SAVE_PATH 表示合并后的模型最终的保存路径。
cd /root/finetune/work_dirs/sft
export MKL_SERVICE_FORCE_INTEL=1
export MKL_THREADING_LAYER=GNU
xtuner convert merge /root/finetune/models/internlm2_5-7b-chat ./hf ./merged --max-shard-size 2GB

#5、模型推理
#5.1、新建编辑infer.py
python infer.py
#5.2、模型部署
pip install lmdeploy
python -m lmdeploy.pytorch.chat ./work_dirs/sft/merged\
    --max_new_tokens 256 \
    --temperture 0.8 \
    --top_p 0.95 \
    --seed 0
#5.3、模型评测
#在opencompass目录下
python run.py internlm3-oc_eval.py --debug

#6、模型上传https://modelscope.cn/home,
pip install modelscope
python upload_to_modelscope.py

模型上传到魔塔社区

  1. 到刚创建好的模型仓库中,拿到hub_model_id,实际上就是 {账号名称/模型库名称},如“Shanghai_AI_Laboratory/internlm3-8b-instruct”
  2. 账号设置-访问令牌 中拿到hub_token,需妥善保存,不要暴露给他人
    在这里插入图片描述
    在这里插入图片描述
#python upload_to_modelscope.py
from modelscope.hub.api import HubApi
from modelscope.hub.constants import Licenses, ModelVisibility

# 配置基本信息
YOUR_ACCESS_TOKEN = 'xxx(从modelscope获取,即上节的hub_token)'
api = HubApi()
api.login(YOUR_ACCESS_TOKEN)

# 取名字
owner_name = 'haidizym'    # ModelScope 的用户名,需根据自己情况修改
model_name = "zym-camp5-v3"    # 为模型库取个响亮优雅又好听的名字,需根据自己情况修改    
model_id = f"{owner_name}/{model_name}"

# 创建模型库,若已通过6.1节的ModelScope网页端创建,此段代码可忽略
api.create_model(
     model_id,
     visibility=ModelVisibility.PUBLIC,
     license=Licenses.APACHE_V2,
     chinese_name=f"{owner_name}的论文分类打榜赛模型"
    )

# 上传模型
api.upload_folder(
    repo_id=f"{owner_name}/{model_name}",
    folder_path='/root/finetune/work_dirs/sft/merged',    # 微调后模型的文件夹名称
    commit_message='upload model folder to repo',    # 写点开心的上传信息
)

在这里插入图片描述

在这里插入图片描述
训练过程中
在这里插入图片描述
模型转换
在这里插入图片描述
模型合并
在这里插入图片描述
模型推理
在这里插入图片描述

模型上传魔塔
在这里插入图片描述
在这里插入图片描述
https://modelscope.cn/models/haidizym/zym-camp5-v3

成绩
在这里插入图片描述
20250716 A榜 69.17,B榜 48.91

附录

#internlm2_5_chat_7b_qlora_alpaca_e3_copy.py
# Copyright (c) OpenMMLab. All rights reserved.
# —— 动态补丁:兼容 transformers>=4.48 ——
from transformers.cache_utils import DynamicCache     # 1. 引入类
if not hasattr(DynamicCache, "get_max_length"):       # 2. 判断是否缺失
    DynamicCache.get_max_length = DynamicCache.get_max_cache_shape  # 3. 补一个别名
import torch
from datasets import load_dataset
from mmengine.dataset import DefaultSampler
from mmengine.hooks import (
    CheckpointHook,
    DistSamplerSeedHook,
    IterTimerHook,
    LoggerHook,
    ParamSchedulerHook,
)
from mmengine.optim import AmpOptimWrapper, CosineAnnealingLR, LinearLR
from peft import LoraConfig
from torch.optim import AdamW
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig

from xtuner.dataset import process_hf_dataset
from xtuner.dataset.collate_fns import default_collate_fn
from xtuner.dataset.map_fns import alpaca_map_fn, template_map_fn_factory
from xtuner.engine.hooks import (
    DatasetInfoHook,
    EvaluateChatHook,
    VarlenAttnArgsToMessageHubHook,
)
from xtuner.engine.runner import TrainLoop
from xtuner.model import SupervisedFinetune
from xtuner.parallel.sequence import SequenceParallelSampler
from xtuner.utils import PROMPT_TEMPLATE, SYSTEM_TEMPLATE

#######################################################################
#                          PART 1  Settings                           #
#######################################################################
# Model
pretrained_model_name_or_path = '/root/finetune/models/internlm2_5-7b-chat'
use_varlen_attn = False

# Data
alpaca_en_path =  '/root/finetune/data/sftdata.jsonl'#换成自己的数据路径
prompt_template = PROMPT_TEMPLATE.internlm2_chat
max_length = 1024
pack_to_max_length = True

# parallel
sequence_parallel_size = 1

# Scheduler & Optimizer
batch_size = 1  # per_device
accumulative_counts = 1
accumulative_counts *= sequence_parallel_size
dataloader_num_workers = 0
max_epochs = 1
optim_type = AdamW
lr = 2e-4
betas = (0.9, 0.999)
weight_decay = 0
max_norm = 1  # grad clip
warmup_ratio = 0.03

# Save
save_steps = 50
save_total_limit = 2  # Maximum checkpoints to keep (-1 means unlimited)

# Evaluate the generation performance during the training
evaluation_freq = 50
SYSTEM = SYSTEM_TEMPLATE.alpaca
evaluation_inputs = ["请给我介绍五个上海的景点", "Please tell me five scenic spots in Shanghai"]

#######################################################################
#                      PART 2  Model & Tokenizer                      #
#######################################################################
tokenizer = dict(
    type=AutoTokenizer.from_pretrained,
    pretrained_model_name_or_path=pretrained_model_name_or_path,
    trust_remote_code=True,
    padding_side="right",
)

model = dict(
    type=SupervisedFinetune,
    use_varlen_attn=use_varlen_attn,
    llm=dict(
        type=AutoModelForCausalLM.from_pretrained,
        pretrained_model_name_or_path=pretrained_model_name_or_path,
        trust_remote_code=True,
        torch_dtype=torch.float16,
        quantization_config=dict(
            type=BitsAndBytesConfig,
            load_in_4bit=True,
            load_in_8bit=False,
            llm_int8_threshold=6.0,
            llm_int8_has_fp16_weight=False,
            bnb_4bit_compute_dtype=torch.float16,
            bnb_4bit_use_double_quant=True,
            bnb_4bit_quant_type="nf4",
        ),
    ),
    lora=dict(
        type=LoraConfig,
        r=64,
        lora_alpha=16,
        lora_dropout=0.1,
        bias="none",
        task_type="CAUSAL_LM",
    ),
)

#######################################################################
#                      PART 3  Dataset & Dataloader                   #
#######################################################################
alpaca_en = dict(
    type=process_hf_dataset,
    dataset=dict(type=load_dataset, path='json', data_files=alpaca_en_path),
    tokenizer=tokenizer,
    max_length=max_length,
    dataset_map_fn=alpaca_map_fn,
    template_map_fn=dict(type=template_map_fn_factory, template=prompt_template),
    remove_unused_columns=True,
    shuffle_before_pack=True,
    pack_to_max_length=pack_to_max_length,
    use_varlen_attn=use_varlen_attn,
)

sampler = SequenceParallelSampler if sequence_parallel_size > 1 else DefaultSampler
train_dataloader = dict(
    batch_size=batch_size,
    num_workers=dataloader_num_workers,
    dataset=alpaca_en,
    sampler=dict(type=sampler, shuffle=True),
    collate_fn=dict(type=default_collate_fn, use_varlen_attn=use_varlen_attn),
)

#######################################################################
#                    PART 4  Scheduler & Optimizer                    #
#######################################################################
# optimizer
optim_wrapper = dict(
    type=AmpOptimWrapper,
    optimizer=dict(type=optim_type, lr=lr, betas=betas, weight_decay=weight_decay),
    clip_grad=dict(max_norm=max_norm, error_if_nonfinite=False),
    accumulative_counts=accumulative_counts,
    loss_scale="dynamic",
    dtype="float16",
)

# learning policy
# More information: https://github.com/open-mmlab/mmengine/blob/main/docs/en/tutorials/param_scheduler.md  # noqa: E501
param_scheduler = [
    dict(
        type=LinearLR,
        start_factor=1e-5,
        by_epoch=True,
        begin=0,
        end=warmup_ratio * max_epochs,
        convert_to_iter_based=True,
    ),
    dict(
        type=CosineAnnealingLR,
        eta_min=0.0,
        by_epoch=True,
        begin=warmup_ratio * max_epochs,
        end=max_epochs,
        convert_to_iter_based=True,
    ),
]

# train, val, test setting
train_cfg = dict(type=TrainLoop, max_epochs=max_epochs)

#######################################################################
#                           PART 5  Runtime                           #
#######################################################################
# Log the dialogue periodically during the training process, optional
custom_hooks = [
    dict(type=DatasetInfoHook, tokenizer=tokenizer),
    dict(
        type=EvaluateChatHook,
        tokenizer=tokenizer,
        every_n_iters=evaluation_freq,
        evaluation_inputs=evaluation_inputs,
        system=SYSTEM,
        prompt_template=prompt_template,
    ),
]

if use_varlen_attn:
    custom_hooks += [dict(type=VarlenAttnArgsToMessageHubHook)]

# configure default hooks
default_hooks = dict(
    # record the time of every iteration.
    timer=dict(type=IterTimerHook),
    # print log every 10 iterations.
    logger=dict(type=LoggerHook, log_metric_by_epoch=False, interval=10),
    # enable the parameter scheduler.
    param_scheduler=dict(type=ParamSchedulerHook),
    # save checkpoint per `save_steps`.
    checkpoint=dict(
        type=CheckpointHook,
        by_epoch=False,
        interval=save_steps,
        max_keep_ckpts=save_total_limit,
    ),
    # set sampler seed in distributed evrionment.
    sampler_seed=dict(type=DistSamplerSeedHook),
)

# configure environment
env_cfg = dict(
    # whether to enable cudnn benchmark
    cudnn_benchmark=False,
    # set multi process parameters
    mp_cfg=dict(mp_start_method="fork", opencv_num_threads=0),
    # set distributed parameters
    dist_cfg=dict(backend="nccl"),
)

# set visualizer
visualizer = None

# set log level
log_level = "INFO"

# load from which checkpoint
load_from = None

# whether to resume training from the loaded checkpoint
resume = False

# Defaults to use random seed and disable `deterministic`
randomness = dict(seed=None, deterministic=False)

# set log processor
log_processor = dict(by_epoch=False)

#infer.py
from transformers import AutoModelForCausalLM, AutoTokenizer
import time

# 加载模型和分词器
# model_path = "./work_dirs/merged"
model_path = "./internlm2_5-7b-chat"
print(f"加载模型:{model_path}")

start_time = time.time()

tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    model_path, trust_remote_code=True, torch_dtype="auto", device_map="auto"
)

def classify_paper(title, authors, abstract, additional_info=""):
    # 构建输入,包含多选选项
    prompt = f"Based on the title '{title}', authors '{authors}', and abstract '{abstract}', please determine the scientific category of this paper. {additional_info}\n\nA. astro-ph\nB. cond-mat.mes-hall\nC. cond-mat.mtrl-sci\nD. cs.CL\nE. cs.CV\nF. cs.LG\nG. gr-qc\nH. hep-ph\nI. hep-th\nJ. quant-ph"

    # 设置系统信息
    messages = [
        {"role": "system", "content": "你是个优秀的论文分类师"},
        {"role": "user", "content": prompt},
    ]

    # 应用聊天模板
    input_text = tokenizer.apply_chat_template(messages, tokenize=False)

    # 生成回答
    inputs = tokenizer(input_text, return_tensors="pt").to(model.device)
    outputs = model.generate(
        **inputs,
        max_new_tokens=10,  # 减少生成长度,只需要简短答案
        temperature=0.1,  # 降低温度提高确定性
        top_p=0.95,
        repetition_penalty=1.0,
    )

    # 解码输出
    response = tokenizer.decode(
        outputs[0][inputs.input_ids.shape[1] :], skip_special_tokens=True
    ).strip()

    # 如果回答中包含选项标识符,只返回该标识符
    for option in ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]:
        if option in response:
            return option

    # 如果回答不包含选项,返回完整回答
    return response

# 示例使用
if __name__ == "__main__":
    title = "Outilex, plate-forme logicielle de traitement de textes 'ecrits"
    authors = "Olivier Blanc (IGM-LabInfo), Matthieu Constant (IGM-LabInfo), Eric Laporte (IGM-LabInfo)"
    abstract = "The Outilex software platform, which will be made available to research, development and industry, comprises software components implementing all the fundamental operations of written text processing: processing without lexicons, exploitation of lexicons and grammars, language resource management. All data are structured in XML formats, and also in more compact formats, either readable or binary, whenever necessary; the required format converters are included in the platform; the grammar formats allow for combining statistical approaches with resource-based approaches. Manually constructed lexicons for French and English, originating from the LADL, and of substantial coverage, will be distributed with the platform under LGPL-LR license."

    result = classify_paper(title, authors, abstract)
    print(result)

    # 计算并打印总耗时
    end_time = time.time()
    total_time = end_time - start_time
    print(f"程序总耗时:{total_time:.2f}秒")

#评测代码(数据/root/datasets/train/newformat_sft_test_data.csv是A榜测试数据)
#在opencompass目录下
#python run.py internlm3-oc_eval.py --debug
 # To run this example, you need to do the following steps:
# 1. Install latest opencompass
# 2. Start a local server with Qwen2.5-72B-Instruct as LLMJudge server (i.e. using vLLM or LMDeploy)
# 3. Change the judge_cfg openai_api_base to your corresponindg local server address
# 4. Start this evaluation by running 'opencompass eval_internlm3_math500_thinking.py' 
# from opencompass.models import VLLMwithChatTemplate, OpenAISDK
from mmengine.config import read_base
from opencompass.models import HuggingFaceCausalLM

models = [
    dict(
        type=HuggingFaceCausalLM,
        path='',
        tokenizer_path='',
        tokenizer_kwargs=dict(padding_side='left', truncation_side='left'),
        model_kwargs=dict(device_map='auto'),
        max_seq_len=32768,
        max_out_len=16384,
        batch_size=4,
        run_cfg=dict(num_gpus=1),
    )
]

datasets = [
    {"path": "/root/datasets/train/newformat_sft_test_data.csv", "data_type": "mcq", "infer_method": "gen"},
]
Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐