""" Borrowed and modified from https://github.com/tloen/alpaca-lora """ import argparse…
- User
""" Borrowed and modified from https://github.com/tloen/alpaca-lora """
import argparse import os import json import gc
import torch import transformers import peft from peft import PeftModel
parser = argparse.ArgumentParser() parser.add_argument('--base_model',default=None,required=True,type=str,help="Please specify a base_model") parser.add_argument('--lora_model',default=None,required=True,type=str,help="Please specify a lora_model")
deprecated; the script infers the model size from the checkpoint
parser.add_argument('--model_size',default='7B',type=str,help="Size of the LLaMA model",choices=['7B','13B'])
parser.add_argument('--offload_dir',default=None,type=str,help="(Optional) Please specify a temp folder for offloading (useful for low-RAM machines). Default None (disable offload).") parser.add_argument('--output_dir',default='./',type=str) args = parser.parse_args()
assert ( "LlamaTokenizer" in transformers._import_structure["models.llama"] ), "LLaMA is now in HuggingFace's main branch.\nPlease reinstall it: pip uninstall transformers && pip install git+https://github.com/huggingface/transformers.git" from transformers import LlamaTokenizer, LlamaForCausalLM
BASE_MODEL = args.base_model LORA_MODEL = args.lora_model output_dir = args.output_dir
assert ( BASE_MODEL ), "Please specify a BASE_MODEL in the script, e.g. 'decapoda-research/llama-7b-hf'"
tokenizer = LlamaTokenizer.from_pretrained(LORA_MODEL) if args.offload_dir is not None: # Load with offloading, which is useful for low-RAM machines. # Note that if you have enough RAM, please use original method instead, as it is faster. base_model = LlamaForCausalLM.from_pretrained( BASE_MODEL, load_in_8bit=False, torch_dtype=torch.float16, offload_folder=args.offload_dir, offload_state_dict=True, low_cpu_mem_usage=True, device_map={"": "cpu"}, ) else: # Original method without offloading base_model = LlamaForCausalLM.from_pretrained( BASE_MODEL, load_in_8bit=False, torch_dtype=torch.float16, device_map={"": "cpu"}, )
base_model.resize_token_embeddings(len(tokenizer)) assert base_model.get_input_embeddings().weight.size(0) == len(tokenizer) tokenizer.save_pretrained(output_dir) print(f"Extended vocabulary size: {len(tokenizer)}")
first_weight = base_model.model.layers[0].self_attn.q_proj.weight first_weight_old = first_weight.clone()
infer the model size from the checkpoint
emb_to_model_size = { 4096 : '7B', 5120 : '13B', 6656 : '30B', 8192 : '65B', } embedding_size = base_model.get_input_embeddings().weight.size(1) model_size = emb_to_model_size[embedding_size] print(f"Loading LoRA for {model_size} model")
lora_model = PeftModel.from_pretrained( base_model, LORA_MODEL, device_map={"": "cpu"}, torch_dtype=torch.float16, )
- Assistant
Summary
This script is used to convert a Llama model into a Lora model. It includes the conversion code and all necessary dependencies, including the Peft library.
Inputs
--base_model: (required) the name or path of the Llama-base model to be converted to Lora--lora_model: (required) the name or path to the Lora model to load weights from.--offload_dir: (optional) a temp directory to use for offloading data. Useful for low-RAM machines, but not required.--output_dir: (optional) the path to save output files. Default is the current directory.
Outputs
The script will output new files (in the
output_dirpath):- A
tokenizerfile (LLaMaTokenizer) for use with the new Lora model. - One or several
consolidated.0x.pthfiles, representing the Lora model weights - A
params.jsonfile containing hyperparameters of the model
Example
!python lora_convert.py --base_model decapoda-research/llama-7b-hf --lora_model decapoda-research/lora-7b --offload_dir 'offloading_folder/' --output_dir ./lora-model/ - User
我在调用这个代码时候报错Saving shard 1 of 1 into /mnt/workspace/datas/mergeLLamaOutPut/consolidated.00.pth Traceback (most recent call last): File "/home/pai/envs/llama/lib/python3.9/site-packages/torch/serialization.py", line 441, in save _save(obj, opened_zipfile, pickle_module, pickle_protocol) File "/home/pai/envs/llama/lib/python3.9/site-packages/torch/serialization.py", line 668, in _save zip_file.write_record(name, storage.data_ptr(), num_bytes) RuntimeError: [enforce fail at inline_container.cc:471] . PytorchStreamWriter failed writing file data/205: file write failed
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "/mnt/workspace/Chinese-LLaMA-Alpaca/scripts/merge_llama_with_chinese_lora.py", line 290, in save_shards(lora_model_sd=lora_model_sd, num_shards=num_shards) File "/mnt/workspace/Chinese-LLaMA-Alpaca/scripts/merge_llama_with_chinese_lora.py", line 220, in save_shards torch.save(new_state_dict, output_dir + "/consolidated.00.pth") File "/home/pai/envs/llama/lib/python3.9/site-packages/torch/serialization.py", line 442, in save return File "/home/pai/envs/llama/lib/python3.9/site-packages/torch/serialization.py", line 291, in exit self.file_like.write_end_of_file() RuntimeError: [enforce fail at inline_container.cc:337] . unexpected pos 5715263744 vs 5715263640
- Assistant
这看起来可能是 file write failed 错误,这可能与你的输出目录没有足够的空间有关。请确保你的输出目录足够大,并确保你有权限在该目录下进行写操作。你也可以尝试在另一个目录下运行代码。
- User
如何查询我的输出目录还有多少可用空间
- Assistant
你可以在命令行中使用
df命令来查询硬盘空间。在终端中输入df -h <your_output_directory>,它将显示你想要查看的输出目录的磁盘使用情况。注意 "Avail" 列,这是当前可用空间的总和,以字节为单位。例如,如果你想查看挂载在 /dev/sdb1 目录下的硬盘空间信息,请执行以下命令:
df -h /dev/sdb1该命令将在终端中显示 /dev/sdb1 目录下的可用磁盘空间。
- User
如何递归的查看当前目录下所有文件的大小,
- Assistant
你可以在命令行中使用
du命令来显示目录和子目录中的磁盘使用情况。 输入du -h <your_directory>来显示你指定目录(包括子目录)的磁盘使用情况。 -h 标志用于使结果以易于阅读的格式显示。例如,如果你想要查看当前目录下所有文件和子目录的大小,可以进入该目录并使用以下命令:
du -h该命令将递归地显示当前目录中的所有文件和子目录的大小。
- User
我如果只想查看一级目录的大小 该使用哪种命令
- Assistant
如果你只想查看当前目录中直接包含的文件和子目录的大小,可以使用以下命令:
du --max-depth=1 -h这将在当前目录中仅显示一级文件和子目录的大小,并将结果格式化以易于阅读的格式显示。
--max-depth=1指定了要显示的子目录的最大深度。 - User
/.git目录下面的内容可以删除吗
- Assistant
.git目录是 Git 存储版本控制信息的地方。如果你没有打算删除 Git 存储库并重新开始,那么.git目录下的东西通常不应该被删除,因为它们存储了受版本控制的所有数据。这些数据包括 Git 中所有的提交信息、分支、标签和配置设置等等。如果你删除 .git 目录,你将失去对这些信息的访问。如果你的意图是为了清理磁盘空间而希望删除不必要的文件,请不要删除
.git目录。相反,你可以考虑删除(清理)git log,删除旧的 git objects。你可以运行以下命令:git reflog expire --all --expire=now git gc --prune=now --aggressive
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.