找回密码
 立即注册
查看: 307|回复: 0

从0到1基于ChatGLM-6B使用LaRA进行参数高效微调

[复制链接]
发表于 2024-7-15 19:00 | 显示全部楼层 |阅读模式
之前测验考试了基于LLaMA使用LoRA进行参数高效微调,有被惊艳到。相对于full finetuning,使用LaRA显著提升了训练的速度。
虽然 LLaMA 在英文上具有强大的零样本学习和迁移能力,但是由于在预训练阶段 LLaMA 几乎没有见过中文语料。因此,它的中文能力很弱,即使对其进行有监督的微调,同等参数规模下,它的中文能力也是要弱于bloom-7b1、chatglm-6b等。
下面,我们来测验考试基于中英双语的对话语言模型ChatGLM-6B使用LoRA进行参数高效微调,相关代码放置在GitHub上面:llm-action
ChatGLM-6B简介

ChatGLM-6B 是一个开源的、撑持中英双语的对话语言模型,基于 General Language Model (GLM) 架构,具有 62 亿参数。ChatGLM-6B 使用了和 ChatGPT 相似的技术,针对中文问答和对话进行了优化。颠末约 1T 标识符的中英双语训练,辅以监督微调、反馈自助、人类反馈强化学习等技术的加持,62 亿参数的 ChatGLM-6B 已经能生成相当符合人类偏好的回答。
不外,由于 ChatGLM-6B 的规模较小,目前已知其具有相当多的局限性,如事实性/数学逻辑错误,可能生成有害/有成见内容,较弱的上下文能力,自我认知混乱,以及对英文指示生成与中文指示完全矛盾的内容。
具备的一些能力

自我认知、提纲写作、案牍写作、邮件写作助手、信息抽取、角色扮演、评论斗劲、旅游向导等
局限性

由于 ChatGLM-6B 的小规模,其能力仍然有许多局限性。以下是我们目前发现的一些问题:

  • 模型容量较小:6B 的小容量,决定了其相对较弱的模型记忆和语言能力。在面对许多事实性常识任务时,ChatGLM-6B 可能会生成不正确的信息;它也不擅长逻辑类问题(如数学、编程)的解答。
  • 发生有害说明或有成见的内容:ChatGLM-6B 只是一个初步与人类意图对齐的语言模型,可能会生成有害、有成见的内容。(内容可能具有冲犯性,此处不展示)
  • 英文能力不足:ChatGLM-6B 训练时使用的指示/回答大部门都是中文的,仅有极小一部门英文内容。因此,如果输入英文指示,答复的质量远不如中文,甚至与中文指示下的内容矛盾,而且呈现中英夹杂的情况。
  • 易被误导,对话能力较弱:ChatGLM-6B 对话能力还斗劲弱,而且 “自我认知” 存在问题,并很容易被误导并发生错误的言论。例如当前版本的模型在被误导的情况下,会在自我认知上发生偏差。
LoRA 技术道理




image.png

LoRA 的道理其实并不复杂,它的核心思想是在原始预训练语言模型旁边增加一个旁路,做一个降维再升维的操作,来模拟所谓的 intrinsic rank(预训练模型在各类下游任务上泛化的过程其实就是在优化各类任务的公共低维本征(low-dimensional intrinsic)子空间中非常少量的几个自由参数)。训练的时候固定预训练语言模型的参数,只训练降维矩阵 A 与升维矩阵 B。而模型的输入输出维度不变,输出时将 BA 与预训练语言模型的参数叠加。用随机高斯分布初始化 A,用 0 矩阵初始化 B。这样能保证训练开始时,新增的通路BA=0从,而对模型成果没有影响。
在推理时,将摆布两部门的成果加到一起即可,h=Wx+BAx=(W+BA)x,所以,只要将训练完成的矩阵乘积BA跟原本的权重矩阵W加到一起作为新权重参数替换原始预训练语言模型的W即可,不会增加额外的计算资源。
LoRA 的最大优势是速度更快,使用的内存更少;因此,可以在消费级硬件上运行。
环境搭建

基础环境配置如下:

  • 操作系统: CentOS 7
  • CPUs: 单个节点具有 1TB 内存的 Intel CPU,物理CPU个数为64,每颗CPU核数为16
  • GPUs: 8 卡 A800 80GB GPUs
  • Python: 3.10 (需要先升级OpenSSL到1.1.1t版本(点击下载OpenSSL),然后再编译安装Python),点击下载Python
  • NVIDIA驱动法式版本: 515.65.01,按照分歧型号选择分歧的驱动法式,点击下载
  • CUDA东西包: 11.7,点击下载
  • NCCL: nccl_2.14.3-1+cuda11.7,点击下载
  • cuDNN: 8.8.1.3_cuda11,点击下载
上面的NVIDIA驱动、CUDA、Python等东西的安装就纷歧一赘述了。
创建虚拟环境并激活虚拟环境chatglm-lora-venv-py310-cu117:
  1. cd /home/guodong.li/virtual-venv
  2. virtualenv -p /usr/bin/python3.10 chatglm-lora-venv-py310-cu117
  3. source /home/guodong.li/virtual-venv/chatglm-lora-venv-py310-cu117/bin/activate
复制代码
离线安装PyTorch,点击下载对应cuda版本的torch和torchvision即可。
  1. pip install torch-1.13.1+cu117-cp310-cp310-linux_x86_64.whl
  2. pip install torchvision-0.14.1+cu117-cp310-cp310-linux_x86_64.whl
复制代码
安装相关的库。
  1. pip install -r requirements.txt
复制代码
requirements.txt文件内容如下:
  1. # int8
  2. bitsandbytes==0.37.1
  3. accelerate==0.17.1
  4. # chatglm
  5. protobuf>=3.19.5,<3.20.1
  6. transformers==4.27.1
  7. icetk
  8. cpm_kernels==1.0.11
  9. #torch>=1.13.1
  10. tensorboard
  11. datasets==2.10.1
复制代码
安装PEFT,PEFT 是一个库(LoRA 是其撑持的技术之一,除此之外还有Prefix Tuning、P-Tuning、Prompt Tuning),可以让你使用各种基于 Transformer 布局的语言模型进行高效微调。
  1. git clone https://github.com/huggingface/peft.git
  2. cd peft/
  3. git checkout e536616
  4. pip install .
复制代码
数据集筹备

本文采用Stanford Alpaca中提供的alpaca_data.json指令数据集进行参数高效微调,但是在Alpaca-LoRA中提到该数据集存在一些噪声,因此,他们对该数据集做了清洗后得到了alpaca_data_cleaned.json文件。采用该数据集进行训练概略率会得到更好成果。
数据预措置

下载ChatGLM-Tuning代码,并切换到对应的commitid保证代码的一致性。
  1. git clone https://github.com/mymusise/ChatGLM-Tuning.git
  2. cd ChatGLM-Tuning
  3. git checkout 9973930
复制代码
转化alpaca数据集为jsonl格式,即每行一条json语料。
  1. python cover_alpaca2jsonl.py \
  2.   --data_path /data/nfs/guodong.li/data/alpaca_data_cleaned.json \
  3.   --save_path /data/nfs/guodong.li/data/alpaca_data_cleaned.jsonl
复制代码
查当作果:
  1. > head -n10 /data/nfs/guodong.li/data/alpaca_data_cleaned.jsonl
  2. > {”context”: ”Instruction: Give three tips for staying healthy.\nAnswer: ”, ”target”: ”1.Eat a balanced diet and make sure to include plenty of fruits and vegetables. \n2. Exercise regularly to keep your body active and strong. \n3. Get enough sleep and maintain a consistent sleep schedule.”}
  3. > {”context”: ”Instruction: What are the three primary colors?\nAnswer: ”, ”target”: ”The three primary colors are red, blue, and yellow.”}
  4. > {”context”: ”Instruction: Describe the structure of an atom.\nAnswer: ”, ”target”: ”An atom is made up of a nucleus, which contains protons and neutrons, surrounded by electrons that travel in orbits around the nucleus. The protons and neutrons have a positive charge, while the electrons have a negative charge, resulting in an overall neutral atom. The number of each particle determines the atomic number and the type of atom.”}
  5. > {”context”: ”Instruction: How can we reduce air pollution?\nAnswer: ”, ”target”: ”There are a number of ways to reduce air pollution, such as shifting to renewable energy sources, encouraging the use of public transportation, prohibiting the burning of fossil fuels, implementing policies to reduce emissions from industrial sources, and implementing vehicle emissions standards. Additionally, individuals can do their part to reduce air pollution by reducing car use, avoiding burning materials such as wood, and changing to energy efficient appliances.”}
  6. > {”context”: ”Instruction: Pretend you are a project manager of a construction company. Describe a time when you had to make a difficult decision.\nAnswer: ”, ”target”: ”I had to make a difficult decision when I was working as a project manager at a construction company. I was in charge of a project that needed to be completed by a certain date in order to meet the client\u2019s expectations. However, due to unexpected delays, we were not able to meet the deadline and so I had to make a difficult decision. I decided to extend the deadline, but I had to stretch the team\u2019s resources even further and increase the budget. Although it was a risky decision, I ultimately decided to go ahead with it to ensure that the project was completed on time and that the client\u2019s expectations were met. The project was eventually successfully completed and this was seen as a testament to my leadership and decision-making abilities.”}
  7. > {”context”: ”Instruction: Identify the odd one out.\nInput: Twitter, Instagram, Telegram\nAnswer: ”, ”target”: ”Telegram”}
  8. > {”context”: ”Instruction: Explain why the following fraction is equivalent to 1/4\nInput: 4/16\nAnswer: ”, ”target”: ”The fraction 4/16 is equivalent to 1/4 because both numerators and denominators are divisible by 4. Dividing both the top and bottom numbers by 4 yields the fraction 1/4.”}
  9. > {”context”: ”Instruction: Write a short story in third person narration about a protagonist who has to make an important career decision.\nAnswer: ”, ”target”: ”John was at a crossroads in his life. He had just graduated college and was now facing the big decision of what career to pursue. After much deliberation, he decided that he wanted to be an accountant and help the financially disadvantaged. He had always been good with numbers and enjoyed seeing the tangible results of his work. \n\nJohn enrolled in accounting courses and initially found it quite challenging. He had to learn multiple systems and regulations quickly, but he worked hard and eventually excelled in his studies. After a few years, John started working at an accounting firm in his city. He was eager to put his knowledge of taxes and accounting to use in a real-world setting.\n\nJohn loved his job, as it let him express his creativity in finding strategies to save his clients money. After a few years at the firm, he became a senior accountant and was asked to manage bigger and more challenging cases. He was now a respected figure in the financial industry, but he still remembers when he was just a recent college graduate, unsure of the direction in which his life would take him.”}
  10. > {”context”: ”Instruction: Render a 3D model of a house\nAnswer: ”, ”target”: ”<nooutput> This type of instruction cannot be fulfilled by a GPT model.”}
  11. > {”context”: ”Instruction: Evaluate this sentence for spelling and grammar mistakes\nInput: He finnished his meal and left the resturant\nAnswer: ”, ”target”: ”He finished his meal and left the restaurant.”}
复制代码
对预措置后的语料进行分词并保留。
  1. # 预先创建输出分词后的目录
  2. mkdir -p /data/nfs/guodong.li/data/alpaca_tokenize
  3. python tokenize_dataset_rows.py \
  4. \--jsonl_path  /data/nfs/guodong.li/data/alpaca_data_cleaned.jsonl  \
  5. \--save_path /data/nfs/guodong.li/data/alpaca_tokenize \
  6. \--max_seq_length 200 \
  7. \--skip_overlength True
复制代码
参数说明:

  • --jsonl_path 微调的数据路径, 格式jsonl, 对每行的[&#39;context&#39;]和[&#39;target&#39;]字段进行encode
  • --save_path 输出路径
  • --max_seq_length 样本的最大长度
查看措置之后的成果:
  1. > ls -al --block-size=K /data/nfs/guodong.li/data/alpaca_tokenize
  2. total 15588K
  3. drwxrwxr-x 1 nobody nobody     0K Apr 13 14:06 .
  4. drwxr-xr-x 1 nobody nobody     0K Apr 13 14:06 ..
  5. -rw-rw-r-- 1 nobody nobody 15578K Apr 13 14:06 data-00000-of-00001.arrow
  6. -rw-rw-r-- 1 nobody nobody     1K Apr 13 14:06 dataset_info.json # 数据集信息文件
  7. -rw-rw-r-- 1 nobody nobody     1K Apr 13 14:06 state.json
复制代码
参数高效微调

单卡模式模型训练

改削finetune.py文件:
  1. # TODO
  2. # tokenizer = AutoTokenizer.from_pretrained(”THUDM/chatglm-6b”, trust_remote_code=True)
  3. tokenizer = AutoTokenizer.from_pretrained(”/data/nfs/llm/model/chatglm-6b”, trust_remote_code=True)
  4. ...
  5. def main():
  6.     ...
  7.     # TODO
  8.     ”””
  9.     model = AutoModel.from_pretrained(
  10.         ”THUDM/chatglm-6b”, load_in_8bit=True, trust_remote_code=True, device_map=”auto”
  11.     )
  12.     ”””
  13.     model = AutoModel.from_pretrained(
  14.          ”/data/nfs/llm/model/chatglm-6b”, load_in_8bit=True, trust_remote_code=True, device_map=”auto”
  15.     )
复制代码
运行命令:
  1. python finetune.py \
  2.     --dataset_path /data/nfs/guodong.li/data/alpaca_tokenize \
  3.     --lora_rank 8 \
  4.     --per_device_train_batch_size 6 \
  5.     --gradient_accumulation_steps 1 \
  6.     --max_steps 52000 \
  7.     --save_steps 1000 \
  8.     --save_total_limit 2 \
  9.     --learning_rate 1e-4 \
  10.     --fp16 \
  11.     --remove_unused_columns false \
  12.     --logging_steps 50 \
  13.     --output_dir /home/guodong.li/data/chatglm-6b-lora
复制代码
运行过程:
  1. {&#39;loss&#39;: 2.2081, &#39;learning_rate&#39;: 9.991153846153847e-05, &#39;epoch&#39;: 0.01}
  2. ...
  3. {&#39;loss&#39;: 1.7604, &#39;learning_rate&#39;: 9.904615384615386e-05, &#39;epoch&#39;: 0.06}
  4. {&#39;loss&#39;: 1.7521, &#39;learning_rate&#39;: 9.895e-05, &#39;epoch&#39;: 0.07}
  5.   1%|█▌                         | 588/52000 [11:42<16:38:08,  1.16s/it]
复制代码
貌似很慢,测验考试增大batch_size和gradient_accumulation_steps来提升。
  1. python finetune.py \
  2.   --dataset_path /data/nfs/guodong.li/data/alpaca_tokenize \
  3.   --lora_rank 8 \
  4.   --per_device_train_batch_size 32 \
  5.   --gradient_accumulation_steps 4 \
  6.   --num_train_epochs 3 \
  7.   --save_steps 1000 \
  8.   --save_total_limit 2 \
  9.   --learning_rate 1e-4 \
  10.   --fp16 \
  11.   --remove_unused_columns false \
  12.   --logging_steps 50 \
  13.   --output_dir /home/guodong.li/data/chatglm-6b-lora
复制代码
运行过程:
  1. 0%|                     | 0/1167 [00:00<?, ?it/s]
  2. {&#39;loss&#39;: 2.142, &#39;learning_rate&#39;: 9.571550985432734e-05, &#39;epoch&#39;: 0.13}
  3. 8%|██████████▊         | 89/1167 [33:17<6:30:07, 21.71s/it]
复制代码
速度提升上去了,但是还是在单卡模式下进行训练,下面测验考试使用数据并行技术来进一步提升训练速度。
数据并行模式模型训练

首先,拷贝finetune.py文件为finetune_dp.py。
  1. cp finetune.py finetune_dp.py
复制代码
然后,改削finetune_dp.py文件。
  1. # TODO
  2. # tokenizer = AutoTokenizer.from_pretrained(”THUDM/chatglm-6b”, trust_remote_code=True)
  3. tokenizer = AutoTokenizer.from_pretrained(”/data/nfs/llm/model/chatglm-6b”, trust_remote_code=True, revision=””)
  4. ...
  5. def main():
  6.     writer = SummaryWriter()
  7.     finetune_args, training_args = HfArgumentParser(
  8.         (FinetuneArguments, TrainingArguments)
  9.     ).parse_args_into_dataclasses()
  10.     # init model
  11.     # TODO
  12.     ”””
  13.     model = AutoModel.from_pretrained(
  14.         ”THUDM/chatglm-6b”, load_in_8bit=True, trust_remote_code=True, device_map=”auto”
  15.     )
  16.     ”””
  17.     while True:
  18.         try:
  19.             model = AutoModel.from_pretrained(”/data/nfs/llm/model/chatglm-6b”, trust_remote_code=True, revision=””)
  20.             break
  21.         except:
  22.             pass
  23.     model.gradient_checkpointing_enable()
  24.     model.enable_input_require_grads()
  25.     # TODO
  26.     #model.is_parallelizable = True
  27.     #model.model_parallel = True
  28.     model.lm_head = CastOutputToFloat(model.lm_head)
  29.     model.config.use_cache = (
  30.         False  # silence the warnings. Please re-enable for inference!
  31.     )
  32.     # setup peft
  33.     peft_config = LoraConfig(
  34.         task_type=TaskType.CAUSAL_LM,
  35.         inference_mode=False,
  36.         r=finetune_args.lora_rank,
  37.         lora_alpha=32,
  38.         lora_dropout=0.1,
  39.     )
  40.     model = get_peft_model(model, peft_config)
  41.     # load dataset
  42.     dataset = datasets.load_from_disk(finetune_args.dataset_path)
  43.     print(f”\n{len(dataset)=}\n”)
  44.     training_args.ddp_find_unused_parameters=False
  45.     # start train
  46.     trainer = ModifiedTrainer(
  47.         model=model,
  48.         train_dataset=dataset,
  49.         args=training_args,
  50.         callbacks=[TensorBoardCallback(writer)],
  51.         data_collator=data_collator,
  52.     )
  53.     trainer.train()
  54.     writer.close()
  55.     # save model
  56.     model.save_pretrained(training_args.output_dir)
复制代码
注意:
chatglm加载模型时会调用transformers/dynamic_module_utils.py文件下的get_class_in_module方式,而该方式在并发情况下会存在找不到文件的问题。本文在法式中加了个while True进行简单的容错措置,因此,呈现FileNotFoundError可以忽略。
运行命令:
  1. torchrun --nproc_per_node=4 --master_port=29005 finetune_dp.py \
  2.   --dataset_path /data/nfs/guodong.li/data/alpaca_tokenize \
  3.   --lora_rank 8 \
  4.   --per_device_train_batch_size 40 \
  5.   --gradient_accumulation_steps 4 \
  6.   --num_train_epochs 3 \
  7.   --save_steps 1000 \
  8.   --save_total_limit 2 \
  9.   --learning_rate 1e-4 \
  10.   --fp16 \
  11.   --remove_unused_columns false \
  12.   --logging_steps 50 \
  13.   --output_dir /home/guodong.li/data/chatglm-6b-lora
复制代码
运行成果:
  1. WARNING:torch.distributed.run:
  2. *****************************************
  3. Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed.
  4. *****************************************
  5. ===================================BUG REPORT===================================
  6. Welcome to bitsandbytes. For bug reports, please submit your error trace to: https://github.com/TimDettmers/bitsandbytes/issues
  7. ================================================================================
  8. ...
  9. /home/guodong.li/virtual-venv/chatglm-lora-venv-py310-cu117/lib/python3.10/site-packages/bitsandbytes/cuda_setup/main.py:136: UserWarning: WARNING: The following directories listed in your path were found to be non-existent: {PosixPath(&#39;/opt/rh/devtoolset-7/root/usr/lib/dyninst&#39;), PosixPath(&#39;/opt/rh/devtoolset-9/root/usr/lib/dyninst&#39;)}
  10.   warn(msg)
  11. CUDA SETUP: CUDA runtime path found: /usr/local/cuda-11.7/lib64/libcudart.so
  12. CUDA SETUP: Highest compute capability among GPUs detected: 8.0
  13. CUDA SETUP: Detected CUDA version 117
  14. CUDA SETUP: Loading binary /home/guodong.li/virtual-venv/chatglm-lora-venv-py310-cu117/lib/python3.10/site-packages/bitsandbytes/libbitsandbytes_cuda117.so...
  15. /home/guodong.li/virtual-venv/chatglm-lora-venv-py310-cu117/lib/python3.10/site-packages/bitsandbytes/cuda_setup/main.py:136: UserWarning: WARNING: The following directories listed in your path were found to be non-existent: {PosixPath(&#39;/opt/rh/devtoolset-9/root/usr/lib/dyninst&#39;), PosixPath(&#39;/opt/rh/devtoolset-7/root/usr/lib/dyninst&#39;)}
  16. ...
  17. CUDA SETUP: CUDA runtime path found: /usr/local/cuda-11.7/lib64/libcudart.so
  18. CUDA SETUP: Highest compute capability among GPUs detected: 8.0
  19. CUDA SETUP: Detected CUDA version 117
  20. CUDA SETUP: Loading binary /home/guodong.li/virtual-venv/chatglm-lora-venv-py310-cu117/lib/python3.10/site-packages/bitsandbytes/libbitsandbytes_cuda117.so...
  21. ...
  22. Loading checkpoint shards: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 8/8 [00:16<00:00,  2.05s/it]
  23. /home/guodong.li/virtual-venv/chatglm-lora-venv-py310-cu117/lib/python3.10/site-packages/peft/tuners/lora.py:191: UserWarning: fan_in_fan_out is set to True but the target module is not a Conv1D. Setting fan_in_fan_out to False.
  24.   warnings.warn(
  25. Loading checkpoint shards: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 8/8 [00:17<00:00,  2.17s/it]
  26. /home/guodong.li/virtual-venv/chatglm-lora-venv-py310-cu117/lib/python3.10/site-packages/peft/tuners/lora.py:191: UserWarning: fan_in_fan_out is set to True but the target module is not a Conv1D. Setting fan_in_fan_out to False.
  27.   warnings.warn(
  28. Loading checkpoint shards: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 8/8 [00:20<00:00,  2.54s/it]
  29. /home/guodong.li/virtual-venv/chatglm-lora-venv-py310-cu117/lib/python3.10/site-packages/peft/tuners/lora.py:191: UserWarning: fan_in_fan_out is set to True but the target module is not a Conv1D. Setting fan_in_fan_out to False.
  30.   warnings.warn(
  31. Loading checkpoint shards: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 8/8 [00:21<00:00,  2.63s/it]
  32. len(dataset)=49847
  33. len(dataset)=49847
  34. len(dataset)=49847
  35. len(dataset)=49847
  36. {&#39;loss&#39;: 2.1301, &#39;learning_rate&#39;: 7.863247863247864e-05, &#39;epoch&#39;: 0.64}
  37. {&#39;loss&#39;: 1.8471, &#39;learning_rate&#39;: 5.726495726495726e-05, &#39;epoch&#39;: 1.28}
  38. {&#39;loss&#39;: 1.7966, &#39;learning_rate&#39;: 3.58974358974359e-05, &#39;epoch&#39;: 1.92}
  39. {&#39;loss&#39;: 1.7829, &#39;learning_rate&#39;: 1.4529914529914531e-05, &#39;epoch&#39;: 2.56}
  40. {&#39;train_runtime&#39;: 2654.3961, &#39;train_samples_per_second&#39;: 56.337, &#39;train_steps_per_second&#39;: 0.088, &#39;train_loss&#39;: 1.8721362872001452, &#39;epoch&#39;: 3.0}
  41. 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 234/234 [44:13<00:00, 11.34s/it]
复制代码
显存占用:
  1. Thu Apr 13 20:20:05 2023
  2. +-----------------------------------------------------------------------------+
  3. | NVIDIA-SMI 515.105.01   Driver Version: 515.105.01   CUDA Version: 11.7     |
  4. |-------------------------------+----------------------+----------------------+
  5. | GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
  6. | Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
  7. |                               |                      |               MIG M. |
  8. |===============================+======================+======================|
  9. |   0  NVIDIA A800 80G...  Off  | 00000000:34:00.0 Off |                    0 |
  10. | N/A   67C    P0   271W / 300W |  33429MiB / 81920MiB |    100%      Default |
  11. |                               |                      |             Disabled |
  12. +-------------------------------+----------------------+----------------------+
  13. |   1  NVIDIA A800 80G...  Off  | 00000000:35:00.0 Off |                    0 |
  14. | N/A   68C    P0   342W / 300W |  52621MiB / 81920MiB |    100%      Default |
  15. |                               |                      |             Disabled |
  16. +-------------------------------+----------------------+----------------------+
  17. |   2  NVIDIA A800 80G...  Off  | 00000000:36:00.0 Off |                    0 |
  18. | N/A   68C    P0   241W / 300W |  75273MiB / 81920MiB |    100%      Default |
  19. |                               |                      |             Disabled |
  20. +-------------------------------+----------------------+----------------------+
  21. |   3  NVIDIA A800 80G...  Off  | 00000000:37:00.0 Off |                    0 |
  22. | N/A   70C    P0   341W / 300W |  29897MiB / 81920MiB |    100%      Default |
  23. |                               |                      |             Disabled |
  24. +-------------------------------+----------------------+----------------------+
  25. +-----------------------------------------------------------------------------+
  26. | Processes:                                                                  |
  27. |  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
  28. |        ID   ID                                                   Usage      |
  29. |=============================================================================|
  30. |    0   N/A  N/A     55827      C   ...nv-py310-cu117/bin/python    33427MiB |
  31. |    1   N/A  N/A     55828      C   ...nv-py310-cu117/bin/python    52619MiB |
  32. |    2   N/A  N/A     55829      C   ...nv-py310-cu117/bin/python    75271MiB |
  33. |    3   N/A  N/A     55830      C   ...nv-py310-cu117/bin/python    29895MiB |
  34. +-----------------------------------------------------------------------------+
复制代码
模型输出文件:
  1. > ls -al
  2. total 14368
  3. drwxrwxr-x  3 guodong.li guodong.li       86 Apr 13 20:00 .
  4. drwxrwxr-x 12 guodong.li guodong.li      206 Apr 13 11:13 ..
  5. -rw-rw-r--  1 guodong.li guodong.li      425 Apr 13 20:00 adapter_config.json
  6. -rw-rw-r--  1 guodong.li guodong.li 14700953 Apr 13 20:00 adapter_model.bin
  7. drwxrwxr-x 13 guodong.li guodong.li     4096 Apr 13 19:15 runs
复制代码
至此,整个训练过程就完成了,接下来使用生成的模型进行推理。
模型推理

新增推理代码inference.py:
  1. from transformers import AutoModel,AutoTokenizer
  2. import torch
  3. from peft import PeftModel
  4. import json
  5. from cover_alpaca2jsonl import format_example
  6. device = torch.device(”cuda:0”) if torch.cuda.is_available() else torch.device(”cpu”)
  7. model = AutoModel.from_pretrained(”/data/nfs/llm/model/chatglm-6b”, trust_remote_code=True, load_in_8bit=True, device_map=&#39;auto&#39;, revision=””)
  8. tokenizer = AutoTokenizer.from_pretrained(”/data/nfs/llm/model/chatglm-6b”, trust_remote_code=True,  revision=””)
  9. model = PeftModel.from_pretrained(model, ”/home/guodong.li/data/chatglm-6b-lora”)
  10. # TODO
  11. instructions = json.load(open(”/data/nfs/guodong.li/data/alpaca_data_cleaned.json”))
  12. answers = []
  13. with torch.no_grad():
  14.     for idx, item in enumerate(instructions[:3]):
  15.         feature = format_example(item)
  16.         input_text = feature[&#39;context&#39;]
  17.         ids = tokenizer.encode(input_text)
  18.         input_ids = torch.LongTensor([ids])
  19.         input_ids = input_ids.to(device)
  20.         out = model.generate(
  21.             input_ids=input_ids,
  22.             max_length=150,
  23.             do_sample=False,
  24.             temperature=0
  25.         )
  26.         out_text = tokenizer.decode(out[0])
  27.         answer = out_text.replace(input_text, ””).replace(”\nEND”, ””).strip()
  28.         item[&#39;infer_answer&#39;] = answer
  29.         print(out_text)
  30.         print(f”### {idx+1}.Answer:\n”, item.get(&#39;output&#39;), &#39;\n\n&#39;)
  31.         answers.append({&#39;index&#39;: idx, **item})
复制代码
运行命令:
  1. CUDA_VISIBLE_DEVICES=0 python inference.py
复制代码
运行成果:
  1. > CUDA_VISIBLE_DEVICES=0 python inference.py
  2. ===================================BUG REPORT===================================
  3. Welcome to bitsandbytes. For bug reports, please submit your error trace to: https://github.com/TimDettmers/bitsandbytes/issues
  4. ================================================================================
  5. /home/guodong.li/virtual-venv/chatglm-lora-venv-py310-cu117/lib/python3.10/site-packages/bitsandbytes/cuda_setup/main.py:136: UserWarning: WARNING: The following directories listed in your path were found to be non-existent: {PosixPath(&#39;/opt/rh/devtoolset-7/root/usr/lib/dyninst&#39;), PosixPath(&#39;/opt/rh/devtoolset-9/root/usr/lib/dyninst&#39;)}
  6.   warn(msg)
  7. CUDA SETUP: CUDA runtime path found: /usr/local/cuda-11.7/lib64/libcudart.so
  8. CUDA SETUP: Highest compute capability among GPUs detected: 8.0
  9. CUDA SETUP: Detected CUDA version 117
  10. CUDA SETUP: Loading binary /home/guodong.li/virtual-venv/chatglm-lora-venv-py310-cu117/lib/python3.10/site-packages/bitsandbytes/libbitsandbytes_cuda117.so...
  11. Overriding torch_dtype=None with `torch_dtype=torch.float16` due to requirements of `bitsandbytes` to enable model loading in mixed int8. Either pass torch_dtype=torch.float16 or don&#39;t pass this argument at all to remove this warning.
  12. Loading checkpoint shards: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 8/8 [00:11<00:00,  1.39s/it]
  13. The dtype of attention mask (torch.int64) is not bool
  14. Instruction: Give three tips for staying healthy.
  15. Answer: Three tips for staying healthy include: 1) eating a balanced diet, 2) getting regular exercise, and 3) getting enough rest.
  16. ### 1.Answer:
  17. 1.Eat a balanced diet and make sure to include plenty of fruits and vegetables.
  18. 2. Exercise regularly to keep your body active and strong.
  19. 3. Get enough sleep and maintain a consistent sleep schedule.
  20. Instruction: What are the three primary colors?
  21. Answer: The three primary colors are red, blue, and yellow.
  22. ### 2.Answer:
  23. The three primary colors are red, blue, and yellow.
  24. Instruction: Describe the structure of an atom.
  25. Answer: An atom is a small particle of matter that contains a core of positive charge, surrounded by a cloud of negative charge. The positive charge is caused by the presence of an electron cloud, which is surrounded by an electron cloud. The negative charge is caused by the presence of an electron cloud, which is surrounded by an electron cloud. The positive and negative charges are balanced by the presence of an equal number of protons and neutrons.
  26. ### 3.Answer:
  27. An atom is made up of a nucleus, which contains protons and neutrons, surrounded by electrons that travel in orbits around the nucleus. The protons and neutrons have a positive charge, while the electrons have a negative charge, resulting in an overall neutral atom. The number of each particle determines the atomic number and the type of atom.
复制代码
此中:Answer: 是模型的输出,#### Answer: 是原答案。
结语

本文主要讲述了基于ChatGLM-6B使用LoRA进行参数高效微调以及使用训练好的模型对其进行推理,后续再基于ChatGLM-6B使用其他的参数高效微调技术。
参考文档

  • Alpaca-LoRA
  • Stanford Alpaca
  • ChatGLM-Tuning
<hr/>我叫果冻,如果感觉我的文章/回答能够辅佐到你,等候你的点赞,祝好~~~

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-11-21 21:16 , Processed in 0.179891 second(s), 24 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表