一分钟上手ChatGLM2-6B模型微调
AI日日新
编辑于 2023年07月11日 07:48

notebook链接:

代码块
Python
自动换行
复制代码
https://www.kaggle.com/code/tiansztianszs/chatglm-6b
复制成功

首先安装依赖:

代码块
Python
自动换行
复制代码
!pip install rouge_chinese nltk jieba datasets
复制成功

克隆仓库:

代码块
Python
自动换行
复制代码
!git clone https://github.com/THUDM/ChatGLM2-6B.git
复制成功

切换到项目目录:

代码块
Python
自动换行
复制代码
%cd ChatGLM2-6B
复制成功

安装依赖:

代码块
Python
自动换行
复制代码
!pip install -r requirements.txt
!pip install --upgrade accelerate
复制成功

切换到微调目录:

代码块
Python
自动换行
复制代码
%cd ptuning
复制成功

开始微调:

代码块
Python
自动换行
复制代码
!WANDB_DISABLED=true torchrun --standalone --nnodes=1 --nproc-per-node=1 main.py \
    --do_train \
    --train_file /kaggle/input/chatglm2-6b-dataset/AdvertiseGen/train.json \
    --validation_file /kaggle/input/chatglm2-6b-dataset/AdvertiseGen/dev.json \
    --preprocessing_num_workers 1 \
    --prompt_column content \
    --response_column summary \
    --overwrite_cache \
    --model_name_or_path THUDM/chatglm2-6b-int4 \
    --output_dir output \
    --overwrite_output_dir \
    --max_source_length 64 \
    --max_target_length 128 \
    --per_device_train_batch_size 1 \
    --per_device_eval_batch_size 1 \
    --gradient_accumulation_steps 1 \
    --predict_with_generate \
    --max_steps 100 \
    --logging_steps 10 \
    --save_steps 100 \
    --learning_rate 2e-2 \
    --pre_seq_len 128 \
    --quantization_bit 4
复制成功

加载微调后的模型:

代码块
Python
自动换行
复制代码
save_steps = 100

from transformers import AutoConfig, AutoModel, AutoTokenizer
import torch

# 载入Tokenizer
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b-int4", trust_remote_code=True)
config = AutoConfig.from_pretrained("THUDM/chatglm2-6b-int4", trust_remote_code=True, pre_seq_len=128)
model = AutoModel.from_pretrained("THUDM/chatglm2-6b-int4", config=config, trust_remote_code=True)
prefix_state_dict = torch.load(f"output/checkpoint-{save_steps}/pytorch_model.bin")
new_prefix_state_dict = {}
for k, v in prefix_state_dict.items():
    if k.startswith("transformer.prefix_encoder."):
        new_prefix_state_dict[k[len("transformer.prefix_encoder."):]] = v
model.transformer.prefix_encoder.load_state_dict(new_prefix_state_dict)
model = model.quantize(4)
model = model.cuda()
model = model.eval()
复制成功

测试微调效果:

代码块
Python
自动换行
复制代码
response, history = model.chat(tokenizer, "类型#上衣*版型#宽松*版型#显瘦*图案#线条*衣样式#衬衫*衣袖型#泡泡袖*衣款式#抽绳", history=[])

response
复制成功