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
|
|
|
import sys
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
import accelerate
|
|
|
|
import torch
|
2023-03-28 19:38:55 +02:00
|
|
|
import transformers
|
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-03-13 04:08:01 +01:00
|
|
|
sys.path.insert(0, str(Path("repositories/GPTQ-for-LLaMa")))
|
2023-03-20 20:30:56 +01:00
|
|
|
import llama_inference_offload
|
2023-03-28 19:38:55 +02:00
|
|
|
from modelutils import find_layers
|
2023-03-28 22:34:15 +02:00
|
|
|
from quant import make_quant
|
|
|
|
|
2023-03-28 19:38:55 +02:00
|
|
|
|
2023-03-28 21:45:38 +02:00
|
|
|
def _load_quant(model, checkpoint, wbits, groupsize=-1, faster_kernel=False, exclude_layers=['lm_head'], kernel_switch_threshold=128):
|
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
|
|
|
|
|
|
|
config = AutoConfig.from_pretrained(model)
|
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)
|
|
|
|
model = AutoModelForCausalLM.from_config(config)
|
|
|
|
torch.set_default_dtype(torch.float)
|
|
|
|
model = model.eval()
|
|
|
|
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-04-06 17:16:48 +02:00
|
|
|
gptq_args = inspect.getfullargspec(make_quant).args
|
2023-03-28 19:38:55 +02:00
|
|
|
|
2023-04-06 17:16:48 +02:00
|
|
|
make_quant_kwargs = {
|
2023-04-07 05:15:45 +02:00
|
|
|
'module': model,
|
2023-04-06 17:16:48 +02:00
|
|
|
'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
|
2023-04-07 05:15:45 +02:00
|
|
|
|
2023-04-06 17:16:48 +02:00
|
|
|
make_quant(**make_quant_kwargs)
|
|
|
|
|
|
|
|
del layers
|
|
|
|
|
2023-03-28 19:38:55 +02:00
|
|
|
print('Loading model ...')
|
|
|
|
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
|
|
|
|
|
|
|
try:
|
|
|
|
from quant import autotune_warmup, make_quant_attn
|
|
|
|
# triton branch
|
|
|
|
make_quant_attn(model)
|
2023-04-13 14:59:49 +02:00
|
|
|
if not shared.args.no_warmup_autotune:
|
2023-04-12 17:26:06 +02:00
|
|
|
autotune_warmup(model)
|
|
|
|
except ImportError: # not triton branch
|
|
|
|
pass
|
|
|
|
|
2023-03-28 19:38:55 +02:00
|
|
|
model.seqlen = 2048
|
|
|
|
print('Done.')
|
|
|
|
|
|
|
|
return model
|
2023-03-12 15:12:34 +01:00
|
|
|
|
2023-04-07 05:15:45 +02:00
|
|
|
|
2023-03-13 20:11:32 +01:00
|
|
|
def load_quantized(model_name):
|
2023-03-26 05:11:33 +02:00
|
|
|
if not shared.args.model_type:
|
2023-03-13 20:11:32 +01:00
|
|
|
# Try to determine model type from model name
|
2023-03-30 02:47:36 +02:00
|
|
|
name = model_name.lower()
|
2023-04-04 18:23:27 +02:00
|
|
|
if any((k in name for k in ['llama', 'alpaca', 'vicuna'])):
|
2023-03-26 05:11:33 +02:00
|
|
|
model_type = 'llama'
|
2023-03-30 02:47:36 +02:00
|
|
|
elif any((k in name for k in ['opt-', 'galactica'])):
|
2023-03-26 05:11:33 +02:00
|
|
|
model_type = 'opt'
|
2023-03-30 02:47:36 +02:00
|
|
|
elif any((k in name for k in ['gpt-j', 'pygmalion-6b'])):
|
2023-03-28 19:38:55 +02:00
|
|
|
model_type = 'gptj'
|
2023-03-26 05:11:33 +02:00
|
|
|
else:
|
|
|
|
print("Can't determine model type from model name. Please specify it manually using --model_type "
|
2023-03-13 20:11:32 +01:00
|
|
|
"argument")
|
|
|
|
exit()
|
|
|
|
else:
|
2023-03-26 05:11:33 +02:00
|
|
|
model_type = shared.args.model_type.lower()
|
2023-03-13 20:11:32 +01:00
|
|
|
|
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:
|
|
|
|
print("Warning: ignoring --pre_layer because it only works for llama model type.")
|
2023-03-28 19:38:55 +02:00
|
|
|
load_quant = _load_quant
|
2023-03-12 15:12:34 +01:00
|
|
|
else:
|
2023-03-28 19:38:55 +02:00
|
|
|
print("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-12 17:26:06 +02:00
|
|
|
# Now we are going to try to locate the quantized model file. I think it's cleaner and supports the new name containing groupsize
|
2023-04-05 04:19:38 +02:00
|
|
|
path_to_model = Path(f'{shared.args.model_dir}/{model_name}')
|
2023-03-26 05:11:33 +02:00
|
|
|
pt_path = None
|
2023-04-12 17:26:06 +02:00
|
|
|
priority_name_list = [
|
|
|
|
Path(f'{shared.args.model_dir}/{model_name}/{shared.args.wbits}bit-{shared.args.groupsize}g.safetensors'),
|
|
|
|
Path(f'{shared.args.model_dir}/{model_name}/{shared.args.wbits}bit-{shared.args.groupsize}g.pt'),
|
|
|
|
Path(f'{shared.args.model_dir}/{model_name}/{shared.args.wbits}bit.safetensors'),
|
|
|
|
Path(f'{shared.args.model_dir}/{model_name}/{shared.args.wbits}bit.pt'),
|
|
|
|
Path(f'{shared.args.model_dir}/{model_name}-{shared.args.wbits}bit-{shared.args.groupsize}g.safetensors'),
|
|
|
|
Path(f'{shared.args.model_dir}/{model_name}-{shared.args.wbits}bit-{shared.args.groupsize}g.pt'),
|
|
|
|
Path(f'{shared.args.model_dir}/{model_name}-{shared.args.wbits}bit.safetensors'),
|
|
|
|
Path(f'{shared.args.model_dir}/{model_name}-{shared.args.wbits}bit.pt'),
|
|
|
|
]
|
|
|
|
for path in priority_name_list:
|
|
|
|
if path.exists():
|
|
|
|
pt_path = path
|
|
|
|
break
|
|
|
|
|
|
|
|
# For compatibility, do we really need this?
|
|
|
|
if not pt_path:
|
|
|
|
path_to_model = Path(f'{shared.args.model_dir}/{model_name}')
|
|
|
|
found_pts = list(path_to_model.glob("*.pt"))
|
|
|
|
found_safetensors = list(path_to_model.glob("*.safetensors"))
|
|
|
|
pt_path = None
|
|
|
|
|
|
|
|
if len(found_pts) > 0:
|
|
|
|
pt_path = found_pts[-1]
|
|
|
|
elif len(found_safetensors) > 0:
|
|
|
|
pt_path = found_safetensors[-1]
|
2023-03-26 05:11:33 +02:00
|
|
|
else:
|
2023-04-12 17:26:06 +02:00
|
|
|
if path_to_model.name.lower().startswith('llama-7b'):
|
|
|
|
pt_model = f'llama-7b-{shared.args.wbits}bit'
|
|
|
|
elif path_to_model.name.lower().startswith('llama-13b'):
|
|
|
|
pt_model = f'llama-13b-{shared.args.wbits}bit'
|
|
|
|
elif path_to_model.name.lower().startswith('llama-30b'):
|
|
|
|
pt_model = f'llama-30b-{shared.args.wbits}bit'
|
|
|
|
elif path_to_model.name.lower().startswith('llama-65b'):
|
|
|
|
pt_model = f'llama-65b-{shared.args.wbits}bit'
|
|
|
|
else:
|
|
|
|
pt_model = f'{model_name}-{shared.args.wbits}bit'
|
|
|
|
|
|
|
|
# Try to find the .safetensors or .pt both in the model dir and in the subfolder
|
|
|
|
for path in [Path(p + ext) for ext in ['.safetensors', '.pt'] for p in [f"{shared.args.model_dir}/{pt_model}", f"{path_to_model}/{pt_model}"]]:
|
|
|
|
if path.exists():
|
|
|
|
pt_path = path
|
|
|
|
break
|
2023-03-12 15:12:34 +01:00
|
|
|
|
|
|
|
if not pt_path:
|
2023-03-26 05:11:33 +02:00
|
|
|
print("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:
|
|
|
|
print(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-03-26 05:11:33 +02:00
|
|
|
model = load_quant(str(path_to_model), str(pt_path), shared.args.wbits, shared.args.groupsize, shared.args.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-04-12 19:48:17 +02:00
|
|
|
if shared.args.gpu_memory or torch.cuda.device_count() > 1:
|
|
|
|
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]
|
|
|
|
max_memory['cpu'] = max_cpu_memory
|
|
|
|
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-04-12 19:48:17 +02:00
|
|
|
print("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:
|
|
|
|
model = model.to(torch.device('cuda:0'))
|
2023-03-12 15:12:34 +01:00
|
|
|
|
|
|
|
return model
|