{"id":13646250,"url":"https://github.com/liucongg/chatglm-finetuning","last_synced_at":"2025-05-15T08:06:10.148Z","repository":{"id":151838464,"uuid":"624214839","full_name":"liucongg/ChatGLM-Finetuning","owner":"liucongg","description":"基于ChatGLM-6B、ChatGLM2-6B、ChatGLM3-6B模型，进行下游具体任务微调，涉及Freeze、Lora、P-tuning、全参微调等","archived":false,"fork":false,"pushed_at":"2023-12-12T15:36:52.000Z","size":1416,"stargazers_count":2738,"open_issues_count":77,"forks_count":311,"subscribers_count":13,"default_branch":"master","last_synced_at":"2025-04-07T02:19:49.799Z","etag":null,"topics":["chatglm","chatglm2","chatglm3","chatgpt","freeze","lora","p-tuning"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/liucongg.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2023-04-06T01:45:27.000Z","updated_at":"2025-04-04T07:02:04.000Z","dependencies_parsed_at":"2023-12-12T16:29:13.726Z","dependency_job_id":"3a2c9d54-899b-410b-b662-fd9b087e7491","html_url":"https://github.com/liucongg/ChatGLM-Finetuning","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/liucongg%2FChatGLM-Finetuning","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/liucongg%2FChatGLM-Finetuning/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/liucongg%2FChatGLM-Finetuning/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/liucongg%2FChatGLM-Finetuning/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/liucongg","download_url":"https://codeload.github.com/liucongg/ChatGLM-Finetuning/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248870366,"owners_count":21175029,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["chatglm","chatglm2","chatglm3","chatgpt","freeze","lora","p-tuning"],"created_at":"2024-08-02T01:02:51.443Z","updated_at":"2025-04-14T11:25:48.836Z","avatar_url":"https://github.com/liucongg.png","language":"Python","funding_links":[],"categories":["Others"],"sub_categories":[],"readme":"\n## ChatGLM微调\n本项目主要针对ChatGLM、ChatGLM2和ChatGLM3模型进行不同方式的微调（Freeze方法、Lora方法、P-Tuning方法、全量参数等），并对比大模型在不同微调方法上的效果，主要针对信息抽取任务、生成任务、分类任务等。\n\n本项目支持单卡训练\u0026多卡训练，由于采用单指令集方式微调，模型微调之后**并没有出现严重的灾难性遗忘**。\n\n由于官方代码和模型一直在更新，目前ChatGLM1和2的代码和模型的为20230806版本（注意如果发现代码运行有误，可将ChatGLM相关源码替换文件中的py文件，因为可能你下的模型版本与本项目代码版本不一致），ChatGLM3是版本20231212。\n\nPS：没有用Trainer（虽然Trainer代码简单，但不易修改，大模型时代算法工程师本就成为了数据工程师，因此更需了解训练流程）\n\n## 更新简介\n- update-2023.12.12 增加ChatGLM3代码支持，通过model_type完成模型切换，并增加推理代码。\n- update-2023.08.06 代码和模型已经更新到最新，支持单卡\u0026多卡训练，支持ChatGLM2模型训练、支持全量参数训练，所有代码进行了结构增加可读性。\n- update-2023.06.12 [**增加流水线并行训练方法**](https://zhuanlan.zhihu.com/p/636488690)，请看[v0.1 Tag](https://github.com/liucongg/ChatGLM-Finetuning/tree/v0.1)\n- update-2023.04.18 **增加文本生成任务评测**，请看[v0.1 Tag](https://github.com/liucongg/ChatGLM-Finetuning/tree/v0.1)\n- update-2023.04.05 **增加信息抽取任务评测**，请看[v0.1 Tag](https://github.com/liucongg/ChatGLM-Finetuning/tree/v0.1)\n\n## 微调方法\n模型微调时，如果遇到显存不够的情况，可以开启gradient_checkpointing、zero3、offload等参数来节省显存。\n\n下面model_name_or_path参数为模型路径，请根据可根据自己实际模型保存地址进行修改。\n### Freeze方法\nFreeze方法，即参数冻结，对原始模型部分参数进行冻结操作，仅训练部分参数，以达到在单卡或多卡，不进行TP或PP操作就可以对大模型进行训练。\n\n微调代码，见train.py，核心部分如下：\n```python3\nfreeze_module_name = args.freeze_module_name.split(\",\")\nfor name, param in model.named_parameters():\n\tif not any(nd in name for nd in freeze_module_name):\n\t\tparam.requires_grad = False\n```\n针对模型不同层进行修改，可以自行修改freeze_module_name参数配置，例如\"layers.27.,layers.26.,layers.25.,layers.24.\"。\n训练代码均采用DeepSpeed进行训练，可设置参数包含train_path、model_name_or_path、mode、train_type、freeze_module_name、ds_file、num_train_epochs、per_device_train_batch_size、gradient_accumulation_steps、output_dir等， 可根据自己的任务配置。\n\nChatGLM单卡训练\n```\nCUDA_VISIBLE_DEVICES=0 deepspeed --master_port 520 train.py \\\n                --train_path data/spo_0.json \\\n                --model_name_or_path ChatGLM-6B/ \\\n                --per_device_train_batch_size 1 \\\n                --max_len 1560 \\\n                --max_src_len 1024 \\\n                --learning_rate 1e-4 \\\n                --weight_decay 0.1 \\\n                --num_train_epochs 2 \\\n                --gradient_accumulation_steps 4 \\\n                --warmup_ratio 0.1 \\\n                --mode glm \\\n                --train_type freeze \\\n                --freeze_module_name \"layers.27.,layers.26.,layers.25.,layers.24.\" \\\n                --seed 1234 \\\n                --ds_file ds_zero2_no_offload.json \\\n                --gradient_checkpointing \\\n                --show_loss_step 10 \\\n                --output_dir ./output-glm\n```\nChatGLM四卡训练，通过CUDA_VISIBLE_DEVICES控制具体哪几块卡进行训练，如果不加该参数，表示使用运行机器上所有卡进行训练\n```\nCUDA_VISIBLE_DEVICES=0,1,2,3 deepspeed --master_port 520 train.py \\\n                --train_path data/spo_0.json \\\n                --model_name_or_path ChatGLM-6B/ \\\n                --per_device_train_batch_size 1 \\\n                --max_len 1560 \\\n                --max_src_len 1024 \\\n                --learning_rate 1e-4 \\\n                --weight_decay 0.1 \\\n                --num_train_epochs 2 \\\n                --gradient_accumulation_steps 4 \\\n                --warmup_ratio 0.1 \\\n                --mode glm \\\n                --train_type freeze \\\n                --freeze_module_name \"layers.27.,layers.26.,layers.25.,layers.24.\" \\\n                --seed 1234 \\\n                --ds_file ds_zero2_no_offload.json \\\n                --gradient_checkpointing \\\n                --show_loss_step 10 \\\n                --output_dir ./output-glm\n```\nChatGLM2单卡训练\n```\nCUDA_VISIBLE_DEVICES=0 deepspeed --master_port 520 train.py \\\n                --train_path data/spo_0.json \\\n                --model_name_or_path ChatGLM2-6B/ \\\n                --per_device_train_batch_size 1 \\\n                --max_len 1560 \\\n                --max_src_len 1024 \\\n                --learning_rate 1e-4 \\\n                --weight_decay 0.1 \\\n                --num_train_epochs 2 \\\n                --gradient_accumulation_steps 4 \\\n                --warmup_ratio 0.1 \\\n                --mode glm2 \\\n                --train_type freeze \\\n                --freeze_module_name \"layers.27.,layers.26.,layers.25.,layers.24.\" \\\n                --seed 1234 \\\n                --ds_file ds_zero2_no_offload.json \\\n                --gradient_checkpointing \\\n                --show_loss_step 10 \\\n                --output_dir ./output-glm2\n```\nChatGLM2四卡训练，通过CUDA_VISIBLE_DEVICES控制具体哪几块卡进行训练，如果不加该参数，表示使用运行机器上所有卡进行训练\n```\nCUDA_VISIBLE_DEVICES=0,1,2,3 deepspeed --master_port 520 train.py \\\n                --train_path data/spo_0.json \\\n                --model_name_or_path ChatGLM2-6B/ \\\n                --per_device_train_batch_size 1 \\\n                --max_len 1560 \\\n                --max_src_len 1024 \\\n                --learning_rate 1e-4 \\\n                --weight_decay 0.1 \\\n                --num_train_epochs 2 \\\n                --gradient_accumulation_steps 4 \\\n                --warmup_ratio 0.1 \\\n                --mode glm2 \\\n                --train_type freeze \\\n                --freeze_module_name \"layers.27.,layers.26.,layers.25.,layers.24.\" \\\n                --seed 1234 \\\n                --ds_file ds_zero2_no_offload.json \\\n                --gradient_checkpointing \\\n                --show_loss_step 10 \\\n                --output_dir ./output-glm2\n```\nChatGLM3单卡训练\n```\nCUDA_VISIBLE_DEVICES=0 deepspeed --master_port 520 train.py \\\n                --train_path data/spo_0.json \\\n                --model_name_or_path ChatGLM3-6B/ \\\n                --per_device_train_batch_size 1 \\\n                --max_len 1560 \\\n                --max_src_len 1024 \\\n                --learning_rate 1e-4 \\\n                --weight_decay 0.1 \\\n                --num_train_epochs 2 \\\n                --gradient_accumulation_steps 4 \\\n                --warmup_ratio 0.1 \\\n                --mode glm3 \\\n                --train_type freeze \\\n                --freeze_module_name \"layers.27.,layers.26.,layers.25.,layers.24.\" \\\n                --seed 1234 \\\n                --ds_file ds_zero2_no_offload.json \\\n                --gradient_checkpointing \\\n                --show_loss_step 10 \\\n                --output_dir ./output-glm3\n```\nChatGLM3四卡训练，通过CUDA_VISIBLE_DEVICES控制具体哪几块卡进行训练，如果不加该参数，表示使用运行机器上所有卡进行训练\n```\nCUDA_VISIBLE_DEVICES=0,1,2,3 deepspeed --master_port 520 train.py \\\n                --train_path data/spo_0.json \\\n                --model_name_or_path ChatGLM3-6B/ \\\n                --per_device_train_batch_size 1 \\\n                --max_len 1560 \\\n                --max_src_len 1024 \\\n                --learning_rate 1e-4 \\\n                --weight_decay 0.1 \\\n                --num_train_epochs 2 \\\n                --gradient_accumulation_steps 4 \\\n                --warmup_ratio 0.1 \\\n                --mode glm3 \\\n                --train_type freeze \\\n                --freeze_module_name \"layers.27.,layers.26.,layers.25.,layers.24.\" \\\n                --seed 1234 \\\n                --ds_file ds_zero2_no_offload.json \\\n                --gradient_checkpointing \\\n                --show_loss_step 10 \\\n                --output_dir ./output-glm3\n```\nPS：ChatGLM微调时所用显存要比ChatGLM2多，详细显存占比如下：\n\n| Model |  DeepSpeed-Stage |  Offload | Gradient Checkpointing |  Batch Size | Max Length | GPU-A40 Number | 所耗显存 |\n| ------- | ------ | ------  | ------ | ------ | ------  | ------ | ------ |\n| ChaGLM | zero2 | No | Yes | 1 | 1560  | 1 | 36G |\n| ChaGLM | zero2 | No | No | 1 | 1560  | 1 | 38G |\n| ChaGLM | zero2 | No | Yes | 1 | 1560  | 4 | 24G |\n| ChaGLM | zero2 | No | No | 1 | 1560  | 4 | 29G |\n| ChaGLM2 | zero2 | No | Yes | 1 | 1560  | 1 | 35G |\n| ChaGLM2 | zero2 | No | No | 1 | 1560  | 1 | 36G |\n| ChaGLM2 | zero2 | No | Yes | 1 | 1560  | 4 | 22G |\n| ChaGLM2 | zero2 | No | No | 1 | 1560  | 4 | 27G |\n\n\n### PT方法\nPT方法，即P-Tuning方法，参考[ChatGLM官方代码](https://github.com/THUDM/ChatGLM-6B/blob/main/ptuning/README.md) ，是一种针对于大模型的soft-prompt方法。\n\n![](images/PT.png)\n- P-Tuning仅对大模型的Embedding加入新的参数。[paper](https://arxiv.org/abs/2103.10385)\n- P-Tuning-V2，将大模型的Embedding和每一层前都加上新的参数。[paper](https://arxiv.org/abs/2110.07602)\n\n微调代码，见train.py，核心部分如下：\n```python3\nconfig = MODE[args.mode][\"config\"].from_pretrained(args.model_name_or_path)\nconfig.pre_seq_len = args.pre_seq_len\nconfig.prefix_projection = args.prefix_projection\nmodel = MODE[args.mode][\"model\"].from_pretrained(args.model_name_or_path, config=config)\nfor name, param in model.named_parameters():\n\tif not any(nd in name for nd in [\"prefix_encoder\"]):\n\t\tparam.requires_grad = False\n```\n当prefix_projection为True时，为P-Tuning-V2方法，在大模型的Embedding和每一层前都加上新的参数；为False时，为P-Tuning方法，仅在大模型的Embedding上新的参数。\n\n训练代码均采用DeepSpeed进行训练，可设置参数包含train_path、model_name_or_path、mode、train_type、pre_seq_len、prefix_projection、ds_file、num_train_epochs、per_device_train_batch_size、gradient_accumulation_steps、output_dir等， 可根据自己的任务配置。\n\nChatGLM单卡训练\n```\nCUDA_VISIBLE_DEVICES=0 deepspeed --master_port 520 train.py \\\n                --train_path data/spo_0.json \\\n                --model_name_or_path ChatGLM-6B \\\n                --per_device_train_batch_size 1 \\\n                --max_len 768 \\\n                --max_src_len 512 \\\n                --learning_rate 1e-4 \\\n                --weight_decay 0.1 \\\n                --num_train_epochs 2 \\\n                --gradient_accumulation_steps 4 \\\n                --warmup_ratio 0.1 \\\n                --mode glm \\\n                --train_type ptuning \\\n                --seed 1234 \\\n                --ds_file ds_zero2_no_offload.json \\\n                --gradient_checkpointing \\\n                --show_loss_step 10 \\\n                --pre_seq_len 16 \\\n                --prefix_projection True \\\n                --output_dir ./output-glm\n```\nChatGLM四卡训练，通过CUDA_VISIBLE_DEVICES控制具体哪几块卡进行训练，如果不加该参数，表示使用运行机器上所有卡进行训练\n```\nCUDA_VISIBLE_DEVICES=0,1,2,3 deepspeed --master_port 520 train.py \\\n                --train_path data/spo_0.json \\\n                --model_name_or_path ChatGLM-6B \\\n                --per_device_train_batch_size 1 \\\n                --max_len 1560 \\\n                --max_src_len 1024 \\\n                --learning_rate 1e-4 \\\n                --weight_decay 0.1 \\\n                --num_train_epochs 2 \\\n                --gradient_accumulation_steps 4 \\\n                --warmup_ratio 0.1 \\\n                --mode glm \\\n                --train_type ptuning \\\n                --seed 1234 \\\n                --ds_file ds_zero2_no_offload.json \\\n                --gradient_checkpointing \\\n                --show_loss_step 10 \\\n                --pre_seq_len 16 \\\n                --prefix_projection True \\\n                --output_dir ./output-glm\n```\nChatGLM2单卡训练\n```\nCUDA_VISIBLE_DEVICES=0 deepspeed --master_port 520 train.py \\\n                --train_path data/spo_0.json \\\n                --model_name_or_path ChatGLM2-6B \\\n                --per_device_train_batch_size 1 \\\n                --max_len 1560 \\\n                --max_src_len 1024 \\\n                --learning_rate 1e-4 \\\n                --weight_decay 0.1 \\\n                --num_train_epochs 2 \\\n                --gradient_accumulation_steps 4 \\\n                --warmup_ratio 0.1 \\\n                --mode glm2 \\\n                --train_type ptuning \\\n                --seed 1234 \\\n                --ds_file ds_zero2_no_offload.json \\\n                --gradient_checkpointing \\\n                --show_loss_step 10 \\\n                --pre_seq_len 16 \\\n                --prefix_projection True \\\n                --output_dir ./output-glm2\n```\nChatGLM2四卡训练，通过CUDA_VISIBLE_DEVICES控制具体哪几块卡进行训练，如果不加该参数，表示使用运行机器上所有卡进行训练\n```\nCUDA_VISIBLE_DEVICES=0,1,2,3 deepspeed --master_port 520 train.py \\\n                --train_path data/spo_0.json \\\n                --model_name_or_path ChatGLM2-6B \\\n                --per_device_train_batch_size 1 \\\n                --max_len 1560 \\\n                --max_src_len 1024 \\\n                --learning_rate 1e-4 \\\n                --weight_decay 0.1 \\\n                --num_train_epochs 2 \\\n                --gradient_accumulation_steps 4 \\\n                --warmup_ratio 0.1 \\\n                --mode glm2 \\\n                --train_type ptuning \\\n                --seed 1234 \\\n                --ds_file ds_zero2_no_offload.json \\\n                --gradient_checkpointing \\\n                --show_loss_step 10 \\\n                --pre_seq_len 16 \\\n                --prefix_projection True \\\n                --output_dir ./output-glm2\n```\nChatGLM3单卡训练\n```\nCUDA_VISIBLE_DEVICES=0 deepspeed --master_port 520 train.py \\\n                --train_path data/spo_0.json \\\n                --model_name_or_path ChatGLM3-6B/ \\\n                --per_device_train_batch_size 1 \\\n                --max_len 1560 \\\n                --max_src_len 1024 \\\n                --learning_rate 1e-4 \\\n                --weight_decay 0.1 \\\n                --num_train_epochs 2 \\\n                --gradient_accumulation_steps 4 \\\n                --warmup_ratio 0.1 \\\n                --mode glm3 \\\n                --train_type ptuning \\\n                --seed 1234 \\\n                --ds_file ds_zero2_no_offload.json \\\n                --gradient_checkpointing \\\n                --show_loss_step 10 \\\n                --pre_seq_len 16 \\\n                --prefix_projection True \\\n                --output_dir ./output-glm3\n```\nChatGLM3四卡训练，通过CUDA_VISIBLE_DEVICES控制具体哪几块卡进行训练，如果不加该参数，表示使用运行机器上所有卡进行训练\n```\nCUDA_VISIBLE_DEVICES=0,1,2,3 deepspeed --master_port 520 train.py \\\n                --train_path data/spo_0.json \\\n                --model_name_or_path ChatGLM3-6B/ \\\n                --per_device_train_batch_size 1 \\\n                --max_len 1560 \\\n                --max_src_len 1024 \\\n                --learning_rate 1e-4 \\\n                --weight_decay 0.1 \\\n                --num_train_epochs 2 \\\n                --gradient_accumulation_steps 4 \\\n                --warmup_ratio 0.1 \\\n                --mode glm3 \\\n                --train_type ptuning \\\n                --seed 1234 \\\n                --ds_file ds_zero2_no_offload.json \\\n                --gradient_checkpointing \\\n                --show_loss_step 10 \\\n                --pre_seq_len 16 \\\n                --prefix_projection True \\\n                --output_dir ./output-glm3\n```\nPS：ChatGLM微调时所用显存要比ChatGLM2多，详细显存占比如下：\n\n| Model |  DeepSpeed-Stage |  Offload | Gradient Checkpointing |  Batch Size | Max Length | GPU-A40 Number | 所耗显存 |\n| ------- | ------ | ------  | ------ | ------ | ------  | ------ | ------ |\n| ChaGLM | zero2 | No | Yes | 1 | 768  | 1 | 43G |\n| ChaGLM | zero2 | No | No | 1 | 300  | 1 | 44G |\n| ChaGLM | zero2 | No | Yes | 1 | 1560  | 4 | 37G |\n| ChaGLM | zero2 | No | No | 1 | 1360  | 4 | 44G |\n| ChaGLM2 | zero2 | No | Yes | 1 | 1560  | 1 | 20G |\n| ChaGLM2 | zero2 | No | No | 1 | 1560  | 1 | 40G |\n| ChaGLM2 | zero2 | No | Yes | 1 | 1560  | 4 | 19G |\n| ChaGLM2 | zero2 | No | No | 1 | 1560  | 4 | 39G |\n\n\n### Lora方法\nLora方法，即在大型语言模型上对指定参数（权重矩阵）并行增加额外的低秩矩阵，并在模型训练过程中，仅训练额外增加的并行低秩矩阵的参数。\n当“秩值”远小于原始参数维度时，新增的低秩矩阵参数量也就很小。在下游任务tuning时，仅须训练很小的参数，但能获取较好的表现结果。\n\n![](images/Lora.png)\n- 论文：[paper](https://arxiv.org/abs/2106.09685)\n- 官方代码：[Github](https://github.com/microsoft/LoRA)\n- HuggingFace封装的peft库：[Github](https://github.com/huggingface/peft)\n\n微调代码，见train.py，核心部分如下：\n```python3\nmodel = MODE[args.mode][\"model\"].from_pretrained(args.model_name_or_path)\nlora_module_name = args.lora_module_name.split(\",\")\nconfig = LoraConfig(r=args.lora_dim,\n\t\t\t\t\tlora_alpha=args.lora_alpha,\n\t\t\t\t\ttarget_modules=lora_module_name,\n\t\t\t\t\tlora_dropout=args.lora_dropout,\n\t\t\t\t\tbias=\"none\",\n\t\t\t\t\ttask_type=\"CAUSAL_LM\",\n\t\t\t\t\tinference_mode=False,\n\t\t\t\t\t)\nmodel = get_peft_model(model, config)\nmodel.config.torch_dtype = torch.float32\n```\nPS: Lora训练之后，请先参数合并，在进行模型预测。\n\n训练代码均采用DeepSpeed进行训练，可设置参数包含train_path、model_name_or_path、mode、train_type、lora_dim、lora_alpha、lora_dropout、lora_module_name、ds_file、num_train_epochs、per_device_train_batch_size、gradient_accumulation_steps、output_dir等， 可根据自己的任务配置。\n\nChatGLM单卡训练\n```\nCUDA_VISIBLE_DEVICES=0 deepspeed --master_port 520 train.py \\\n              --train_path data/spo_0.json \\\n              --model_name_or_path ChatGLM-6B \\\n              --per_device_train_batch_size 1 \\\n              --max_len 1560 \\\n              --max_src_len 1024 \\\n              --learning_rate 1e-4 \\\n              --weight_decay 0.1 \\\n              --num_train_epochs 2 \\\n              --gradient_accumulation_steps 4 \\\n              --warmup_ratio 0.1 \\\n              --mode glm \\\n              --train_type lora \\\n              --lora_dim 16 \\\n              --lora_alpha 64 \\\n              --lora_dropout 0.1 \\\n              --lora_module_name \"query_key_value\" \\\n              --seed 1234 \\\n              --ds_file ds_zero2_no_offload.json \\\n              --gradient_checkpointing \\\n              --show_loss_step 10 \\\n              --output_dir ./output-glm\n```\nChatGLM四卡训练，通过CUDA_VISIBLE_DEVICES控制具体哪几块卡进行训练，如果不加该参数，表示使用运行机器上所有卡进行训练\n```\nCUDA_VISIBLE_DEVICES=0,1,2,3 deepspeed --master_port 520 train.py \\\n              --train_path data/spo_0.json \\\n              --model_name_or_path ChatGLM-6B \\\n              --per_device_train_batch_size 1 \\\n              --max_len 1560 \\\n              --max_src_len 1024 \\\n              --learning_rate 1e-4 \\\n              --weight_decay 0.1 \\\n              --num_train_epochs 2 \\\n              --gradient_accumulation_steps 4 \\\n              --warmup_ratio 0.1 \\\n              --mode glm \\\n              --train_type lora \\\n              --lora_dim 16 \\\n              --lora_alpha 64 \\\n              --lora_dropout 0.1 \\\n              --lora_module_name \"query_key_value\" \\\n              --seed 1234 \\\n              --ds_file ds_zero2_no_offload.json \\\n              --gradient_checkpointing \\\n              --show_loss_step 10 \\\n              --output_dir ./output-glm\n```\nChatGLM2单卡训练\n```\nCUDA_VISIBLE_DEVICES=0 deepspeed --master_port 520 train.py \\\n              --train_path data/spo_0.json \\\n              --model_name_or_path ChatGLM2-6B \\\n              --per_device_train_batch_size 1 \\\n              --max_len 1560 \\\n              --max_src_len 1024 \\\n              --learning_rate 1e-4 \\\n              --weight_decay 0.1 \\\n              --num_train_epochs 2 \\\n              --gradient_accumulation_steps 4 \\\n              --warmup_ratio 0.1 \\\n              --mode glm2 \\\n              --train_type lora \\\n              --lora_dim 16 \\\n              --lora_alpha 64 \\\n              --lora_dropout 0.1 \\\n              --lora_module_name \"query_key_value,dense_h_to_4h,dense_4h_to_h,dense\" \\\n              --seed 1234 \\\n              --ds_file ds_zero2_no_offload.json \\\n              --gradient_checkpointing \\\n              --show_loss_step 10 \\\n              --output_dir ./output-glm2\n```\nChatGLM2四卡训练，通过CUDA_VISIBLE_DEVICES控制具体哪几块卡进行训练，如果不加该参数，表示使用运行机器上所有卡进行训练\n```\nCUDA_VISIBLE_DEVICES=0,1,2,3 deepspeed --master_port 520 train.py \\\n              --train_path data/spo_0.json \\\n              --model_name_or_path ChatGLM2-6B \\\n              --per_device_train_batch_size 1 \\\n              --max_len 1560 \\\n              --max_src_len 1024 \\\n              --learning_rate 1e-4 \\\n              --weight_decay 0.1 \\\n              --num_train_epochs 2 \\\n              --gradient_accumulation_steps 4 \\\n              --warmup_ratio 0.1 \\\n              --mode glm2 \\\n              --train_type lora \\\n              --lora_dim 16 \\\n              --lora_alpha 64 \\\n              --lora_dropout 0.1 \\\n              --lora_module_name \"query_key_value,dense_h_to_4h,dense_4h_to_h,dense\" \\\n              --seed 1234 \\\n              --ds_file ds_zero2_no_offload.json \\\n              --gradient_checkpointing \\\n              --show_loss_step 10 \\\n              --output_dir ./output-glm2\n```\nChatGLM3单卡训练\n```\nCUDA_VISIBLE_DEVICES=0 deepspeed --master_port 520 train.py \\\n                --train_path data/spo_0.json \\\n                --model_name_or_path ChatGLM3-6B/ \\\n                --per_device_train_batch_size 1 \\\n                --max_len 1560 \\\n                --max_src_len 1024 \\\n                --learning_rate 1e-4 \\\n                --weight_decay 0.1 \\\n                --num_train_epochs 2 \\\n                --gradient_accumulation_steps 4 \\\n                --warmup_ratio 0.1 \\\n                --mode glm3 \\\n                --lora_dim 16 \\\n                --lora_alpha 64 \\\n                --lora_dropout 0.1 \\\n                --lora_module_name \"query_key_value,dense_h_to_4h,dense_4h_to_h,dense\" \\\n                --seed 1234 \\\n                --ds_file ds_zero2_no_offload.json \\\n                --gradient_checkpointing \\\n                --show_loss_step 10 \\\n                --output_dir ./output-glm3\n```\nChatGLM3四卡训练，通过CUDA_VISIBLE_DEVICES控制具体哪几块卡进行训练，如果不加该参数，表示使用运行机器上所有卡进行训练\n```\nCUDA_VISIBLE_DEVICES=0,1,2,3 deepspeed --master_port 520 train.py \\\n                --train_path data/spo_0.json \\\n                --model_name_or_path ChatGLM3-6B/ \\\n                --per_device_train_batch_size 1 \\\n                --max_len 1560 \\\n                --max_src_len 1024 \\\n                --learning_rate 1e-4 \\\n                --weight_decay 0.1 \\\n                --num_train_epochs 2 \\\n                --gradient_accumulation_steps 4 \\\n                --warmup_ratio 0.1 \\\n                --mode glm3 \\\n                --lora_dim 16 \\\n                --lora_alpha 64 \\\n                --lora_dropout 0.1 \\\n                --lora_module_name \"query_key_value,dense_h_to_4h,dense_4h_to_h,dense\" \\\n                --seed 1234 \\\n                --ds_file ds_zero2_no_offload.json \\\n                --gradient_checkpointing \\\n                --show_loss_step 10 \\\n                --output_dir ./output-glm3\n```\nPS：ChatGLM微调时所用显存要比ChatGLM2多，详细显存占比如下：\n\n| Model |  DeepSpeed-Stage |  Offload | Gradient Checkpointing |  Batch Size | Max Length | GPU-A40 Number | 所耗显存 |\n| ------- | ------ | ------  | ------ | ------ | ------  | ------ | ------ |\n| ChaGLM | zero2 | No | Yes | 1 | 1560  | 1 | 20G |\n| ChaGLM | zero2 | No | No | 1 | 1560  | 1 | 45G |\n| ChaGLM | zero2 | No | Yes | 1 | 1560  | 4 | 20G |\n| ChaGLM | zero2 | No | No | 1 | 1560  | 4 | 45G |\n| ChaGLM2 | zero2 | No | Yes | 1 | 1560  | 1 | 20G |\n| ChaGLM2 | zero2 | No | No | 1 | 1560  | 1 | 43G |\n| ChaGLM2 | zero2 | No | Yes | 1 | 1560  | 4 | 19G |\n| ChaGLM2 | zero2 | No | No | 1 | 1560  | 4 | 42G |\n\n注意：Lora方法在模型保存时仅保存了Lora训练参数，因此在模型预测时需要将模型参数进行合并，具体参考[merge_lora.py](./merge_lora.py)。\n\n### 全参方法\n全参方法，对大模型进行全量参数训练，主要借助DeepSpeed-Zero3方法，对模型参数进行多卡分割，并借助Offload方法，将优化器参数卸载到CPU上以解决显卡不足问题。\n\n微调代码，见train.py，核心部分如下：\n```python3\nmodel = MODE[args.mode][\"model\"].from_pretrained(args.model_name_or_path)\n```\n训练代码均采用DeepSpeed进行训练，可设置参数包含train_path、model_name_or_path、mode、train_type、ds_file、num_train_epochs、per_device_train_batch_size、gradient_accumulation_steps、output_dir等， 可根据自己的任务配置。\n\nChatGLM四卡训练，通过CUDA_VISIBLE_DEVICES控制具体哪几块卡进行训练，如果不加该参数，表示使用运行机器上所有卡进行训练\n```\nCUDA_VISIBLE_DEVICES=0,1,2,3 deepspeed --master_port 520 train.py \\\n              --train_path data/spo_0.json \\\n              --model_name_or_path ChatGLM-6B \\\n              --per_device_train_batch_size 1 \\\n              --max_len 1560 \\\n              --max_src_len 1024 \\\n              --learning_rate 1e-4 \\\n              --weight_decay 0.1 \\\n              --num_train_epochs 2 \\\n              --gradient_accumulation_steps 4 \\\n              --warmup_ratio 0.1 \\\n              --mode glm \\\n              --train_type all \\\n              --seed 1234 \\\n              --ds_file ds_zero3_offload.json \\\n              --gradient_checkpointing \\\n              --show_loss_step 10 \\\n              --output_dir ./output-glm\n```\nChatGLM2四卡训练，通过CUDA_VISIBLE_DEVICES控制具体哪几块卡进行训练，如果不加该参数，表示使用运行机器上所有卡进行训练\n```\nCUDA_VISIBLE_DEVICES=0,1,2,3 deepspeed --master_port 520 train.py \\\n              --train_path data/spo_0.json \\\n              --model_name_or_path ChatGLM2-6B \\\n              --per_device_train_batch_size 1 \\\n              --max_len 1560 \\\n              --max_src_len 1024 \\\n              --learning_rate 1e-4 \\\n              --weight_decay 0.1 \\\n              --num_train_epochs 2 \\\n              --gradient_accumulation_steps 4 \\\n              --warmup_ratio 0.1 \\\n              --mode glm2 \\\n              --train_type all \\\n              --seed 1234 \\\n              --ds_file ds_zero3_no_offload.json \\\n              --gradient_checkpointing \\\n              --show_loss_step 10 \\\n              --output_dir ./output-glm2\n```\nChatGLM3四卡训练，通过CUDA_VISIBLE_DEVICES控制具体哪几块卡进行训练，如果不加该参数，表示使用运行机器上所有卡进行训练\n```\nCCUDA_VISIBLE_DEVICES=0,1,2,3 deepspeed --master_port 520 train.py \\\n              --train_path data/spo_0.json \\\n              --model_name_or_path ChatGLM3-6B \\\n              --per_device_train_batch_size 1 \\\n              --max_len 1560 \\\n              --max_src_len 1024 \\\n              --learning_rate 1e-4 \\\n              --weight_decay 0.1 \\\n              --num_train_epochs 2 \\\n              --gradient_accumulation_steps 4 \\\n              --warmup_ratio 0.1 \\\n              --mode glm3 \\\n              --train_type all \\\n              --seed 1234 \\\n              --ds_file ds_zero3_no_offload.json \\\n              --gradient_checkpointing \\\n              --show_loss_step 10 \\\n              --output_dir ./output-glm3\n```\nPS：ChatGLM微调时所用显存要比ChatGLM2多，详细显存占比如下：\n\n| Model |  DeepSpeed-Stage |  Offload | Gradient Checkpointing |  Batch Size | Max Length | GPU-A40 Number | 所耗显存 |\n| ------- | ------ | ------  | ------ | ------ | ------  | ------ | ------ |\n| ChaGLM | zero3 | Yes | Yes | 1 | 1560  | 4 | 33G |\n| ChaGLM2 | zero3 | No | Yes | 1 | 1560  | 4 | 44G |\n| ChaGLM2 | zero3 | Yes | Yes | 1 | 1560  | 4 | 26G |\n\n后面补充DeepSpeed的Zero-Stage的相关内容说明。\n\n### 运行环境\n查看requirements.txt文件\n\n## 实验结果\n### 三元组抽取\n- 为了防止大模型的数据泄露，采用一个领域比赛数据集-[汽车工业故障模式关系抽取](https://www.datafountain.cn/competitions/584)，随机抽取50条作为测试集\n- 训练示例：\n```\n{\n    \"instruction\": \"你现在是一个信息抽取模型，请你帮我抽取出关系内容为\\\"性能故障\\\", \\\"部件故障\\\", \\\"组成\\\"和 \\\"检测工具\\\"的相关三元组，三元组内部用\\\"_\\\"连接，三元组之间用\\\\n分割。文本：\",\n    \"input\": \"故障现象：发动机水温高，风扇始终是低速转动，高速档不工作，开空调尤其如此。\",\n    \"output\": \"发动机_部件故障_水温高\\n风扇_部件故障_低速转动\"\n}\n```\n\n\n| 微调方法 |  PT-Only-Embedding |  PT | Freeze |  Lora | \n| ------- | ------ | ------  | ------ | ------ |\n| 测试结果F1 | 0.0 | 0.6283 | 0.5675 | 0.5359 |\n\n结构分析：\n- 效果为PT\u003eFreeze\u003eLora\u003ePT-Only-Embedding\n- PT-Only-Embedding效果很不理想，发现在训练时，最后的loss仅能收敛到2.几，而其他机制可以收敛到0.几。分析原因为，输出内容形式与原有语言模型任务相差很大，仅增加额外Embedding参数，不足以改变复杂的下游任务。\n- 上面测试仅代表个人测试结果，并且由于生成模型生成长度对推理耗时影响很大，因此可以其他数据会有不一样的结果。\n- 模型在指定任务上微调之后，并没有丧失原有能力，例如生成“帮我写个快排算法”，依然可以生成-快排代码。\n- 由于大模型微调都采用大量instruction进行模型训练，仅采用单一的指令进行微调时，对原来其他的指令影响不大，因此并没导致原来模型的能力丧失。\n\n很多同学在微调后出现了灾难性遗忘现象，但本项目的训练代码并没有出现，对“翻译任务”、“代码任务”、“问答任务”进行测试，具体测试效果如下：\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003e翻译任务\u003c/b\u003e\u003c/summary\u003e\n\n![](images/ft_fanyi.png)\n\n\u003c/details\u003e\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003e代码任务\u003c/b\u003e\u003c/summary\u003e\n\n![](images/ft_code.png)\n\n\u003c/details\u003e\n\u003cdetails\u003e\u003csummary\u003e\u003cb\u003e问答任务\u003c/b\u003e\u003c/summary\u003e\n\n![](images/ft_qa.png)\n\n\u003c/details\u003e\n\n### 文本生成\n- 为了防止大模型的数据泄露，采用一个“万创杯”中医药天池大数据竞赛-[中医文献问题生成挑战](https://tianchi.aliyun.com/competition/entrance/531826/introduction)，随机抽取20条作为测试集\n- PT为官方的P-Tuning V2训练方法，PT-Only-Embedding表示仅对Embedding进行soft-prompt，Freeze仅训练模型后五层参数，Lora采用低秩矩阵方法训练，秩为8；\n- 训练示例：\n```\n{\n    \"instruction\": \"你现在是一个问题生成模型，请根据下面文档生成一个问题，文档：\",\n    \"input\": \"清热解毒口服液由生石膏、知母、紫花地丁、金银花、麦门冬、黄芩、玄参、连翘、龙胆草、生地黄、栀子、板蓝根组成。具有疏风解表、清热解毒利咽、生津止渴的功效，适用于治疗外感时邪、内有蕴热所致的身热汗出、头痛身痛、心烦口渴、微恶寒或反恶热、舌红、苔黄、脉数等症。现代临床主要用于治疗流行性感冒、流行性脑脊髓膜炎、肺炎等各种发热性疾病。口服液：每支10毫升，每次10~20毫升，每日3次。〔注意事项〕阳虚便澹者不宜使用。\",\n    \"output\": \"清热解毒口服的功效有哪些？\"\n}\n```\n\n由于生成模型的内容不能想信息抽取任务一样评价，用现有的BLUE或者Rouge来评价也是不合适，因此制定了评分规则。 通过多样性和准确性两个角度判断D2Q模型好坏，每个样本总计5分，共20个样本。\n- 多样性：\n\t- 问题是否高度相似，每重复一个问题扣0.25分；\n\t- 问题对应答案是否相同，每有一个重复答案或找不到答案，扣0.25分；\n- 准确性：\n\t- 问题能否从文档中找到答案，每有一个找不到答案，扣0.25分；\n\t- 问题内容是否流畅，每有一个问题不流畅，扣0.25分；\n\t- 问题内容是否有害，每有一个有害，扣0.25分；\n\n| 微调方法 |  原始模型 | PT-Only-Embedding |  PT | Freeze |  Lora | \n| ------- | ------ | ------ | ------  | ------ | ------ |\n| 分数 | 51.75 | 73.75 | 87.75 | 79.25 | 86.75 |\n\n\n## 流水线并行训练\n代码说明见：[大模型流水线并行（Pipeline）实战](https://zhuanlan.zhihu.com/p/636488690)\n\n请看[v0.1 Tag](https://github.com/liucongg/ChatGLM-Finetuning/tree/v0.1)\n\n## Star History\n![Star History Chart](https://api.star-history.com/svg?repos=liucongg/ChatGLM-Finetuning\u0026type=Date)","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fliucongg%2Fchatglm-finetuning","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fliucongg%2Fchatglm-finetuning","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fliucongg%2Fchatglm-finetuning/lists"}