notebook链接:
https://www.kaggle.com/code/tiansztianszs/chatglm-6b
首先安装依赖:
!pip install rouge_chinese nltk jieba datasets 克隆仓库:
!git clone https://github.com/THUDM/ChatGLM2-6B.git 切换到项目目录:
%cd ChatGLM2-6B 安装依赖:
!pip install -r requirements.txt
!pip install --upgrade accelerate 切换到微调目录:
%cd ptuning 开始微调:
!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 加载微调后的模型:
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() 测试微调效果:
response, history = model.chat(tokenizer, "类型#上衣*版型#宽松*版型#显瘦*图案#线条*衣样式#衬衫*衣袖型#泡泡袖*衣款式#抽绳", history=[])
response