2023-09-12 13:33:07 -04:00
|
|
|
import os
|
2023-10-21 02:53:24 -04:00
|
|
|
import traceback
|
2023-09-12 13:33:07 -04:00
|
|
|
from pathlib import Path
|
|
|
|
from typing import Any, Dict, Optional, Union
|
|
|
|
|
|
|
|
import torch
|
2023-11-02 14:23:04 -04:00
|
|
|
from exllamav2 import (
|
|
|
|
ExLlamaV2,
|
|
|
|
ExLlamaV2Cache,
|
|
|
|
ExLlamaV2Cache_8bit,
|
2024-03-06 21:02:25 -05:00
|
|
|
ExLlamaV2Cache_Q4,
|
2024-09-27 23:26:03 -04:00
|
|
|
ExLlamaV2Cache_TP,
|
2023-11-02 14:23:04 -04:00
|
|
|
ExLlamaV2Config
|
|
|
|
)
|
2023-09-12 13:33:07 -04:00
|
|
|
from torch.nn import CrossEntropyLoss
|
|
|
|
from transformers import GenerationConfig, PretrainedConfig, PreTrainedModel
|
|
|
|
from transformers.modeling_outputs import CausalLMOutputWithPast
|
|
|
|
|
|
|
|
from modules import shared
|
|
|
|
from modules.logging_colors import logger
|
|
|
|
|
2023-09-18 15:25:17 -04:00
|
|
|
try:
|
|
|
|
import flash_attn
|
|
|
|
except ModuleNotFoundError:
|
|
|
|
logger.warning(
|
|
|
|
'You are running ExLlamaV2 without flash-attention. This will cause the VRAM usage '
|
|
|
|
'to be a lot higher than it could be.\n'
|
|
|
|
'Try installing flash-attention following the instructions here: '
|
|
|
|
'https://github.com/Dao-AILab/flash-attention#installation-and-features'
|
|
|
|
)
|
|
|
|
pass
|
2023-10-21 02:53:24 -04:00
|
|
|
except Exception:
|
|
|
|
logger.warning('Failed to load flash-attention due to the following error:\n')
|
|
|
|
traceback.print_exc()
|
2023-09-18 15:25:17 -04:00
|
|
|
|
2023-09-12 13:33:07 -04:00
|
|
|
|
|
|
|
class Exllamav2HF(PreTrainedModel):
|
|
|
|
def __init__(self, config: ExLlamaV2Config):
|
|
|
|
super().__init__(PretrainedConfig())
|
|
|
|
self.ex_config = config
|
2023-10-14 15:12:41 -04:00
|
|
|
self.loras = None
|
2024-02-16 13:26:10 -05:00
|
|
|
self.generation_config = GenerationConfig()
|
2023-09-12 13:33:07 -04:00
|
|
|
|
2024-02-17 15:42:22 -05:00
|
|
|
self.ex_model = ExLlamaV2(config)
|
2024-02-16 13:26:10 -05:00
|
|
|
|
2024-09-27 23:26:03 -04:00
|
|
|
split = None
|
|
|
|
if shared.args.gpu_split:
|
|
|
|
split = [float(alloc) for alloc in shared.args.gpu_split.split(",")]
|
2024-02-16 13:26:10 -05:00
|
|
|
|
2024-09-27 23:26:03 -04:00
|
|
|
if shared.args.enable_tp:
|
2024-09-27 23:26:36 -04:00
|
|
|
self.ex_model.load_tp(split)
|
2024-09-27 23:26:03 -04:00
|
|
|
elif not shared.args.autosplit:
|
2024-09-27 23:26:36 -04:00
|
|
|
self.ex_model.load(split)
|
2023-09-12 13:33:07 -04:00
|
|
|
|
2024-09-27 23:26:03 -04:00
|
|
|
# Determine the correct cache type
|
2024-02-17 15:42:22 -05:00
|
|
|
if shared.args.cache_8bit:
|
2024-09-27 23:26:03 -04:00
|
|
|
cache_type = ExLlamaV2Cache_8bit
|
2024-03-06 21:02:25 -05:00
|
|
|
elif shared.args.cache_4bit:
|
2024-09-27 23:26:03 -04:00
|
|
|
cache_type = ExLlamaV2Cache_Q4
|
2024-02-17 15:42:22 -05:00
|
|
|
else:
|
2024-09-27 23:26:03 -04:00
|
|
|
cache_type = ExLlamaV2Cache
|
2024-02-17 15:42:22 -05:00
|
|
|
|
2024-09-27 23:26:03 -04:00
|
|
|
# Use TP if specified
|
|
|
|
if shared.args.enable_tp:
|
|
|
|
self.ex_cache = ExLlamaV2Cache_TP(self.ex_model, base=cache_type)
|
|
|
|
else:
|
|
|
|
self.ex_cache = cache_type(self.ex_model, lazy=shared.args.autosplit)
|
|
|
|
|
|
|
|
if shared.args.autosplit and not shared.args.enable_tp:
|
2024-02-17 15:42:22 -05:00
|
|
|
self.ex_model.load_autosplit(self.ex_cache)
|
|
|
|
|
2023-11-02 14:23:04 -04:00
|
|
|
self.past_seq = None
|
2023-09-12 13:33:07 -04:00
|
|
|
if shared.args.cfg_cache:
|
2023-11-02 14:23:04 -04:00
|
|
|
if shared.args.cache_8bit:
|
|
|
|
self.ex_cache_negative = ExLlamaV2Cache_8bit(self.ex_model)
|
2024-03-07 11:08:21 -05:00
|
|
|
elif shared.args.cache_4bit:
|
|
|
|
self.ex_cache_negative = ExLlamaV2Cache_Q4(self.ex_model)
|
2023-11-02 14:23:04 -04:00
|
|
|
else:
|
|
|
|
self.ex_cache_negative = ExLlamaV2Cache(self.ex_model)
|
|
|
|
|
2023-09-12 13:33:07 -04:00
|
|
|
self.past_seq_negative = None
|
|
|
|
|
|
|
|
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):
|
|
|
|
use_cache = kwargs.get('use_cache', True)
|
|
|
|
labels = kwargs.get('labels', None)
|
|
|
|
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 ExLlamav2_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
|
|
|
|
|
|
|
|
seq = input_ids[0].tolist()
|
|
|
|
if is_negative and past_key_values is not None:
|
|
|
|
seq = past_key_values + seq
|
|
|
|
|
|
|
|
seq_tensor = torch.tensor(seq)
|
2023-09-19 16:12:19 -04:00
|
|
|
reset = True
|
2023-09-12 13:33:07 -04:00
|
|
|
|
|
|
|
# Make the forward call
|
|
|
|
if labels is None:
|
2023-09-19 16:12:19 -04: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:
|
2023-10-14 15:12:41 -04:00
|
|
|
self.ex_model.forward(seq_tensor[longest_prefix:-1].view(1, -1), ex_cache, preprocess_only=True, loras=self.loras)
|
2023-10-05 11:20:56 -04:00
|
|
|
elif len(seq_tensor) == longest_prefix:
|
|
|
|
# Very tricky: if the prefix we are reusing *is* the input_ids, then we have to back up the cache pointer by one,
|
|
|
|
# because we feed input_ids[-1] to forward() below, but that last token is already in the cache!
|
|
|
|
ex_cache.current_seq_len -= 1
|
2023-09-19 16:12:19 -04:00
|
|
|
|
|
|
|
if reset:
|
2023-09-12 13:33:07 -04:00
|
|
|
ex_cache.current_seq_len = 0
|
2023-09-19 16:12:19 -04:00
|
|
|
if len(seq_tensor) > 1:
|
2023-10-14 15:12:41 -04:00
|
|
|
self.ex_model.forward(seq_tensor[:-1].view(1, -1), ex_cache, preprocess_only=True, loras=self.loras)
|
2023-09-12 13:33:07 -04:00
|
|
|
|
2023-10-18 22:16:05 -04:00
|
|
|
logits = self.ex_model.forward(seq_tensor[-1:].view(1, -1), ex_cache, loras=self.loras).to(input_ids.device).float()
|
2023-09-12 13:33:07 -04:00
|
|
|
else:
|
|
|
|
ex_cache.current_seq_len = 0
|
2023-10-18 22:16:05 -04:00
|
|
|
logits = self.ex_model.forward(seq_tensor.view(1, -1), ex_cache, last_id_only=False, loras=self.loras).float()
|
2023-09-12 13:33:07 -04:00
|
|
|
|
|
|
|
if is_negative:
|
|
|
|
self.past_seq_negative = seq_tensor
|
|
|
|
else:
|
|
|
|
self.past_seq = seq_tensor
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
return CausalLMOutputWithPast(logits=logits, past_key_values=seq if use_cache else None, loss=loss)
|
|
|
|
|
|
|
|
@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)
|
|
|
|
|
|
|
|
pretrained_model_name_or_path = Path(f'{shared.args.model_dir}') / Path(pretrained_model_name_or_path)
|
|
|
|
|
|
|
|
config = ExLlamaV2Config()
|
2023-09-12 20:42:22 -04:00
|
|
|
config.model_dir = str(pretrained_model_name_or_path)
|
2023-09-12 13:33:07 -04:00
|
|
|
config.prepare()
|
2023-09-12 18:02:47 -04:00
|
|
|
|
2023-09-12 13:33:07 -04:00
|
|
|
config.max_seq_len = shared.args.max_seq_len
|
2023-09-13 01:35:09 -04:00
|
|
|
config.scale_pos_emb = shared.args.compress_pos_emb
|
|
|
|
config.scale_alpha_value = shared.args.alpha_value
|
2023-11-02 11:19:42 -04:00
|
|
|
config.no_flash_attn = shared.args.no_flash_attn
|
2024-07-11 18:47:37 -04:00
|
|
|
config.no_xformers = shared.args.no_xformers
|
|
|
|
config.no_sdpa = shared.args.no_sdpa
|
2023-12-17 10:08:33 -05:00
|
|
|
config.num_experts_per_token = int(shared.args.num_experts_per_token)
|
2023-09-12 13:33:07 -04:00
|
|
|
|
|
|
|
return Exllamav2HF(config)
|