2023-04-06 17:16:48 +02:00
|
|
|
import inspect
|
2023-03-20 19:11:56 +01:00
|
|
|
import re
|
2023-03-12 15:12:34 +01:00
|
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
import accelerate
|
|
|
|
import torch
|
2023-03-28 19:38:55 +02:00
|
|
|
import transformers
|
2023-10-27 05:26:25 +02:00
|
|
|
from accelerate.utils import is_xpu_available
|
2023-10-27 04:39:51 +02:00
|
|
|
from gptq_for_llama import llama_inference_offload
|
|
|
|
from gptq_for_llama.modelutils import find_layers
|
|
|
|
from gptq_for_llama.quant import make_quant
|
2023-03-28 22:34:15 +02:00
|
|
|
from transformers import AutoConfig, AutoModelForCausalLM
|
2023-03-12 15:12:34 +01:00
|
|
|
|
|
|
|
import modules.shared as shared
|
2023-05-22 03:42:34 +02:00
|
|
|
from modules.logging_colors import logger
|
2023-03-12 15:12:34 +01:00
|
|
|
|
2023-03-28 19:38:55 +02:00
|
|
|
|
2023-04-17 04:26:52 +02:00
|
|
|
# This function is a replacement for the load_quant function in the
|
|
|
|
# GPTQ-for_LLaMa repository. It supports more models and branches.
|
2023-05-09 03:55:41 +02:00
|
|
|
def _load_quant(model, checkpoint, wbits, groupsize=-1, faster_kernel=False, exclude_layers=None, kernel_switch_threshold=128, eval=True):
|
|
|
|
exclude_layers = exclude_layers or ['lm_head']
|
2023-04-07 05:15:45 +02:00
|
|
|
|
2023-03-28 19:38:55 +02:00
|
|
|
def noop(*args, **kwargs):
|
|
|
|
pass
|
2023-04-07 05:15:45 +02:00
|
|
|
|
2023-05-07 22:42:44 +02:00
|
|
|
config = AutoConfig.from_pretrained(model, trust_remote_code=shared.args.trust_remote_code)
|
2023-04-06 17:16:48 +02:00
|
|
|
torch.nn.init.kaiming_uniform_ = noop
|
|
|
|
torch.nn.init.uniform_ = noop
|
|
|
|
torch.nn.init.normal_ = noop
|
2023-03-28 19:38:55 +02:00
|
|
|
|
|
|
|
torch.set_default_dtype(torch.half)
|
|
|
|
transformers.modeling_utils._init_weights = False
|
|
|
|
torch.set_default_dtype(torch.half)
|
2023-05-07 22:42:44 +02:00
|
|
|
model = AutoModelForCausalLM.from_config(config, trust_remote_code=shared.args.trust_remote_code)
|
2023-03-28 19:38:55 +02:00
|
|
|
torch.set_default_dtype(torch.float)
|
2023-04-17 06:11:18 +02:00
|
|
|
if eval:
|
|
|
|
model = model.eval()
|
2023-05-10 07:07:22 +02:00
|
|
|
|
2023-03-28 19:38:55 +02:00
|
|
|
layers = find_layers(model)
|
|
|
|
for name in exclude_layers:
|
|
|
|
if name in layers:
|
|
|
|
del layers[name]
|
2023-04-07 05:15:45 +02:00
|
|
|
|
2023-08-10 06:42:34 +02:00
|
|
|
gptq_args = inspect.getfullargspec(make_quant).args
|
|
|
|
|
|
|
|
make_quant_kwargs = {
|
|
|
|
'module': model,
|
|
|
|
'names': layers,
|
|
|
|
'bits': wbits,
|
|
|
|
}
|
|
|
|
if 'groupsize' in gptq_args:
|
|
|
|
make_quant_kwargs['groupsize'] = groupsize
|
|
|
|
if 'faster' in gptq_args:
|
|
|
|
make_quant_kwargs['faster'] = faster_kernel
|
|
|
|
if 'kernel_switch_threshold' in gptq_args:
|
|
|
|
make_quant_kwargs['kernel_switch_threshold'] = kernel_switch_threshold
|
|
|
|
|
|
|
|
make_quant(**make_quant_kwargs)
|
2023-04-06 17:16:48 +02:00
|
|
|
|
|
|
|
del layers
|
2023-03-28 19:38:55 +02:00
|
|
|
if checkpoint.endswith('.safetensors'):
|
|
|
|
from safetensors.torch import load_file as safe_load
|
2023-04-07 05:15:45 +02:00
|
|
|
model.load_state_dict(safe_load(checkpoint), strict=False)
|
2023-03-28 19:38:55 +02:00
|
|
|
else:
|
2023-04-07 05:15:45 +02:00
|
|
|
model.load_state_dict(torch.load(checkpoint), strict=False)
|
2023-04-12 17:26:06 +02:00
|
|
|
|
2023-03-28 19:38:55 +02:00
|
|
|
model.seqlen = 2048
|
|
|
|
return model
|
2023-03-12 15:12:34 +01:00
|
|
|
|
2023-04-07 05:15:45 +02:00
|
|
|
|
2023-04-17 04:26:52 +02:00
|
|
|
# Used to locate the .pt/.safetensors quantized file
|
|
|
|
def find_quantized_model_file(model_name):
|
2023-05-04 20:17:20 +02:00
|
|
|
if shared.args.checkpoint:
|
|
|
|
return Path(shared.args.checkpoint)
|
|
|
|
|
2023-04-17 04:26:52 +02:00
|
|
|
path_to_model = Path(f'{shared.args.model_dir}/{model_name}')
|
|
|
|
pt_path = None
|
|
|
|
priority_name_list = [
|
|
|
|
Path(f'{shared.args.model_dir}/{model_name}{hyphen}{shared.args.wbits}bit{group}{ext}')
|
|
|
|
for group in ([f'-{shared.args.groupsize}g', ''] if shared.args.groupsize > 0 else [''])
|
|
|
|
for ext in ['.safetensors', '.pt']
|
|
|
|
for hyphen in ['-', f'/{model_name}-', '/']
|
|
|
|
]
|
2023-05-10 16:59:59 +02:00
|
|
|
|
2023-04-17 04:26:52 +02:00
|
|
|
for path in priority_name_list:
|
|
|
|
if path.exists():
|
|
|
|
pt_path = path
|
|
|
|
break
|
|
|
|
|
|
|
|
# If the model hasn't been found with a well-behaved name, pick the last .pt
|
|
|
|
# or the last .safetensors found in its folder as a last resort
|
|
|
|
if not pt_path:
|
2023-05-17 21:22:56 +02:00
|
|
|
for ext in ['.pt', '.safetensors']:
|
|
|
|
found = list(path_to_model.glob(f"*{ext}"))
|
|
|
|
if len(found) > 0:
|
|
|
|
if len(found) > 1:
|
2023-05-22 03:42:34 +02:00
|
|
|
logger.warning(f'More than one {ext} model has been found. The last one will be selected. It could be wrong.')
|
2023-05-17 21:22:56 +02:00
|
|
|
|
|
|
|
pt_path = found[-1]
|
|
|
|
break
|
2023-04-17 04:26:52 +02:00
|
|
|
|
|
|
|
return pt_path
|
|
|
|
|
|
|
|
|
|
|
|
# The function that loads the model in modules/models.py
|
2023-03-13 20:11:32 +01:00
|
|
|
def load_quantized(model_name):
|
2023-05-10 16:59:59 +02:00
|
|
|
if shared.args.model_type is None:
|
2023-05-22 03:42:34 +02:00
|
|
|
logger.error("The model could not be loaded because its type could not be inferred from its name.")
|
|
|
|
logger.error("Please specify the type manually using the --model_type argument.")
|
2023-05-19 16:20:08 +02:00
|
|
|
return None
|
2023-03-13 20:11:32 +01:00
|
|
|
|
2023-04-13 16:17:32 +02:00
|
|
|
# Select the appropriate load_quant function
|
2023-05-10 16:59:59 +02:00
|
|
|
model_type = shared.args.model_type.lower()
|
2023-04-05 06:21:40 +02:00
|
|
|
if shared.args.pre_layer and model_type == 'llama':
|
|
|
|
load_quant = llama_inference_offload.load_quant
|
2023-03-28 19:38:55 +02:00
|
|
|
elif model_type in ('llama', 'opt', 'gptj'):
|
2023-04-05 06:21:40 +02:00
|
|
|
if shared.args.pre_layer:
|
2023-05-22 03:42:34 +02:00
|
|
|
logger.warning("Ignoring --pre_layer because it only works for llama model type.")
|
2023-05-04 02:43:17 +02:00
|
|
|
|
2023-03-28 19:38:55 +02:00
|
|
|
load_quant = _load_quant
|
2023-03-12 15:12:34 +01:00
|
|
|
else:
|
2023-05-22 03:42:34 +02:00
|
|
|
logger.error("Unknown pre-quantized model type specified. Only 'llama', 'opt' and 'gptj' are supported")
|
2023-03-13 17:59:57 +01:00
|
|
|
exit()
|
2023-03-12 15:12:34 +01:00
|
|
|
|
2023-04-17 04:26:52 +02:00
|
|
|
# Find the quantized model weights file (.pt/.safetensors)
|
2023-04-05 04:19:38 +02:00
|
|
|
path_to_model = Path(f'{shared.args.model_dir}/{model_name}')
|
2023-04-17 04:26:52 +02:00
|
|
|
pt_path = find_quantized_model_file(model_name)
|
2023-03-12 15:12:34 +01:00
|
|
|
if not pt_path:
|
2023-05-22 03:42:34 +02:00
|
|
|
logger.error("Could not find the quantized model in .pt or .safetensors format, exiting...")
|
2023-03-12 15:12:34 +01:00
|
|
|
exit()
|
2023-04-10 04:19:28 +02:00
|
|
|
else:
|
2023-05-22 03:42:34 +02:00
|
|
|
logger.info(f"Found the following quantized model: {pt_path}")
|
2023-03-12 15:12:34 +01:00
|
|
|
|
2023-03-20 20:40:08 +01:00
|
|
|
# qwopqwop200's offload
|
2023-04-05 06:19:26 +02:00
|
|
|
if model_type == 'llama' and shared.args.pre_layer:
|
2023-05-17 15:41:09 +02:00
|
|
|
if len(shared.args.pre_layer) == 1:
|
|
|
|
pre_layer = shared.args.pre_layer[0]
|
|
|
|
else:
|
|
|
|
pre_layer = shared.args.pre_layer
|
|
|
|
|
|
|
|
model = load_quant(str(path_to_model), str(pt_path), shared.args.wbits, shared.args.groupsize, pre_layer)
|
2023-03-20 20:30:56 +01:00
|
|
|
else:
|
2023-03-28 21:45:38 +02:00
|
|
|
threshold = False if model_type == 'gptj' else 128
|
|
|
|
model = load_quant(str(path_to_model), str(pt_path), shared.args.wbits, shared.args.groupsize, kernel_switch_threshold=threshold)
|
2023-03-12 15:12:34 +01:00
|
|
|
|
2023-03-20 20:40:08 +01:00
|
|
|
# accelerate offload (doesn't work properly)
|
2023-10-27 04:39:51 +02:00
|
|
|
if shared.args.gpu_memory or torch.cuda.device_count() > 1 or (is_xpu_available() and torch.xpu.device_count() > 1):
|
2023-04-12 19:48:17 +02:00
|
|
|
if shared.args.gpu_memory:
|
|
|
|
memory_map = list(map(lambda x: x.strip(), shared.args.gpu_memory))
|
|
|
|
max_cpu_memory = shared.args.cpu_memory.strip() if shared.args.cpu_memory is not None else '99GiB'
|
|
|
|
max_memory = {}
|
|
|
|
for i in range(len(memory_map)):
|
|
|
|
max_memory[i] = f'{memory_map[i]}GiB' if not re.match('.*ib$', memory_map[i].lower()) else memory_map[i]
|
2023-05-12 11:17:07 +02:00
|
|
|
|
|
|
|
max_memory['cpu'] = f'{max_cpu_memory}GiB' if not re.match('.*ib$', max_cpu_memory.lower()) else max_cpu_memory
|
2023-04-12 19:48:17 +02:00
|
|
|
else:
|
|
|
|
max_memory = accelerate.utils.get_balanced_memory(model)
|
2023-03-12 15:12:34 +01:00
|
|
|
|
2023-03-20 20:30:56 +01:00
|
|
|
device_map = accelerate.infer_auto_device_map(model, max_memory=max_memory, no_split_module_classes=["LlamaDecoderLayer"])
|
2023-05-22 03:42:34 +02:00
|
|
|
logger.info("Using the following device map for the quantized model:", device_map)
|
2023-03-20 20:30:56 +01:00
|
|
|
# https://huggingface.co/docs/accelerate/package_reference/big_modeling#accelerate.dispatch_model
|
|
|
|
model = accelerate.dispatch_model(model, device_map=device_map, offload_buffers=True)
|
2023-03-20 20:40:08 +01:00
|
|
|
|
|
|
|
# No offload
|
2023-03-20 20:30:56 +01:00
|
|
|
elif not shared.args.cpu:
|
2023-10-27 04:39:51 +02:00
|
|
|
if is_xpu_available():
|
|
|
|
model = model.to(torch.device("xpu:0"))
|
|
|
|
else:
|
|
|
|
model = model.to(torch.device('cuda:0'))
|
2023-03-12 15:12:34 +01:00
|
|
|
|
|
|
|
return model
|