AirLLM 2.8T LLM inference with single 4GB GPU
Python chinese-llmchinese-nlpfinetunegenerative-aiinstruct-gptinstruction-setllamallmloraopen-modelsopen-sourceopen-source-modelsqlora
add safetensors model support, fix profiling, refactor code, fix typo
Yu Li2b5d50b9caa1
diff --git a/air_llm/README.md b/air_llm/README.mdindex 9380111..4781be1 100644--- a/air_llm/README.md+++ b/air_llm/README.md@@ -7,6 +7,8 @@ AirLLM优化inference内存,4GB单卡GPU可以运行70B大语言模型推理## Updates+[2023/12/02] added support for safetensors. Now support all top 10 models in open llm leaderboard.+[2023/12/01] airllm 2.0. Support compressions: **3x run time speed up!**[2023/11/20] airllm Initial verion!@@ -107,6 +109,42 @@ When initialize the model, we support the following configurations:* **profiling_mode**: supported options: True to output time consumptions or by default False* **layer_shards_saving_path**: optionally another path to save the splitted model+### 5. Supported Models++#### [HF open llm leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard) top models++@12/01/23++| Rank | Model | Supported |+| ------------- | ------------- | ------------- |+| 1 | TigerResearch/tigerbot-70b-chat-v2 | ✅ |+| 2 | upstage/SOLAR-0-70b-16bit | ✅ |+| 3 | ICBU-NPU/FashionGPT-70B-V1.1 | ✅ |+| 4 | sequelbox/StellarBright | ✅ |+| 5 | bhenrym14/platypus-yi-34b | ✅ |+| 6 | MayaPH/GodziLLa2-70B | ✅ |+| 7 | 01-ai/Yi-34B | ✅ |+| 8 | garage-bAInd/Platypus2-70B-instruct | ✅ |+| 9 | jondurbin/airoboros-l2-70b-2.2.1 | ✅ |+| 10 | chargoddard/Yi-34B-Llama | ✅ |+++#### [opencompass leaderboard](https://opencompass.org.cn/leaderboard-llm) top models++@12/01/23++| Rank | Model | Supported |+| ------------- | ------------- | ------------- |+| 1 | GPT-4 | closed.ai😓 |+| 2 | TigerResearch/tigerbot-70b-chat-v2 | ✅ |+| 3 | THUDM/chatglm3-6b-base | ⏰(adding, [to accelerate😀](https://bmc.link/lyogavinQ)) |+| 4 | Qwen/Qwen-14B | ⏰(adding, [to accelerate😀](https://bmc.link/lyogavinQ)) |+| 5 | 01-ai/Yi-34B | ✅ |+| 6 | ChatGPT | closed.ai😓 |+| 7 | OrionStarAI/OrionStar-Yi-34B-Chat | ✅ |+| 8 | Qwen/Qwen-14B-Chat | ⏰(adding, [to accelerate😀](https://bmc.link/lyogavinQ)) |+| 9 | Duxiaoman-DI/XuanYuan-70B | ✅ |+| 10 | internlm/internlm-20b | ⏰(adding, [to accelerate😀](https://bmc.link/lyogavinQ)) |## Acknowledgement@@ -126,3 +164,11 @@ safetensors_rust.SafetensorError: Error while deserializing header: MetadataIncoIf you run into this error, most possible cause is you run out of disk space. The process of splitting model is very disk-consuming. See [this](https://huggingface.co/TheBloke/guanaco-65B-GPTQ/discussions/12). You may need to extend your disk space, clear huggingface [.cache](https://huggingface.co/docs/datasets/cache) and rerun.如果你碰到这个error,很有可能是空间不足。可以参考一下[这个](https://huggingface.co/TheBloke/guanaco-65B-GPTQ/discussions/12) 可能需要扩大硬盘空间,删除huggingface的[.cache](https://huggingface.co/docs/datasets/cache),然后重新run。++## Contribution++Welcome contribution, ideas and discussions!++If you find it useful, please ⭐ or buy me a coffee! 🙏++[](https://bmc.link/lyogavinQ)diff --git a/air_llm/airllm/__init__.py b/air_llm/airllm/__init__.pyindex 292fa0f..e92a4b6 100644--- a/air_llm/airllm/__init__.py+++ b/air_llm/airllm/__init__.py@@ -1,3 +1,3 @@from .airllm import AirLLMLlama2-from .airllm import split_and_save_layers-from .airllm import NotEnoughSpaceException\ No newline at end of file+from .utils import split_and_save_layers+from .utils import NotEnoughSpaceException\ No newline at end of filediff --git a/air_llm/airllm/airllm.py b/air_llm/airllm/airllm.pyindex 72fcbca..953f1be 100644--- a/air_llm/airllm/airllm.py+++ b/air_llm/airllm/airllm.py@@ -18,6 +18,8 @@ from safetensors.torch import load_file, save_filefrom optimum.bettertransformer import BetterTransformerimport huggingface_hub+from .utils import save_quant_state_to_dict, NotEnoughSpaceException, clean_memory, uncompress_layer_state_dict, load_layer, \+ check_space, compress_layer_state_dict, split_and_save_layers, find_or_create_local_splitted_pathtry:import bitsandbytes as bnb@@ -32,257 +34,6 @@ total_gpu_loading_time = Nonetotal_compression_overhead_time = None-# replacement for bnb quantstat.as_dict(True), until the bug is fixed....-def save_quant_state_to_dict(self, packed=True):- """- returns dict of tensors and strings to use in serialization via _save_to_state_dict()- param: packed -- returns dict[str, torch.Tensor] for state_dict- """- qs_dict = {- 'quant_type': self.quant_type,- 'absmax': self.absmax,- 'blocksize': self.blocksize,- 'quant_map': self.code,- 'dtype': str(self.dtype).strip('torch.'),- 'shape': tuple(self.shape),- }- if self.nested:- qs_dict.update({- 'nested_absmax': self.state2.absmax,- 'nested_blocksize': self.state2.blocksize,- 'nested_quant_map': self.state2.code,- 'nested_dtype': str(self.state2.dtype).strip('torch.'),- 'nested_offset': self.offset.item(),- })- if not packed:- return qs_dict-- qs_packed_dict = {k: v for k, v in qs_dict.items() if isinstance(v, torch.Tensor)}- non_tensor_dict = {k: v for k, v in qs_dict.items() if not isinstance(v, torch.Tensor)}- qs_packed_dict["quant_state." + "bitsandbytes__" + self.quant_type] = bnb.utils.pack_dict_to_tensor(non_tensor_dict)- return qs_packed_dict----class NotEnoughSpaceException(Exception):- pass--# Function to clean RAM & vRAM-def clean_memory():- gc.collect()- try:- ctypes.CDLL("libc.so.6").malloc_trim(0)- except Exception as ex:- # maybe platform- pass- torch.cuda.empty_cache()---def uncompress_layer_state_dict(layer_state_dict):- uncompressed_layer_state_dict = None- if any(['4bit' in k for k in layer_state_dict.keys()]):- uncompressed_layer_state_dict = {}- for k, v in layer_state_dict.items():- if '4bit' not in k:- quant_state_dict = {kk[len(k):]: kv for kk, kv in layer_state_dict.items() if kk.startswith(k) and k != kk}- quant_state = bnb.functional.QuantState.from_dict(qs_dict=quant_state_dict, device="cuda")-- dqv = bnb.functional.dequantize_nf4(v.cuda(), quant_state)- uncompressed_layer_state_dict[k] = dqv- del layer_state_dict- elif any(['8bit' in k for k in layer_state_dict.keys()]):- uncompressed_layer_state_dict = {}- for k, v in layer_state_dict.items():- if '8bit' not in k:-- absmax = layer_state_dict[k + ".8bit.absmax"]- code = layer_state_dict[k + ".8bit.code"]-- dqv = bnb.functional.dequantize_blockwise(v.cuda(),- bnb.functional.QuantState(absmax=absmax.cuda(),- code=code.cuda(),- blocksize=2048,- dtype=torch.float16))- uncompressed_layer_state_dict[k] = dqv- del layer_state_dict-- return layer_state_dict if uncompressed_layer_state_dict is None else uncompressed_layer_state_dict--def load_layer(local_path, layer_name):- layer_state_dict = load_file(Path(local_path) / (layer_name + ".safetensors"), device="cpu")-- if total_compression_overhead_time is not None:- t = time.process_time()-- to_return = uncompress_layer_state_dict(layer_state_dict)-- clean_memory()-- if total_compression_overhead_time is not None:- elapsed_time = time.process_time() - t- total_compression_overhead_time.append(elapsed_time)- return to_return----def check_space(checkpoint_path, layer_shards_saving_path=None, compression=None):- total_shard_files_size_bytes = 0- for model_shard_file in glob(str(checkpoint_path / '*')):- total_shard_files_size_bytes += os.path.getsize(model_shard_file)-- if compression == '4bit':- total_shard_files_size_bytes = int(total_shard_files_size_bytes / 0.2813)- elif compression == '8bit':- total_shard_files_size_bytes = total_shard_files_size_bytes // 2-- total, used, free = shutil.disk_usage(checkpoint_path if layer_shards_saving_path is None else layer_shards_saving_path)-- if free < total_shard_files_size_bytes:- raise NotEnoughSpaceException(f"Not enough space. Free space under {checkpoint_path if layer_shards_saving_path is None else layer_shards_saving_path}:" \- f" {free / 1024 / 1024 / 1024:.02f}GB. Model total size: {total_shard_files_size_bytes / 1024 / 1024 / 1024:.02f}GB.")--def compress_layer_state_dict(layer_state_dict, compression=None):- compressed_layer_state_dict = None- if compression == '4bit':- compressed_layer_state_dict = {}- for k, v in layer_state_dict.items():- v_quant, quant_state = bnb.functional.quantize_nf4(v.cuda(), blocksize=64)- compressed_layer_state_dict[k] = v_quant- for quant_state_k, quant_state_v in save_quant_state_to_dict(quant_state).items():- compressed_layer_state_dict[k + ".4bit." + quant_state_k] = quant_state_v- elif compression == '8bit':- compressed_layer_state_dict = {}- for k, v in layer_state_dict.items():- v_quant, quant_state = bnb.functional.quantize_blockwise(v.cuda(), blocksize=2048)- absmax = quant_state.absmax.clone().contiguous()- code = quant_state.code.clone().contiguous()- compressed_layer_state_dict[k] = v_quant- compressed_layer_state_dict[k + ".8bit.absmax"] = absmax- compressed_layer_state_dict[k + ".8bit.code"] = code-- return compressed_layer_state_dict if compressed_layer_state_dict is not None else layer_state_dict---def split_and_save_layers(checkpoint_path, layer_shards_saving_path=None, splitted_model_dir_name='splitted_model', compression=None):- """- Save the all layers of a model sharded checkpoint using safetensors.- """-- if compression is not None:- assert bitsandbytes_installed, f"when using compression bitsandbytes has to be installed."- splitted_model_dir_name = splitted_model_dir_name + "." + compression-- checkpoint_path = Path(checkpoint_path)--- saving_path = checkpoint_path / splitted_model_dir_name-- if layer_shards_saving_path is not None:- saving_path = Path(layer_shards_saving_path) / splitted_model_dir_name-- if os.path.exists(saving_path):- # already exists, assuming it's saved already, directly return- return str(saving_path)---- check_space(checkpoint_path, layer_shards_saving_path, compression)-- safetensors_format = False- if os.path.exists(checkpoint_path / 'pytorch_model.bin.index.json'):- with open(checkpoint_path / 'pytorch_model.bin.index.json', 'rb') as f:- index = json.load(f)['weight_map']- else:- safetensors_format = True- assert os.path.exists(checkpoint_path / 'model.safetensors.index.json'), f'model.safetensors.index.json should exist.'- with open(checkpoint_path / 'model.safetensors.index.json', 'rb') as f:- index = json.load(f)['weight_map']-- n_layers = len(set([int(k.split('.')[2]) for k in index.keys() if 'model.layers' in k]))- layers = ['model.embed_tokens.'] + [f'model.layers.{i}.' for i in range(n_layers)] + ['model.norm.', 'lm_head.']- shard = 0- n_shards = len(set(index.values()))- state_dict = {}---- if not os.path.exists(saving_path):- os.makedirs(saving_path)-- for layer in tqdm(layers):-- # Optionnally load next shard- shards = [int(v.split('-')[1]) for k, v in index.items() if k.startswith(layer)]- if max(shards) > shard:- shard += 1- print(f'Loading shard {shard}/{n_shards}')- if not safetensors_format:- state_dict.update(torch.load(checkpoint_path / f'pytorch_model-000{shard:02d}-of-000{n_shards:02d}.bin',- map_location='cpu'))- else:- state_dict.update(load_file(checkpoint_path / f'model-000{shard:02d}-of-000{n_shards:02d}.safetensors',- map_location='cpu'))-- # Get layer state dict- layer_state_dict = dict([(k, v) for k, v in state_dict.items() if k.startswith(layer)])-- layer_state_dict = compress_layer_state_dict(layer_state_dict, compression)--- # Save layer state dict as using safetensors- save_file(layer_state_dict, saving_path / (layer + 'safetensors'))-- print(f"saved as: {saving_path / (layer + 'safetensors')}")-- # Free memory- for k in layer_state_dict.keys():- if k in state_dict:- del state_dict[k]- del layer_state_dict- clean_memory()-- return str(saving_path)--def find_or_create_local_splitted_path(model_local_path_or_repo_id, layer_shards_saving_path=None, compression=None):- """- find the model's local cache path, download the cache if not exists, then split and save the model.-- Parameters- ----------- model_local_path_or_repo_id : str- model local path or hf repo id- layer_shards_saving_path : str, optional- optional path to save the splitted model, by default directly under the model local path-- Returns- -------- model_local_path : str- local model path- saved_layer_shards_path : str- the path saved layer shards- compression: str, optinal- setting to '4bit' or '8bit' to enable compression from 16 bits to 4 bits/8 bits which speeed up 4x or 2x inference time with a tiny accuracy loss.- """-- # try local model path, if the model exist split and save there- if os.path.exists(model_local_path_or_repo_id):- if os.path.exists(Path(model_local_path_or_repo_id) / 'pytorch_model.bin.index.json') or \- os.path.exists(Path(model_local_path_or_repo_id) / 'model.safetensors.index.json'):- return Path(model_local_path_or_repo_id), split_and_save_layers(model_local_path_or_repo_id, layer_shards_saving_path, compression=compression)- else:- print(- f"Found local directory in {model_local_path_or_repo_id}, but didn't find downloaded model. Try using {model_local_path_or_repo_id} as a HF repo...")-- # it should be a repo id at this point...- hf_cache_path = huggingface_hub.snapshot_download(model_local_path_or_repo_id)- assert os.path.exists(Path(hf_cache_path) / 'pytorch_model.bin.index.json') or \- os.path.exists(Path(hf_cache_path) / 'model.safetensors.index.json'), \- f"{hf_cache_path}/pytorch_model.bin.index.json or {hf_cache_path}/model.safetensors.index.json should exists."-- # if splitted_model subdir exists under cache use it, otherwise split and save- return Path(hf_cache_path), split_and_save_layers(hf_cache_path, layer_shards_saving_path, compression=compression)--class AirLLMLlama2(GenerationMixin):def __init__(self, model_local_path_or_repo_id, device="cuda:0", dtype=torch.float16, max_seq_len=512,@@ -311,8 +62,7 @@ class AirLLMLlama2(GenerationMixin):"""- if profiling_mode:- self.profiling_mode = profiling_mode+ self.profiling_mode = profiling_modeif compression is not None:if not bitsandbytes_installed:@@ -361,11 +111,20 @@ class AirLLMLlama2(GenerationMixin):set_module_tensor_to_device(self.model, buffer_name, self.running_device, value=buffer,dtype=self.running_dtype)- def load_layer_to_cpu(self, layer_name):+ def load_layer_to_cpu(self, layer_name, profiling=False):- state_dict = load_layer(self.checkpoint_path, layer_name)+ t = time.process_time()+ load_layer_output = load_layer(self.checkpoint_path, layer_name, profiling)+ elapsed_time = time.process_time() - t- return state_dict+ if profiling:+ state_dict, compression_time = load_layer_output+ disk_loading_time = elapsed_time - compression_time+ return state_dict, disk_loading_time, compression_time+ else:+ state_dict = load_layer_output++ return state_dictdef move_layer_to_device(self, state_dict):for param_name, param in state_dict.items():@@ -439,6 +198,7 @@ class AirLLMLlama2(GenerationMixin):total_disk_loading_time = []total_gpu_loading_time = []total_compression_overhead_time = []+ forward_start = time.process_time()# Reboot the model to make sure buffers are loaded and memory is cleandel self.model@@ -467,12 +227,14 @@ class AirLLMLlama2(GenerationMixin):for i, (layer_name, layer) in tqdm(enumerate(zip(self.layer_names, self.layers)), desc=self.running_device,total=len(self.layers)):- t = time.process_time()- state_dict = self.load_layer_to_cpu(layer_name)- elapsed_time = time.process_time() - t+ load_layer_to_cpu_output = self.load_layer_to_cpu(layer_name, self.profiling_mode)# profileif self.profiling_mode:- total_disk_loading_time.append(elapsed_time)+ state_dict, disk_loading_time, compression_time = load_layer_to_cpu_output+ total_disk_loading_time.append(disk_loading_time)+ total_compression_overhead_time.append(compression_time)+ else:+ state_dict = load_layer_to_cpu_outputt = time.process_time()self.move_layer_to_device(state_dict)@@ -578,12 +340,20 @@ class AirLLMLlama2(GenerationMixin):tuple(all_hidden_states) if all_hidden_states is not None else None,tuple(all_self_attns) if all_self_attns is not None else None] if v is not None)if self.profiling_mode:- print(f"total disk loading time: {sum(total_disk_loading_time):.04f}")- print(f"total gpu loading time: {sum(total_gpu_loading_time):.04f}")- print(f"total compression overhead time: {sum(total_compression_overhead_time):.04f}")+ forward_elapsed_time = time.process_time() - forward_start+ if self.compression:+ print(f"total disk loading time: {sum(total_disk_loading_time):.04f}")+ print(f"total gpu loading time: {sum(total_gpu_loading_time):.04f}")+ print(f"total compression overhead time: {sum(total_compression_overhead_time):.04f}")+ else:+ # loading is async/lazy, so can't really distinguish them...+ print(f"total disk+gpu loading time: {sum(total_disk_loading_time) + sum(total_gpu_loading_time):.04f}")++ print(f"total infer time(including all above plus gpu compute): {forward_elapsed_time:.04f}")total_disk_loading_time = []total_gpu_loading_time = []+ total_compression_overhead_time = []return CausalLMOutputWithPast(diff --git a/air_llm/airllm/utils.py b/air_llm/airllm/utils.pynew file mode 100644index 0000000..705b7e6--- /dev/null+++ b/air_llm/airllm/utils.py@@ -0,0 +1,276 @@+import gc+import json+import os+import ctypes+import shutil+from tqdm import tqdm+from pathlib import Path+from glob import glob+import time++import torch+from safetensors.torch import load_file, save_file++try:+ import bitsandbytes as bnb++ bitsandbytes_installed = True+except ImportError:+ bitsandbytes_installed = False+++import huggingface_hub++++# replacement for bnb quantstat.as_dict(True), until the bug is fixed....+def save_quant_state_to_dict(self, packed=True):+ """+ returns dict of tensors and strings to use in serialization via _save_to_state_dict()+ param: packed -- returns dict[str, torch.Tensor] for state_dict+ """+ qs_dict = {+ 'quant_type': self.quant_type,+ 'absmax': self.absmax,+ 'blocksize': self.blocksize,+ 'quant_map': self.code,+ 'dtype': str(self.dtype).strip('torch.'),+ 'shape': tuple(self.shape),+ }+ if self.nested:+ qs_dict.update({+ 'nested_absmax': self.state2.absmax,+ 'nested_blocksize': self.state2.blocksize,+ 'nested_quant_map': self.state2.code,+ 'nested_dtype': str(self.state2.dtype).strip('torch.'),+ 'nested_offset': self.offset.item(),+ })+ if not packed:+ return qs_dict++ qs_packed_dict = {k: v for k, v in qs_dict.items() if isinstance(v, torch.Tensor)}+ non_tensor_dict = {k: v for k, v in qs_dict.items() if not isinstance(v, torch.Tensor)}+ qs_packed_dict["quant_state." + "bitsandbytes__" + self.quant_type] = bnb.utils.pack_dict_to_tensor(non_tensor_dict)+ return qs_packed_dict++++class NotEnoughSpaceException(Exception):+ pass++# Function to clean RAM & vRAM+def clean_memory():+ gc.collect()+ try:+ ctypes.CDLL("libc.so.6").malloc_trim(0)+ except Exception as ex:+ # maybe platform+ pass+ torch.cuda.empty_cache()+++def uncompress_layer_state_dict(layer_state_dict):+ uncompressed_layer_state_dict = None+ if any(['4bit' in k for k in layer_state_dict.keys()]):+ uncompressed_layer_state_dict = {}+ for k, v in layer_state_dict.items():+ if '4bit' not in k:+ quant_state_dict = {kk[len(k):]: kv for kk, kv in layer_state_dict.items() if kk.startswith(k) and k != kk}+ quant_state = bnb.functional.QuantState.from_dict(qs_dict=quant_state_dict, device="cuda")++ dqv = bnb.functional.dequantize_nf4(v.cuda(), quant_state)+ uncompressed_layer_state_dict[k] = dqv+ del layer_state_dict+ elif any(['8bit' in k for k in layer_state_dict.keys()]):+ uncompressed_layer_state_dict = {}+ for k, v in layer_state_dict.items():+ if '8bit' not in k:++ absmax = layer_state_dict[k + ".8bit.absmax"]+ code = layer_state_dict[k + ".8bit.code"]++ dqv = bnb.functional.dequantize_blockwise(v.cuda(),+ bnb.functional.QuantState(absmax=absmax.cuda(),+ code=code.cuda(),+ blocksize=2048,+ dtype=torch.float16))+ uncompressed_layer_state_dict[k] = dqv+ del layer_state_dict++ return layer_state_dict if uncompressed_layer_state_dict is None else uncompressed_layer_state_dict++def load_layer(local_path, layer_name, profiling=False):+ layer_state_dict = load_file(Path(local_path) / (layer_name + ".safetensors"), device="cpu")++ if profiling:+ t = time.process_time()++ to_return = uncompress_layer_state_dict(layer_state_dict)++ clean_memory()++ if profiling:+ elapsed_time = time.process_time() - t+ return to_return, elapsed_time+ else:+ return to_return++++def check_space(checkpoint_path, layer_shards_saving_path=None, compression=None):+ total_shard_files_size_bytes = 0+ for model_shard_file in glob(str(checkpoint_path / '*')):+ total_shard_files_size_bytes += os.path.getsize(model_shard_file)++ if compression == '4bit':+ total_shard_files_size_bytes = int(total_shard_files_size_bytes / 0.2813)+ elif compression == '8bit':+ total_shard_files_size_bytes = total_shard_files_size_bytes // 2++ total, used, free = shutil.disk_usage(checkpoint_path if layer_shards_saving_path is None else layer_shards_saving_path)++ if free < total_shard_files_size_bytes:+ raise NotEnoughSpaceException(f"Not enough space. Free space under {checkpoint_path if layer_shards_saving_path is None else layer_shards_saving_path}:" \+ f" {free / 1024 / 1024 / 1024:.02f}GB. Model total size: {total_shard_files_size_bytes / 1024 / 1024 / 1024:.02f}GB.")++def compress_layer_state_dict(layer_state_dict, compression=None):+ compressed_layer_state_dict = None+ if compression == '4bit':+ compressed_layer_state_dict = {}+ for k, v in layer_state_dict.items():+ v_quant, quant_state = bnb.functional.quantize_nf4(v.cuda(), blocksize=64)+ compressed_layer_state_dict[k] = v_quant+ for quant_state_k, quant_state_v in save_quant_state_to_dict(quant_state).items():+ compressed_layer_state_dict[k + ".4bit." + quant_state_k] = quant_state_v+ elif compression == '8bit':+ compressed_layer_state_dict = {}+ for k, v in layer_state_dict.items():+ v_quant, quant_state = bnb.functional.quantize_blockwise(v.cuda(), blocksize=2048)+ absmax = quant_state.absmax.clone().contiguous()+ code = quant_state.code.clone().contiguous()+ compressed_layer_state_dict[k] = v_quant+ compressed_layer_state_dict[k + ".8bit.absmax"] = absmax+ compressed_layer_state_dict[k + ".8bit.code"] = code++ return compressed_layer_state_dict if compressed_layer_state_dict is not None else layer_state_dict+++def split_and_save_layers(checkpoint_path, layer_shards_saving_path=None, splitted_model_dir_name='splitted_model', compression=None):+ """+ Save the all layers of a model sharded checkpoint using safetensors.+ """++ if compression is not None:+ assert bitsandbytes_installed, f"when using compression bitsandbytes has to be installed."+ splitted_model_dir_name = splitted_model_dir_name + "." + compression++ checkpoint_path = Path(checkpoint_path)+++ saving_path = checkpoint_path / splitted_model_dir_name++ if layer_shards_saving_path is not None:+ saving_path = Path(layer_shards_saving_path) / splitted_model_dir_name++ if os.path.exists(saving_path):+ # already exists, assuming it's saved already, directly return+ return str(saving_path)++++ check_space(checkpoint_path, layer_shards_saving_path, compression)++ safetensors_format = False+ if os.path.exists(checkpoint_path / 'pytorch_model.bin.index.json'):+ with open(checkpoint_path / 'pytorch_model.bin.index.json', 'rb') as f:+ index = json.load(f)['weight_map']+ else:+ safetensors_format = True+ assert os.path.exists(checkpoint_path / 'model.safetensors.index.json'), f'model.safetensors.index.json should exist.'+ with open(checkpoint_path / 'model.safetensors.index.json', 'rb') as f:+ index = json.load(f)['weight_map']++ n_layers = len(set([int(k.split('.')[2]) for k in index.keys() if 'model.layers' in k]))+ layers = ['model.embed_tokens.'] + [f'model.layers.{i}.' for i in range(n_layers)] + ['model.norm.', 'lm_head.']+ shard = 0+ n_shards = len(set(index.values()))+ state_dict = {}++++ if not os.path.exists(saving_path):+ os.makedirs(saving_path)++ for layer in tqdm(layers):++ # Optionnally load next shard+ shards = [int(v.split('-')[1]) for k, v in index.items() if k.startswith(layer)]+ if max(shards) > shard:+ shard += 1+ print(f'Loading shard {shard}/{n_shards}')+ if not safetensors_format:+ state_dict.update(torch.load(checkpoint_path / f'pytorch_model-000{shard:02d}-of-000{n_shards:02d}.bin',+ map_location='cpu'))+ else:+ state_dict.update(load_file(checkpoint_path / f'model-000{shard:02d}-of-000{n_shards:02d}.safetensors',+ device='cpu'))++ # Get layer state dict+ layer_state_dict = dict([(k, v) for k, v in state_dict.items() if k.startswith(layer)])++ layer_state_dict = compress_layer_state_dict(layer_state_dict, compression)+++ # Save layer state dict as using safetensors+ save_file(layer_state_dict, saving_path / (layer + 'safetensors'))++ print(f"saved as: {saving_path / (layer + 'safetensors')}")++ # Free memory+ for k in layer_state_dict.keys():+ if k in state_dict:+ del state_dict[k]+ del layer_state_dict+ clean_memory()++ return str(saving_path)++def find_or_create_local_splitted_path(model_local_path_or_repo_id, layer_shards_saving_path=None, compression=None):+ """+ find the model's local cache path, download the cache if not exists, then split and save the model.++ Parameters+ ----------+ model_local_path_or_repo_id : str+ model local path or hf repo id+ layer_shards_saving_path : str, optional+ optional path to save the splitted model, by default directly under the model local path++ Returns+ -------+ model_local_path : str+ local model path+ saved_layer_shards_path : str+ the path saved layer shards+ compression: str, optinal+ setting to '4bit' or '8bit' to enable compression from 16 bits to 4 bits/8 bits which speeed up 4x or 2x inference time with a tiny accuracy loss.+ """++ # try local model path, if the model exist split and save there+ if os.path.exists(model_local_path_or_repo_id):+ if os.path.exists(Path(model_local_path_or_repo_id) / 'pytorch_model.bin.index.json') or \+ os.path.exists(Path(model_local_path_or_repo_id) / 'model.safetensors.index.json'):+ return Path(model_local_path_or_repo_id), split_and_save_layers(model_local_path_or_repo_id, layer_shards_saving_path, compression=compression)+ else:+ print(+ f"Found local directory in {model_local_path_or_repo_id}, but didn't find downloaded model. Try using {model_local_path_or_repo_id} as a HF repo...")++ # it should be a repo id at this point...+ hf_cache_path = huggingface_hub.snapshot_download(model_local_path_or_repo_id)+ assert os.path.exists(Path(hf_cache_path) / 'pytorch_model.bin.index.json') or \+ os.path.exists(Path(hf_cache_path) / 'model.safetensors.index.json'), \+ f"{hf_cache_path}/pytorch_model.bin.index.json or {hf_cache_path}/model.safetensors.index.json should exists."++ # if splitted_model subdir exists under cache use it, otherwise split and save+ return Path(hf_cache_path), split_and_save_layers(hf_cache_path, layer_shards_saving_path, compression=compression)+diff --git a/air_llm/setup.py b/air_llm/setup.pyindex 6297fad..b1d0912 100644--- a/air_llm/setup.py+++ b/air_llm/setup.py@@ -5,7 +5,7 @@ with open("README.md", "r") as fh:setuptools.setup(name="airllm",- version="2.0.0",+ version="2.1.0",author="Gavin Li",author_email="[email protected]",description="AirLLM allows single 4GB GPU card to run 70B large language models without quantization, distillation or pruning.",@@ -13,14 +13,14 @@ setuptools.setup(long_description_content_type="text/markdown",url="https://github.com/lyogavin/Anima/tree/main/air_llm",packages=setuptools.find_packages(),- install_requires=[ # I get to this in a second+ install_requires=['tqdm','torch','transformers','accelerate','safetensors','optimum',- 'huggingface_hub'+ 'huggingface-hub''scipy',#'bitsandbytes' set it to optional to support fallback when not installable],