text-generation-webui/modules/LoRA.py

193 lines
7.0 KiB
Python
Raw Normal View History

2023-03-16 20:35:53 -04:00
from pathlib import Path
2023-03-25 00:18:32 -04:00
import torch
2023-03-29 21:50:58 -04:00
from peft import PeftModel
2023-03-25 00:18:32 -04:00
2023-03-16 20:35:53 -04:00
import modules.shared as shared
from modules.logging_colors import logger
2023-06-05 22:29:29 -04:00
from modules.models import reload_model
2023-03-23 20:56:26 -04:00
def add_lora_to_model(lora_names):
2023-07-09 00:03:43 -04:00
if 'GPTQForCausalLM' in shared.model.__class__.__name__ or shared.args.loader == 'AutoGPTQ':
2023-06-19 11:31:24 -04:00
add_lora_autogptq(lora_names)
2023-07-09 00:03:43 -04:00
elif shared.model.__class__.__name__ in ['ExllamaModel', 'ExllamaHF'] or shared.args.loader == 'ExLlama':
2023-06-19 11:31:24 -04:00
add_lora_exllama(lora_names)
elif shared.model.__class__.__name__ in ['Exllamav2Model', 'Exllamav2HF'] or shared.args.loader == ['ExLlamav2', 'ExLlamav2_HF']:
add_lora_exllamav2(lora_names)
2023-06-19 11:31:24 -04:00
else:
add_lora_transformers(lora_names)
2023-03-16 20:35:53 -04:00
2023-06-05 22:29:29 -04:00
2023-08-10 12:54:28 -04:00
def get_lora_path(lora_name):
p = Path(lora_name)
if p.exists():
lora_name = p.parts[-1]
return Path(f"{shared.args.lora_dir}/{lora_name}")
2023-06-19 11:31:24 -04:00
def add_lora_exllama(lora_names):
2023-06-19 11:31:24 -04:00
try:
from exllama.lora import ExLlamaLora
2023-06-19 11:31:24 -04:00
except:
try:
from repositories.exllama.lora import ExLlamaLora
except:
logger.error("Could not find the file repositories/exllama/lora.py. Make sure that exllama is cloned inside repositories/ and is up to date.")
return
2023-06-19 11:31:24 -04:00
if len(lora_names) == 0:
2023-06-25 23:10:13 -04:00
if shared.model.__class__.__name__ == 'ExllamaModel':
shared.model.generator.lora = None
else:
shared.model.lora = None
2023-06-19 11:31:24 -04:00
shared.lora_names = []
return
else:
if len(lora_names) > 1:
logger.warning('ExLlama can only work with 1 LoRA at the moment. Only the first one in the list will be loaded.')
2023-08-10 12:54:28 -04:00
lora_path = get_lora_path(lora_names[0])
2023-06-19 11:31:24 -04:00
lora_config_path = lora_path / "adapter_config.json"
lora_adapter_path = lora_path / "adapter_model.bin"
logger.info("Applying the following LoRAs to {}: {}".format(shared.model_name, ', '.join([lora_names[0]])))
2023-06-25 23:10:13 -04:00
if shared.model.__class__.__name__ == 'ExllamaModel':
lora = ExLlamaLora(shared.model.model, str(lora_config_path), str(lora_adapter_path))
shared.model.generator.lora = lora
else:
lora = ExLlamaLora(shared.model.ex_model, str(lora_config_path), str(lora_adapter_path))
shared.model.lora = lora
2023-06-19 11:31:24 -04:00
shared.lora_names = [lora_names[0]]
return
2023-06-05 22:29:29 -04:00
def add_lora_exllamav2(lora_names):
from exllamav2 import ExLlamaV2Lora
if isinstance(shared.model.loras, list):
for lora in shared.model.loras:
lora.unload()
if len(lora_names) > 0:
logger.info("Applying the following LoRAs to {}: {}".format(shared.model_name, ', '.join(lora_names)))
shared.model.loras = []
for lora_name in lora_names:
lora_path = get_lora_path(lora_name)
if shared.model.__class__.__name__ == 'Exllamav2Model':
lora = ExLlamaV2Lora.from_directory(shared.model.model, str(lora_path))
else:
lora = ExLlamaV2Lora.from_directory(shared.model.ex_model, str(lora_path))
shared.model.loras.append(lora)
shared.lora_names = lora_names
else:
shared.lora_names = []
shared.model.loras = None
2023-06-19 11:31:24 -04:00
def add_lora_autogptq(lora_names):
'''
Adapted from https://github.com/Ph0rk0z/text-generation-webui-testing
'''
2023-06-05 22:29:29 -04:00
2023-06-19 11:31:24 -04:00
try:
from auto_gptq import get_gptq_peft_model
from auto_gptq.utils.peft_utils import GPTQLoraConfig
except:
logger.error("This version of AutoGPTQ does not support LoRA. You need to install from source or wait for a new release.")
return
2023-06-05 22:29:29 -04:00
2023-07-12 14:33:25 -04:00
if len(lora_names) == 0:
2023-07-09 00:03:43 -04:00
reload_model()
2023-06-19 11:31:24 -04:00
shared.lora_names = []
return
2023-06-05 22:29:29 -04:00
else:
2023-06-19 11:31:24 -04:00
if len(lora_names) > 1:
logger.warning('AutoGPTQ can only work with 1 LoRA at the moment. Only the first one in the list will be loaded.')
2023-07-09 00:03:43 -04:00
if not shared.args.no_inject_fused_attention:
logger.warning('Fused Atttention + AutoGPTQ may break Lora loading. Disable it.')
2023-06-19 11:31:24 -04:00
peft_config = GPTQLoraConfig(
inference_mode=True,
)
2023-08-10 12:54:28 -04:00
lora_path = get_lora_path(lora_names[0])
2023-06-19 11:31:24 -04:00
logger.info("Applying the following LoRAs to {}: {}".format(shared.model_name, ', '.join([lora_names[0]])))
shared.model = get_gptq_peft_model(shared.model, peft_config, lora_path)
shared.lora_names = [lora_names[0]]
return
def add_lora_transformers(lora_names):
prior_set = set(shared.lora_names)
added_set = set(lora_names) - prior_set
removed_set = prior_set - set(lora_names)
# If no LoRA needs to be added or removed, exit
if len(added_set) == 0 and len(removed_set) == 0:
return
# Add a LoRA when another LoRA is already present
if len(removed_set) == 0 and len(prior_set) > 0 and "__merged" not in shared.model.peft_config.keys():
2023-06-19 11:31:24 -04:00
logger.info(f"Adding the LoRA(s) named {added_set} to the model...")
for lora in added_set:
2023-08-10 12:54:28 -04:00
shared.model.load_adapter(get_lora_path(lora), lora)
2023-06-19 11:31:24 -04:00
if len(lora_names) > 1:
merge_loras()
2023-06-19 11:31:24 -04:00
return
# If any LoRA needs to be removed, start over
if len(removed_set) > 0:
# shared.model may no longer be PeftModel
2023-07-12 14:33:25 -04:00
if hasattr(shared.model, 'disable_adapter'):
shared.model.disable_adapter()
shared.model = shared.model.base_model.model
2023-06-19 11:31:24 -04:00
if len(lora_names) > 0:
params = {}
if not shared.args.cpu:
2023-07-12 14:33:25 -04:00
if shared.args.load_in_4bit or shared.args.load_in_8bit:
params['peft_type'] = shared.model.dtype
else:
params['dtype'] = shared.model.dtype
if hasattr(shared.model, "hf_device_map"):
params['device_map'] = {"base_model.model." + k: v for k, v in shared.model.hf_device_map.items()}
2023-06-19 11:31:24 -04:00
logger.info("Applying the following LoRAs to {}: {}".format(shared.model_name, ', '.join(lora_names)))
2023-08-10 12:54:28 -04:00
shared.model = PeftModel.from_pretrained(shared.model, get_lora_path(lora_names[0]), adapter_name=lora_names[0], **params)
2023-06-19 11:31:24 -04:00
for lora in lora_names[1:]:
2023-08-10 12:54:28 -04:00
shared.model.load_adapter(get_lora_path(lora), lora)
2023-06-19 11:31:24 -04:00
if len(lora_names) > 1:
merge_loras()
2023-06-19 11:31:24 -04:00
shared.lora_names = lora_names
if not shared.args.load_in_8bit and not shared.args.cpu:
shared.model.half()
if not hasattr(shared.model, "hf_device_map"):
if torch.backends.mps.is_available():
2023-06-19 11:31:24 -04:00
device = torch.device('mps')
shared.model = shared.model.to(device)
else:
shared.model = shared.model.cuda()
2023-10-23 16:07:17 -04:00
def merge_loras():
if len(list({shared.model.peft_config[adapter].r for adapter in shared.model.peft_config.keys()})) > 1:
logger.warning("The loaded LoRAs cannot be merged, as they have dissimilar ranks. Only the first one will be active.")
return
shared.model.add_weighted_adapter(shared.lora_names, [1] * len(shared.lora_names), "__merged")
shared.model.set_adapter("__merged")