2023-07-16 01:21:13 -04:00
|
|
|
import os
|
|
|
|
from pathlib import Path
|
|
|
|
from typing import Any, Dict, Optional, Union
|
|
|
|
|
|
|
|
import torch
|
|
|
|
from torch.nn import CrossEntropyLoss
|
|
|
|
from transformers import GenerationConfig, PretrainedConfig, PreTrainedModel
|
|
|
|
from transformers.modeling_outputs import CausalLMOutputWithPast
|
|
|
|
|
2024-02-08 00:40:58 -05:00
|
|
|
from modules import RoPE, llama_cpp_python_hijack, shared
|
2023-07-16 01:21:13 -04:00
|
|
|
from modules.logging_colors import logger
|
|
|
|
|
2023-11-17 08:14:25 -05:00
|
|
|
try:
|
|
|
|
import llama_cpp
|
|
|
|
except:
|
|
|
|
llama_cpp = None
|
|
|
|
|
|
|
|
try:
|
|
|
|
import llama_cpp_cuda
|
|
|
|
except:
|
|
|
|
llama_cpp_cuda = None
|
|
|
|
|
2023-12-19 15:30:53 -05:00
|
|
|
try:
|
|
|
|
import llama_cpp_cuda_tensorcores
|
|
|
|
except:
|
|
|
|
llama_cpp_cuda_tensorcores = None
|
|
|
|
|
2023-11-17 08:14:25 -05:00
|
|
|
|
|
|
|
def llama_cpp_lib():
|
2023-12-19 15:30:53 -05:00
|
|
|
if shared.args.cpu and llama_cpp is not None:
|
2023-11-17 08:14:25 -05:00
|
|
|
return llama_cpp
|
2023-12-19 15:30:53 -05:00
|
|
|
elif shared.args.tensorcores and llama_cpp_cuda_tensorcores is not None:
|
|
|
|
return llama_cpp_cuda_tensorcores
|
|
|
|
elif llama_cpp_cuda is not None:
|
2023-11-17 08:14:25 -05:00
|
|
|
return llama_cpp_cuda
|
2023-12-19 15:30:53 -05:00
|
|
|
else:
|
|
|
|
return llama_cpp
|
2023-11-17 08:14:25 -05:00
|
|
|
|
2023-07-24 10:25:36 -04:00
|
|
|
|
2023-07-16 01:21:13 -04:00
|
|
|
class LlamacppHF(PreTrainedModel):
|
2023-08-27 01:15:06 -04:00
|
|
|
def __init__(self, model, path):
|
2023-07-16 01:21:13 -04:00
|
|
|
super().__init__(PretrainedConfig())
|
|
|
|
self.model = model
|
|
|
|
self.generation_config = GenerationConfig()
|
2023-08-24 15:27:36 -04:00
|
|
|
|
|
|
|
self.past_seq = None
|
|
|
|
self.llamacpp_cache = {
|
|
|
|
'n_tokens': self.model.n_tokens,
|
|
|
|
'input_ids': self.model.input_ids,
|
2023-08-24 19:32:21 -04:00
|
|
|
'scores': self.model.scores,
|
2023-11-17 22:31:27 -05:00
|
|
|
'ctx': self.model._ctx
|
2023-08-24 15:27:36 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if shared.args.cfg_cache:
|
|
|
|
self.past_seq_negative = None
|
|
|
|
self.llamacpp_cache_negative = {
|
|
|
|
'n_tokens': self.model.n_tokens,
|
|
|
|
'input_ids': self.model.input_ids.copy(),
|
2023-08-24 19:32:21 -04:00
|
|
|
'scores': self.model.scores.copy(),
|
2024-02-19 21:09:40 -05:00
|
|
|
'ctx': llama_cpp_lib()._internals._LlamaContext(model=model._model, params=model.context_params)
|
2023-08-24 15:27:36 -04:00
|
|
|
}
|
2023-07-16 01:21:13 -04: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}
|
|
|
|
|
2023-08-24 15:27:36 -04:00
|
|
|
def save_cache(self):
|
|
|
|
self.llamacpp_cache.update({
|
|
|
|
'n_tokens': self.model.n_tokens,
|
|
|
|
'input_ids': self.model.input_ids,
|
2023-08-24 19:32:21 -04:00
|
|
|
'scores': self.model.scores,
|
2023-11-17 22:31:27 -05:00
|
|
|
'ctx': self.model._ctx
|
2023-08-24 15:27:36 -04:00
|
|
|
})
|
|
|
|
|
|
|
|
def save_negative_cache(self):
|
|
|
|
self.llamacpp_cache_negative.update({
|
|
|
|
'n_tokens': self.model.n_tokens,
|
|
|
|
'input_ids': self.model.input_ids,
|
2023-08-24 19:32:21 -04:00
|
|
|
'scores': self.model.scores,
|
2023-11-17 22:31:27 -05:00
|
|
|
'ctx': self.model._ctx
|
2023-08-24 15:27:36 -04:00
|
|
|
})
|
|
|
|
|
|
|
|
def load_cache(self):
|
|
|
|
self.model.n_tokens = self.llamacpp_cache['n_tokens']
|
|
|
|
self.model.input_ids = self.llamacpp_cache['input_ids']
|
|
|
|
self.model.scores = self.llamacpp_cache['scores']
|
2023-11-17 22:31:27 -05:00
|
|
|
self.model._ctx = self.llamacpp_cache['ctx']
|
2023-08-24 15:27:36 -04:00
|
|
|
|
|
|
|
def load_negative_cache(self):
|
|
|
|
self.model.n_tokens = self.llamacpp_cache_negative['n_tokens']
|
|
|
|
self.model.input_ids = self.llamacpp_cache_negative['input_ids']
|
|
|
|
self.model.scores = self.llamacpp_cache_negative['scores']
|
2023-11-17 22:31:27 -05:00
|
|
|
self.model._ctx = self.llamacpp_cache_negative['ctx']
|
2023-08-24 15:27:36 -04:00
|
|
|
|
2023-07-16 01:21:13 -04:00
|
|
|
@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)
|
2023-08-24 15:27:36 -04: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 llamacpp_HF.")
|
|
|
|
return
|
|
|
|
|
|
|
|
input_ids = args[0]
|
|
|
|
is_negative = True
|
|
|
|
past_seq = self.past_seq_negative
|
|
|
|
self.load_negative_cache()
|
|
|
|
else:
|
|
|
|
input_ids = kwargs['input_ids']
|
|
|
|
is_negative = False
|
|
|
|
past_seq = self.past_seq
|
|
|
|
self.load_cache()
|
|
|
|
|
2023-08-06 16:22:48 -04:00
|
|
|
seq = input_ids[0].tolist()
|
2023-08-24 15:27:36 -04:00
|
|
|
if is_negative and past_key_values is not None:
|
|
|
|
seq = past_key_values + seq
|
2023-07-16 01:21:13 -04:00
|
|
|
|
|
|
|
seq_tensor = torch.tensor(seq)
|
2023-09-17 14:50:47 -04:00
|
|
|
reset = True
|
2023-08-24 15:27:36 -04:00
|
|
|
|
2023-09-17 14:50:47 -04:00
|
|
|
# Make the forward call. The prefix-match code has been adapted from
|
|
|
|
# https://github.com/abetlen/llama-cpp-python/commit/f4090a0bb2a2a25acfe28d31c82cc1aa273bedee
|
2023-07-16 01:21:13 -04:00
|
|
|
if labels is None:
|
2023-09-17 14:50:47 -04:00
|
|
|
if past_seq is not None:
|
2023-09-18 14:02:45 -04:00
|
|
|
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
|
2023-09-17 14:50:47 -04:00
|
|
|
|
|
|
|
if longest_prefix > 0:
|
|
|
|
reset = False
|
2023-09-19 17:14:40 -04:00
|
|
|
self.model.n_tokens = longest_prefix
|
|
|
|
if len(seq_tensor) - longest_prefix > 0:
|
|
|
|
self.model.eval(seq[longest_prefix:])
|
2024-01-07 08:36:26 -05:00
|
|
|
else:
|
|
|
|
self.model.n_tokens -= 1
|
|
|
|
self.model.eval([seq[-1]])
|
2023-09-17 14:50:47 -04:00
|
|
|
|
|
|
|
if reset:
|
2023-07-16 01:21:13 -04:00
|
|
|
self.model.reset()
|
|
|
|
self.model.eval(seq)
|
|
|
|
|
2023-08-24 15:27:36 -04:00
|
|
|
logits = torch.tensor(self.model.scores[self.model.n_tokens - 1, :]).view(1, 1, -1).to(input_ids.device)
|
2023-07-16 01:21:13 -04:00
|
|
|
else:
|
|
|
|
self.model.reset()
|
|
|
|
self.model.eval(seq)
|
|
|
|
logits = torch.tensor(self.model.eval_logits)
|
2023-08-06 16:22:48 -04:00
|
|
|
logits = logits.view(1, logits.shape[0], logits.shape[1]).to(input_ids.device)
|
2023-07-16 01:21:13 -04:00
|
|
|
|
2023-08-24 15:27:36 -04:00
|
|
|
if is_negative:
|
|
|
|
self.save_negative_cache()
|
|
|
|
self.past_seq_negative = seq_tensor
|
|
|
|
else:
|
|
|
|
self.save_cache()
|
|
|
|
self.past_seq = seq_tensor
|
2023-07-16 23:49:48 -04:00
|
|
|
|
2023-07-16 01:21:13 -04: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 15:27:36 -04:00
|
|
|
return CausalLMOutputWithPast(logits=logits, past_key_values=seq if use_cache else None, loss=loss)
|
2023-07-16 01:21:13 -04: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"
|
2023-09-26 21:05:00 -04:00
|
|
|
|
2023-07-16 01:21:13 -04:00
|
|
|
if isinstance(pretrained_model_name_or_path, str):
|
|
|
|
pretrained_model_name_or_path = Path(pretrained_model_name_or_path)
|
|
|
|
|
|
|
|
path = Path(f'{shared.args.model_dir}') / Path(pretrained_model_name_or_path)
|
|
|
|
if path.is_file():
|
|
|
|
model_file = path
|
|
|
|
else:
|
2023-09-11 10:30:56 -04:00
|
|
|
model_file = list(path.glob('*.gguf'))[0]
|
2023-07-16 01:21:13 -04:00
|
|
|
|
|
|
|
logger.info(f"llama.cpp weights detected: {model_file}\n")
|
2023-08-18 11:03:34 -04:00
|
|
|
|
|
|
|
if shared.args.tensor_split is None or shared.args.tensor_split.strip() == '':
|
|
|
|
tensor_split_list = None
|
|
|
|
else:
|
|
|
|
tensor_split_list = [float(x) for x in shared.args.tensor_split.strip().split(",")]
|
|
|
|
|
2023-07-16 01:21:13 -04:00
|
|
|
params = {
|
|
|
|
'model_path': str(model_file),
|
|
|
|
'n_ctx': shared.args.n_ctx,
|
|
|
|
'n_threads': shared.args.threads or None,
|
2023-10-02 00:27:04 -04:00
|
|
|
'n_threads_batch': shared.args.threads_batch or None,
|
2023-07-16 01:21:13 -04:00
|
|
|
'n_batch': shared.args.n_batch,
|
|
|
|
'use_mmap': not shared.args.no_mmap,
|
|
|
|
'use_mlock': shared.args.mlock,
|
2023-10-22 15:22:06 -04:00
|
|
|
'mul_mat_q': not shared.args.no_mul_mat_q,
|
2023-09-26 21:05:00 -04:00
|
|
|
'numa': shared.args.numa,
|
2023-07-16 01:21:13 -04:00
|
|
|
'n_gpu_layers': shared.args.n_gpu_layers,
|
2023-08-25 09:53:37 -04:00
|
|
|
'rope_freq_base': RoPE.get_rope_freq_base(shared.args.alpha_value, shared.args.rope_freq_base),
|
2023-08-18 11:03:34 -04:00
|
|
|
'tensor_split': tensor_split_list,
|
2023-07-17 21:32:37 -04:00
|
|
|
'rope_freq_scale': 1.0 / shared.args.compress_pos_emb,
|
2023-11-07 17:35:48 -05:00
|
|
|
'logits_all': shared.args.logits_all,
|
2024-02-04 21:36:40 -05:00
|
|
|
'offload_kqv': not shared.args.no_offload_kqv,
|
|
|
|
'split_mode': 1 if not shared.args.row_split else 2
|
2023-07-16 01:21:13 -04:00
|
|
|
}
|
2023-08-27 01:11:07 -04:00
|
|
|
|
2023-11-17 08:14:25 -05:00
|
|
|
Llama = llama_cpp_lib().Llama
|
|
|
|
model = Llama(**params)
|
|
|
|
|
2023-08-27 01:15:06 -04:00
|
|
|
return LlamacppHF(model, model_file)
|