2023-06-21 20:31:42 +02:00
|
|
|
import os
|
|
|
|
from pathlib import Path
|
2023-06-24 17:02:25 +02:00
|
|
|
from typing import Any, Dict, Optional, Union
|
2023-06-21 20:31:42 +02:00
|
|
|
|
|
|
|
import torch
|
2023-06-24 17:02:25 +02:00
|
|
|
from torch.nn import CrossEntropyLoss
|
|
|
|
from transformers import GenerationConfig, PretrainedConfig, PreTrainedModel
|
2023-06-21 20:31:42 +02:00
|
|
|
from transformers.modeling_outputs import CausalLMOutputWithPast
|
|
|
|
|
2023-09-11 16:57:38 +02:00
|
|
|
from modules import shared
|
2023-06-21 20:31:42 +02:00
|
|
|
from modules.logging_colors import logger
|
|
|
|
|
2023-06-25 01:24:17 +02:00
|
|
|
try:
|
|
|
|
from exllama.model import ExLlama, ExLlamaCache, ExLlamaConfig
|
|
|
|
except:
|
|
|
|
logger.warning('Exllama module failed to load. Will attempt to load from repositories.')
|
|
|
|
try:
|
|
|
|
from modules.relative_imports import RelativeImport
|
|
|
|
|
|
|
|
with RelativeImport("repositories/exllama"):
|
|
|
|
from model import ExLlama, ExLlamaCache, ExLlamaConfig
|
|
|
|
except:
|
|
|
|
logger.error("Could not find repositories/exllama/. Make sure that exllama is cloned inside repositories/ and is up to date.")
|
|
|
|
raise
|
2023-06-21 20:31:42 +02:00
|
|
|
|
|
|
|
|
|
|
|
class ExllamaHF(PreTrainedModel):
|
|
|
|
def __init__(self, config: ExLlamaConfig):
|
|
|
|
super().__init__(PretrainedConfig())
|
|
|
|
self.ex_config = config
|
|
|
|
self.ex_model = ExLlama(self.ex_config)
|
|
|
|
self.generation_config = GenerationConfig()
|
2023-06-26 05:10:13 +02:00
|
|
|
self.lora = None
|
2023-06-21 20:31:42 +02:00
|
|
|
|
2023-08-24 21:27:36 +02:00
|
|
|
self.ex_cache = ExLlamaCache(self.ex_model)
|
|
|
|
self.past_seq = None
|
|
|
|
|
|
|
|
if shared.args.cfg_cache:
|
|
|
|
self.ex_cache_negative = ExLlamaCache(self.ex_model)
|
|
|
|
self.past_seq_negative = None
|
|
|
|
|
2023-06-21 20:31:42 +02:00
|
|
|
def _validate_model_class(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def _validate_model_kwargs(self, model_kwargs: Dict[str, Any]):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def prepare_inputs_for_generation(self, input_ids, **kwargs):
|
|
|
|
return {'input_ids': input_ids, **kwargs}
|
|
|
|
|
|
|
|
@property
|
|
|
|
def device(self) -> torch.device:
|
|
|
|
return torch.device(0)
|
|
|
|
|
|
|
|
def __call__(self, *args, **kwargs):
|
2023-06-24 17:02:25 +02:00
|
|
|
use_cache = kwargs.get('use_cache', True)
|
|
|
|
labels = kwargs.get('labels', None)
|
2023-08-24 21:27:36 +02:00
|
|
|
past_key_values = kwargs.get('past_key_values', None)
|
|
|
|
|
|
|
|
if len(args) > 0:
|
|
|
|
if not shared.args.cfg_cache:
|
|
|
|
logger.error("Please enable the cfg-cache option to use CFG with ExLlama_HF.")
|
|
|
|
return
|
|
|
|
|
|
|
|
input_ids = args[0]
|
|
|
|
is_negative = True
|
|
|
|
past_seq = self.past_seq_negative
|
|
|
|
ex_cache = self.ex_cache_negative
|
|
|
|
else:
|
|
|
|
input_ids = kwargs['input_ids']
|
|
|
|
is_negative = False
|
|
|
|
past_seq = self.past_seq
|
|
|
|
ex_cache = self.ex_cache
|
|
|
|
|
2023-08-06 22:22:48 +02:00
|
|
|
seq = input_ids[0].tolist()
|
2023-08-24 21:27:36 +02:00
|
|
|
if is_negative and past_key_values is not None:
|
|
|
|
seq = past_key_values + seq
|
2023-06-24 17:02:25 +02:00
|
|
|
|
2023-08-24 21:27:36 +02:00
|
|
|
seq_tensor = torch.tensor(seq)
|
2023-09-19 22:12:19 +02:00
|
|
|
reset = True
|
2023-08-24 21:27:36 +02:00
|
|
|
|
|
|
|
# Make the forward call
|
2023-07-16 06:52:55 +02:00
|
|
|
if labels is None:
|
2023-09-19 22:12:19 +02:00
|
|
|
if past_seq is not None:
|
|
|
|
min_length = min(past_seq.shape[0], seq_tensor.shape[0])
|
|
|
|
indices = torch.nonzero(~torch.eq(past_seq[:min_length], seq_tensor[:min_length]))
|
|
|
|
if len(indices) > 0:
|
|
|
|
longest_prefix = indices[0].item()
|
|
|
|
else:
|
|
|
|
longest_prefix = min_length
|
|
|
|
|
|
|
|
if longest_prefix > 0:
|
|
|
|
reset = False
|
|
|
|
ex_cache.current_seq_len = longest_prefix
|
|
|
|
if len(seq_tensor) - longest_prefix > 1:
|
|
|
|
self.ex_model.forward(seq_tensor[longest_prefix:-1].view(1, -1), ex_cache, preprocess_only=True, lora=self.lora)
|
|
|
|
|
|
|
|
if reset:
|
2023-08-24 21:27:36 +02:00
|
|
|
ex_cache.current_seq_len = 0
|
2023-09-19 22:12:19 +02:00
|
|
|
if len(seq_tensor) > 1:
|
|
|
|
self.ex_model.forward(seq_tensor[:-1].view(1, -1), ex_cache, preprocess_only=True, lora=self.lora)
|
2023-07-16 06:52:55 +02:00
|
|
|
|
2023-09-19 22:12:19 +02:00
|
|
|
logits = self.ex_model.forward(seq_tensor[-1:].view(1, -1), ex_cache, lora=self.lora).to(input_ids.device)
|
2023-07-16 06:52:55 +02:00
|
|
|
else:
|
2023-08-24 21:27:36 +02:00
|
|
|
ex_cache.current_seq_len = 0
|
2023-09-19 22:12:19 +02:00
|
|
|
logits = self.ex_model.forward(seq_tensor.view(1, -1), ex_cache, last_id_only=False, lora=self.lora)
|
2023-07-16 06:52:55 +02:00
|
|
|
|
2023-08-24 21:27:36 +02:00
|
|
|
if is_negative:
|
|
|
|
self.past_seq_negative = seq_tensor
|
|
|
|
else:
|
|
|
|
self.past_seq = seq_tensor
|
2023-06-24 17:02:25 +02:00
|
|
|
|
|
|
|
loss = None
|
|
|
|
if labels is not None:
|
|
|
|
# Shift so that tokens < n predict n
|
|
|
|
shift_logits = logits[..., :-1, :].contiguous()
|
|
|
|
shift_labels = labels[..., 1:].contiguous()
|
|
|
|
# Flatten the tokens
|
|
|
|
loss_fct = CrossEntropyLoss()
|
|
|
|
shift_logits = shift_logits.view(-1, logits.shape[-1])
|
|
|
|
shift_labels = shift_labels.view(-1)
|
|
|
|
# Enable model parallelism
|
|
|
|
shift_labels = shift_labels.to(shift_logits.device)
|
|
|
|
loss = loss_fct(shift_logits, shift_labels)
|
|
|
|
|
2023-08-24 21:27:36 +02:00
|
|
|
return CausalLMOutputWithPast(logits=logits, past_key_values=seq if use_cache else None, loss=loss)
|
2023-06-21 20:31:42 +02:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *model_args, **kwargs):
|
|
|
|
assert len(model_args) == 0 and len(kwargs) == 0, "extra args is currently not supported"
|
|
|
|
if isinstance(pretrained_model_name_or_path, str):
|
|
|
|
pretrained_model_name_or_path = Path(pretrained_model_name_or_path)
|
2023-06-25 01:24:17 +02:00
|
|
|
|
2023-06-21 20:31:42 +02:00
|
|
|
pretrained_model_name_or_path = Path(f'{shared.args.model_dir}') / Path(pretrained_model_name_or_path)
|
|
|
|
config = ExLlamaConfig(pretrained_model_name_or_path / 'config.json')
|
|
|
|
|
|
|
|
# from 'oobabooga/text-generation-webui/modules/exllama.py'
|
|
|
|
weight_path = None
|
|
|
|
for ext in ['.safetensors', '.pt', '.bin']:
|
|
|
|
found = list(pretrained_model_name_or_path.glob(f"*{ext}"))
|
|
|
|
if len(found) > 0:
|
|
|
|
weight_path = found[-1]
|
|
|
|
break
|
|
|
|
assert weight_path is not None, f'could not find weight in "{pretrained_model_name_or_path}"'
|
|
|
|
|
|
|
|
config.model_path = str(weight_path)
|
2023-06-26 03:49:26 +02:00
|
|
|
config.max_seq_len = shared.args.max_seq_len
|
|
|
|
config.compress_pos_emb = shared.args.compress_pos_emb
|
2023-06-22 21:05:25 +02:00
|
|
|
if shared.args.gpu_split:
|
|
|
|
config.set_auto_map(shared.args.gpu_split)
|
|
|
|
config.gpu_peer_fix = True
|
2023-07-04 06:13:16 +02:00
|
|
|
|
2023-09-11 06:14:36 +02:00
|
|
|
if shared.args.alpha_value > 1 and shared.args.rope_freq_base == 0:
|
|
|
|
config.alpha_value = shared.args.alpha_value
|
2023-07-04 06:13:16 +02:00
|
|
|
config.calculate_rotary_embedding_base()
|
2023-09-11 06:14:36 +02:00
|
|
|
elif shared.args.rope_freq_base > 0:
|
|
|
|
config.rotary_embedding_base = shared.args.rope_freq_base
|
2023-07-04 06:13:16 +02:00
|
|
|
|
2023-06-29 20:03:16 +02:00
|
|
|
if torch.version.hip:
|
|
|
|
config.rmsnorm_no_half2 = True
|
|
|
|
config.rope_no_half2 = True
|
|
|
|
config.matmul_no_half2 = True
|
|
|
|
config.silu_no_half2 = True
|
2023-06-25 01:24:17 +02:00
|
|
|
|
2023-06-21 20:31:42 +02:00
|
|
|
# This slowes down a bit but align better with autogptq generation.
|
|
|
|
# TODO: Should give user choice to tune the exllama config
|
2023-06-22 21:05:25 +02:00
|
|
|
# config.fused_attn = False
|
|
|
|
# config.fused_mlp_thd = 0
|
2023-06-21 20:31:42 +02:00
|
|
|
|
2023-06-22 21:05:25 +02:00
|
|
|
return ExllamaHF(config)
|