2023-04-16 00:36:50 -04:00
|
|
|
import ast
|
2023-06-25 00:38:54 -04:00
|
|
|
import copy
|
2023-08-21 00:40:22 -04:00
|
|
|
import html
|
2024-01-07 13:06:23 -05:00
|
|
|
import pprint
|
2023-04-10 09:29:10 -04:00
|
|
|
import random
|
2023-02-23 10:05:25 -05:00
|
|
|
import time
|
2023-03-20 12:36:52 -04:00
|
|
|
import traceback
|
2023-02-23 10:05:25 -05:00
|
|
|
|
2023-02-23 11:28:30 -05:00
|
|
|
import numpy as np
|
2023-02-23 10:05:25 -05:00
|
|
|
import torch
|
|
|
|
import transformers
|
2024-04-11 17:42:20 -04:00
|
|
|
from transformers import (
|
|
|
|
LogitsProcessorList,
|
|
|
|
is_torch_npu_available,
|
|
|
|
is_torch_xpu_available
|
|
|
|
)
|
2023-02-23 12:41:42 -05:00
|
|
|
|
|
|
|
import modules.shared as shared
|
2024-05-19 22:29:39 -04:00
|
|
|
from modules import models
|
2024-03-08 22:25:33 -05:00
|
|
|
from modules.cache_utils import process_llamacpp_cache
|
2023-06-25 00:38:54 -04:00
|
|
|
from modules.callbacks import (
|
|
|
|
Iteratorize,
|
|
|
|
Stream,
|
|
|
|
_StopEverythingStoppingCriteria
|
|
|
|
)
|
2023-02-23 10:05:25 -05:00
|
|
|
from modules.extensions import apply_extensions
|
2023-12-17 00:01:23 -05:00
|
|
|
from modules.grammar.grammar_utils import initialize_grammar
|
|
|
|
from modules.grammar.logits_process import GrammarConstrainedLogitsProcessor
|
2024-04-04 19:10:47 -04:00
|
|
|
from modules.html_generator import generate_basic_html
|
2023-05-21 21:42:34 -04:00
|
|
|
from modules.logging_colors import logger
|
2024-05-19 22:29:39 -04:00
|
|
|
from modules.models import clear_torch_cache, load_model
|
2023-02-23 12:41:42 -05:00
|
|
|
|
2023-02-23 10:05:25 -05:00
|
|
|
|
2023-05-24 08:38:20 -04:00
|
|
|
def generate_reply(*args, **kwargs):
|
2024-05-19 22:29:39 -04:00
|
|
|
if shared.args.idle_timeout > 0 and shared.model is None and shared.previous_model_name not in [None, 'None']:
|
|
|
|
shared.model, shared.tokenizer = load_model(shared.previous_model_name)
|
|
|
|
|
2023-05-24 08:38:20 -04:00
|
|
|
shared.generation_lock.acquire()
|
|
|
|
try:
|
|
|
|
for result in _generate_reply(*args, **kwargs):
|
|
|
|
yield result
|
|
|
|
finally:
|
2024-05-19 22:29:39 -04:00
|
|
|
models.last_generation_time = time.time()
|
2023-05-24 08:38:20 -04:00
|
|
|
shared.generation_lock.release()
|
|
|
|
|
|
|
|
|
2023-12-12 16:00:38 -05:00
|
|
|
def _generate_reply(question, state, stopping_strings=None, is_chat=False, escape_html=False, for_ui=False):
|
2023-08-06 20:49:27 -04:00
|
|
|
|
|
|
|
# Find the appropriate generation function
|
|
|
|
generate_func = apply_extensions('custom_generate_reply')
|
|
|
|
if generate_func is None:
|
|
|
|
if shared.model_name == 'None' or shared.model is None:
|
|
|
|
logger.error("No model is loaded! Select one in the Model tab.")
|
2023-09-17 11:12:08 -04:00
|
|
|
yield ''
|
|
|
|
return
|
2023-08-06 20:49:27 -04:00
|
|
|
|
2024-04-04 19:23:58 -04:00
|
|
|
if shared.model.__class__.__name__ in ['LlamaCppModel', 'Exllamav2Model']:
|
2023-08-06 20:49:27 -04:00
|
|
|
generate_func = generate_reply_custom
|
|
|
|
else:
|
|
|
|
generate_func = generate_reply_HF
|
|
|
|
|
2024-02-05 00:31:24 -05:00
|
|
|
if generate_func != generate_reply_HF and shared.args.verbose:
|
|
|
|
logger.info("PROMPT=")
|
2024-05-18 12:57:00 -04:00
|
|
|
print_prompt(question)
|
2024-02-05 00:31:24 -05:00
|
|
|
|
2023-08-06 20:49:27 -04:00
|
|
|
# Prepare the input
|
|
|
|
original_question = question
|
|
|
|
if not is_chat:
|
|
|
|
state = apply_extensions('state', state)
|
|
|
|
question = apply_extensions('input', question, state)
|
|
|
|
|
|
|
|
# Find the stopping strings
|
|
|
|
all_stop_strings = []
|
2023-11-06 00:38:29 -05:00
|
|
|
for st in (stopping_strings, state['custom_stopping_strings']):
|
|
|
|
if type(st) is str:
|
|
|
|
st = ast.literal_eval(f"[{st}]")
|
|
|
|
|
2023-08-06 20:49:27 -04:00
|
|
|
if type(st) is list and len(st) > 0:
|
|
|
|
all_stop_strings += st
|
|
|
|
|
|
|
|
shared.stop_everything = False
|
|
|
|
clear_torch_cache()
|
|
|
|
seed = set_manual_seed(state['seed'])
|
|
|
|
last_update = -1
|
|
|
|
reply = ''
|
|
|
|
is_stream = state['stream']
|
|
|
|
if len(all_stop_strings) > 0 and not state['stream']:
|
|
|
|
state = copy.deepcopy(state)
|
|
|
|
state['stream'] = True
|
|
|
|
|
2024-04-26 09:14:51 -04:00
|
|
|
min_update_interval = 0
|
|
|
|
if state.get('max_updates_second', 0) > 0:
|
|
|
|
min_update_interval = 1 / state['max_updates_second']
|
|
|
|
|
2023-08-06 20:49:27 -04:00
|
|
|
# Generate
|
|
|
|
for reply in generate_func(question, original_question, seed, state, stopping_strings, is_chat=is_chat):
|
2023-11-27 13:42:08 -05:00
|
|
|
reply, stop_found = apply_stopping_strings(reply, all_stop_strings)
|
2023-08-21 00:40:22 -04:00
|
|
|
if escape_html:
|
|
|
|
reply = html.escape(reply)
|
2024-03-26 15:32:20 -04:00
|
|
|
|
2023-08-06 20:49:27 -04:00
|
|
|
if is_stream:
|
|
|
|
cur_time = time.time()
|
2023-08-29 16:44:31 -04:00
|
|
|
|
2024-03-26 15:32:20 -04:00
|
|
|
# Limit number of tokens/second to make text readable in real time
|
2023-08-29 16:44:31 -04:00
|
|
|
if state['max_tokens_second'] > 0:
|
|
|
|
diff = 1 / state['max_tokens_second'] - (cur_time - last_update)
|
|
|
|
if diff > 0:
|
|
|
|
time.sleep(diff)
|
|
|
|
|
|
|
|
last_update = time.time()
|
2023-08-06 20:49:27 -04:00
|
|
|
yield reply
|
2024-04-26 09:14:51 -04:00
|
|
|
|
|
|
|
# Limit updates to avoid lag in the Gradio UI
|
|
|
|
# API updates are not limited
|
2023-08-29 16:44:31 -04:00
|
|
|
else:
|
2024-04-26 09:14:51 -04:00
|
|
|
if cur_time - last_update > min_update_interval:
|
|
|
|
last_update = cur_time
|
|
|
|
yield reply
|
|
|
|
|
2024-03-26 15:32:20 -04:00
|
|
|
yield reply
|
2023-08-29 16:44:31 -04:00
|
|
|
|
2023-09-18 13:27:06 -04:00
|
|
|
if stop_found or (state['max_tokens_second'] > 0 and shared.stop_everything):
|
2023-08-06 20:49:27 -04:00
|
|
|
break
|
|
|
|
|
|
|
|
if not is_chat:
|
|
|
|
reply = apply_extensions('output', reply, state)
|
|
|
|
|
|
|
|
yield reply
|
2023-02-23 10:05:25 -05:00
|
|
|
|
2023-04-06 23:15:45 -04:00
|
|
|
|
2023-04-11 17:46:06 -04:00
|
|
|
def encode(prompt, add_special_tokens=True, add_bos_token=True, truncation_length=None):
|
2023-09-17 10:01:34 -04:00
|
|
|
if shared.tokenizer is None:
|
|
|
|
raise ValueError('No tokenizer is loaded')
|
|
|
|
|
2024-04-04 19:23:58 -04:00
|
|
|
if shared.model.__class__.__name__ in ['LlamaCppModel', 'Exllamav2Model']:
|
2023-03-06 06:45:49 -05:00
|
|
|
input_ids = shared.tokenizer.encode(str(prompt))
|
2024-02-06 09:21:17 -05:00
|
|
|
if shared.model.__class__.__name__ not in ['Exllamav2Model']:
|
|
|
|
input_ids = np.array(input_ids).reshape(1, len(input_ids))
|
2023-02-23 10:05:25 -05:00
|
|
|
else:
|
2023-04-11 17:46:06 -04:00
|
|
|
input_ids = shared.tokenizer.encode(str(prompt), return_tensors='pt', add_special_tokens=add_special_tokens)
|
2023-12-12 15:23:14 -05:00
|
|
|
if not add_bos_token:
|
|
|
|
while len(input_ids[0]) > 0 and input_ids[0][0] == shared.tokenizer.bos_token_id:
|
|
|
|
input_ids = input_ids[:, 1:]
|
2023-04-10 15:44:22 -04:00
|
|
|
|
2023-04-11 17:46:06 -04:00
|
|
|
# Handling truncation
|
|
|
|
if truncation_length is not None:
|
|
|
|
input_ids = input_ids[:, -truncation_length:]
|
|
|
|
|
2024-04-04 19:23:58 -04:00
|
|
|
if shared.model.__class__.__name__ in ['LlamaCppModel', 'Exllamav2Model'] or shared.args.cpu:
|
2023-04-11 17:46:06 -04:00
|
|
|
return input_ids
|
|
|
|
elif shared.args.deepspeed:
|
2024-04-11 17:42:20 -04:00
|
|
|
import deepspeed
|
|
|
|
return input_ids.to(deepspeed.get_accelerator().current_device_name())
|
2023-07-17 20:27:18 -04:00
|
|
|
elif torch.backends.mps.is_available():
|
2023-04-11 17:46:06 -04:00
|
|
|
device = torch.device('mps')
|
|
|
|
return input_ids.to(device)
|
2023-10-26 22:39:51 -04:00
|
|
|
elif is_torch_xpu_available():
|
|
|
|
return input_ids.to("xpu:0")
|
2024-04-11 17:42:20 -04:00
|
|
|
elif is_torch_npu_available():
|
|
|
|
return input_ids.to("npu:0")
|
2023-04-11 17:46:06 -04:00
|
|
|
else:
|
|
|
|
return input_ids.cuda()
|
2023-02-23 10:05:25 -05:00
|
|
|
|
2023-04-06 23:15:45 -04:00
|
|
|
|
2023-08-06 20:49:27 -04:00
|
|
|
def decode(output_ids, skip_special_tokens=True):
|
2023-09-17 10:01:34 -04:00
|
|
|
if shared.tokenizer is None:
|
|
|
|
raise ValueError('No tokenizer is loaded')
|
|
|
|
|
2023-11-07 22:05:36 -05:00
|
|
|
return shared.tokenizer.decode(output_ids, skip_special_tokens=skip_special_tokens)
|
2023-08-06 20:49:27 -04:00
|
|
|
|
|
|
|
|
2023-05-09 19:18:02 -04:00
|
|
|
def get_encoded_length(prompt):
|
|
|
|
length_after_extensions = apply_extensions('tokenized_length', prompt)
|
|
|
|
if length_after_extensions is not None:
|
|
|
|
return length_after_extensions
|
|
|
|
|
|
|
|
return len(encode(prompt)[0])
|
|
|
|
|
|
|
|
|
2023-09-15 22:30:44 -04:00
|
|
|
def get_token_ids(prompt):
|
|
|
|
tokens = encode(prompt)[0]
|
2023-09-17 10:01:34 -04:00
|
|
|
decoded_tokens = [shared.tokenizer.decode([i]) for i in tokens]
|
2023-09-15 22:30:44 -04:00
|
|
|
|
|
|
|
output = ''
|
|
|
|
for row in list(zip(tokens, decoded_tokens)):
|
2023-09-17 10:01:34 -04:00
|
|
|
output += f"{str(int(row[0])).ljust(5)} - {repr(row[1])}\n"
|
2023-09-15 22:30:44 -04:00
|
|
|
|
|
|
|
return output
|
|
|
|
|
|
|
|
|
2023-08-06 20:49:27 -04:00
|
|
|
def get_max_prompt_length(state):
|
|
|
|
return state['truncation_length'] - state['max_new_tokens']
|
|
|
|
|
|
|
|
|
|
|
|
def generate_reply_wrapper(question, state, stopping_strings=None):
|
|
|
|
"""
|
|
|
|
Returns formatted outputs for the UI
|
|
|
|
"""
|
|
|
|
reply = question if not shared.is_seq2seq else ''
|
|
|
|
yield formatted_outputs(reply, shared.model_name)
|
|
|
|
|
2023-12-12 16:00:38 -05:00
|
|
|
for reply in generate_reply(question, state, stopping_strings, is_chat=False, escape_html=True, for_ui=True):
|
2023-08-06 20:49:27 -04:00
|
|
|
if not shared.is_seq2seq:
|
|
|
|
reply = question + reply
|
|
|
|
|
|
|
|
yield formatted_outputs(reply, shared.model_name)
|
|
|
|
|
|
|
|
|
|
|
|
def formatted_outputs(reply, model_name):
|
2024-04-04 19:10:47 -04:00
|
|
|
return html.unescape(reply), generate_basic_html(reply)
|
2023-02-23 10:05:25 -05:00
|
|
|
|
2023-04-11 10:46:30 -04:00
|
|
|
|
2023-03-22 14:40:20 -04:00
|
|
|
def set_manual_seed(seed):
|
2023-04-10 09:53:31 -04:00
|
|
|
seed = int(seed)
|
2023-04-10 09:29:10 -04:00
|
|
|
if seed == -1:
|
|
|
|
seed = random.randint(1, 2**31)
|
2023-04-24 18:24:12 -04:00
|
|
|
|
2023-04-10 09:29:10 -04:00
|
|
|
torch.manual_seed(seed)
|
|
|
|
if torch.cuda.is_available():
|
|
|
|
torch.cuda.manual_seed_all(seed)
|
2023-10-26 22:39:51 -04:00
|
|
|
elif is_torch_xpu_available():
|
|
|
|
torch.xpu.manual_seed_all(seed)
|
2024-04-11 17:42:20 -04:00
|
|
|
elif is_torch_npu_available():
|
|
|
|
torch.npu.manual_seed_all(seed)
|
2023-12-04 22:00:40 -05:00
|
|
|
|
2023-04-10 09:53:31 -04:00
|
|
|
return seed
|
2023-03-22 14:40:20 -04:00
|
|
|
|
2023-04-06 23:15:45 -04:00
|
|
|
|
2023-03-27 12:23:59 -04:00
|
|
|
def stop_everything_event():
|
|
|
|
shared.stop_everything = True
|
|
|
|
|
2023-04-06 23:15:45 -04:00
|
|
|
|
2023-06-24 08:43:00 -04:00
|
|
|
def apply_stopping_strings(reply, all_stop_strings):
|
|
|
|
stop_found = False
|
|
|
|
for string in all_stop_strings:
|
|
|
|
idx = reply.find(string)
|
|
|
|
if idx != -1:
|
|
|
|
reply = reply[:idx]
|
|
|
|
stop_found = True
|
|
|
|
break
|
|
|
|
|
|
|
|
if not stop_found:
|
|
|
|
# If something like "\nYo" is generated just before "\nYou:"
|
|
|
|
# is completed, trim it
|
|
|
|
for string in all_stop_strings:
|
|
|
|
for j in range(len(string) - 1, 0, -1):
|
|
|
|
if reply[-j:] == string[:j]:
|
|
|
|
reply = reply[:-j]
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
continue
|
|
|
|
|
|
|
|
break
|
|
|
|
|
|
|
|
return reply, stop_found
|
|
|
|
|
|
|
|
|
2024-01-22 06:07:42 -05:00
|
|
|
def get_reply_from_output_ids(output_ids, state=None, starting_from=0):
|
|
|
|
reply = decode(output_ids[starting_from:], state['skip_special_tokens'] if state else True)
|
2023-12-22 21:11:02 -05:00
|
|
|
|
|
|
|
# Handle tokenizers that do not add the leading space for the first token
|
|
|
|
if (hasattr(shared.tokenizer, 'convert_ids_to_tokens') and len(output_ids) > starting_from) and not reply.startswith(' '):
|
|
|
|
first_token = shared.tokenizer.convert_ids_to_tokens(int(output_ids[starting_from]))
|
|
|
|
if isinstance(first_token, (bytes,)):
|
|
|
|
first_token = first_token.decode('utf8')
|
|
|
|
|
|
|
|
if first_token.startswith('▁'):
|
|
|
|
reply = ' ' + reply
|
2023-12-04 22:00:40 -05:00
|
|
|
|
|
|
|
return reply
|
|
|
|
|
|
|
|
|
2023-06-24 08:43:00 -04:00
|
|
|
def generate_reply_HF(question, original_question, seed, state, stopping_strings=None, is_chat=False):
|
2023-05-05 17:53:03 -04:00
|
|
|
generate_params = {}
|
2024-05-19 22:53:47 -04:00
|
|
|
for k in ['max_new_tokens', 'temperature', 'temperature_last', 'dynamic_temperature', 'dynatemp_low', 'dynatemp_high', 'dynatemp_exponent', 'smoothing_factor', 'smoothing_curve', 'top_p', 'min_p', 'top_k', 'repetition_penalty', 'presence_penalty', 'frequency_penalty', 'repetition_penalty_range', 'typical_p', 'tfs', 'top_a', 'guidance_scale', 'penalty_alpha', 'mirostat_mode', 'mirostat_tau', 'mirostat_eta', 'do_sample', 'encoder_repetition_penalty', 'no_repeat_ngram_size', 'dry_multiplier', 'dry_base', 'dry_allowed_length', 'dry_sequence_breakers']:
|
2024-02-03 22:20:02 -05:00
|
|
|
if k in state:
|
|
|
|
generate_params[k] = state[k]
|
2023-05-05 17:53:03 -04:00
|
|
|
|
2024-02-06 10:05:32 -05:00
|
|
|
if isinstance(state['sampler_priority'], list) and len(state['sampler_priority']) > 0:
|
2024-02-06 09:20:10 -05:00
|
|
|
generate_params['sampler_priority'] = state['sampler_priority']
|
2024-02-06 10:05:32 -05:00
|
|
|
elif isinstance(state['sampler_priority'], str) and state['sampler_priority'].strip() != '':
|
2024-02-06 09:20:10 -05:00
|
|
|
generate_params['sampler_priority'] = [x.strip() for x in state['sampler_priority'].replace('\n', ',').split(',') if x.strip()]
|
|
|
|
|
2023-08-06 16:22:48 -04:00
|
|
|
if state['negative_prompt'] != '':
|
|
|
|
generate_params['negative_prompt_ids'] = encode(state['negative_prompt'])
|
|
|
|
|
2024-01-17 15:09:36 -05:00
|
|
|
if state['prompt_lookup_num_tokens'] > 0:
|
|
|
|
generate_params['prompt_lookup_num_tokens'] = state['prompt_lookup_num_tokens']
|
|
|
|
|
2023-05-21 14:11:57 -04:00
|
|
|
for k in ['epsilon_cutoff', 'eta_cutoff']:
|
|
|
|
if state[k] > 0:
|
|
|
|
generate_params[k] = state[k] * 1e-4
|
|
|
|
|
2023-05-05 17:53:03 -04:00
|
|
|
if state['ban_eos_token']:
|
|
|
|
generate_params['suppress_tokens'] = [shared.tokenizer.eos_token_id]
|
|
|
|
|
2023-09-15 17:27:27 -04:00
|
|
|
if state['custom_token_bans']:
|
|
|
|
to_ban = [int(x) for x in state['custom_token_bans'].split(',')]
|
|
|
|
if len(to_ban) > 0:
|
|
|
|
if generate_params.get('suppress_tokens', None):
|
|
|
|
generate_params['suppress_tokens'] += to_ban
|
|
|
|
else:
|
|
|
|
generate_params['suppress_tokens'] = to_ban
|
|
|
|
|
2023-08-30 16:26:27 -04:00
|
|
|
generate_params.update({'use_cache': not shared.args.no_cache})
|
2023-05-05 17:53:03 -04:00
|
|
|
if shared.args.deepspeed:
|
|
|
|
generate_params.update({'synced_gpus': True})
|
2023-02-27 21:03:35 -05:00
|
|
|
|
2023-04-24 18:24:12 -04:00
|
|
|
# Encode the input
|
2023-04-11 17:46:06 -04:00
|
|
|
input_ids = encode(question, add_bos_token=state['add_bos_token'], truncation_length=get_max_prompt_length(state))
|
2023-03-08 09:26:29 -05:00
|
|
|
output = input_ids[0]
|
2023-05-05 17:53:03 -04:00
|
|
|
cuda = not any((shared.args.cpu, shared.args.deepspeed))
|
2023-08-02 13:52:20 -04:00
|
|
|
if state['auto_max_new_tokens']:
|
|
|
|
generate_params['max_new_tokens'] = state['truncation_length'] - input_ids.shape[-1]
|
2023-04-11 17:46:06 -04:00
|
|
|
|
2023-04-24 18:24:12 -04:00
|
|
|
# Add the encoded tokens to generate_params
|
2023-06-06 06:42:23 -04:00
|
|
|
question, input_ids, inputs_embeds = apply_extensions('tokenizer', state, question, input_ids, None)
|
|
|
|
original_input_ids = input_ids
|
|
|
|
generate_params.update({'inputs': input_ids})
|
|
|
|
if inputs_embeds is not None:
|
2023-04-07 10:14:32 -04:00
|
|
|
generate_params.update({'inputs_embeds': inputs_embeds})
|
2023-03-05 08:12:43 -05:00
|
|
|
|
2023-06-24 10:19:16 -04:00
|
|
|
# Stopping criteria / eos token
|
2023-06-24 08:43:00 -04:00
|
|
|
eos_token_ids = [shared.tokenizer.eos_token_id] if shared.tokenizer.eos_token_id is not None else []
|
2023-05-05 17:53:03 -04:00
|
|
|
generate_params['eos_token_id'] = eos_token_ids
|
2023-06-24 08:43:00 -04:00
|
|
|
generate_params['stopping_criteria'] = transformers.StoppingCriteriaList()
|
2023-07-03 23:03:30 -04:00
|
|
|
generate_params['stopping_criteria'].append(_StopEverythingStoppingCriteria())
|
2023-05-02 22:12:22 -04:00
|
|
|
|
2023-12-17 00:01:23 -05:00
|
|
|
# Logits processor
|
2023-07-13 16:22:41 -04:00
|
|
|
processor = state.get('logits_processor', LogitsProcessorList([]))
|
2023-09-19 16:13:13 -04:00
|
|
|
if not isinstance(processor, LogitsProcessorList):
|
2023-07-13 16:22:41 -04:00
|
|
|
processor = LogitsProcessorList([processor])
|
2023-12-17 00:01:23 -05:00
|
|
|
|
|
|
|
# Grammar
|
|
|
|
if state['grammar_string'].strip() != '':
|
|
|
|
grammar = initialize_grammar(state['grammar_string'])
|
|
|
|
grammar_processor = GrammarConstrainedLogitsProcessor(grammar)
|
|
|
|
processor.append(grammar_processor)
|
|
|
|
|
2023-07-13 16:22:41 -04:00
|
|
|
apply_extensions('logits_processor', processor, input_ids)
|
|
|
|
generate_params['logits_processor'] = processor
|
|
|
|
|
2024-01-07 13:06:23 -05:00
|
|
|
if shared.args.verbose:
|
|
|
|
logger.info("GENERATE_PARAMS=")
|
2024-01-07 13:35:55 -05:00
|
|
|
filtered_params = {key: value for key, value in generate_params.items() if not isinstance(value, torch.Tensor)}
|
|
|
|
pprint.PrettyPrinter(indent=4, sort_dicts=False).pprint(filtered_params)
|
2024-01-07 13:06:23 -05:00
|
|
|
print()
|
|
|
|
|
2024-02-05 00:31:24 -05:00
|
|
|
logger.info("PROMPT=")
|
2024-05-18 12:57:00 -04:00
|
|
|
print_prompt(decode(input_ids[0], skip_special_tokens=False))
|
2024-02-05 00:31:24 -05:00
|
|
|
|
2024-03-08 22:25:33 -05:00
|
|
|
# Handle StreamingLLM for llamacpp_HF
|
|
|
|
if shared.model.__class__.__name__ == 'LlamacppHF' and shared.args.streaming_llm:
|
2024-03-09 00:39:02 -05:00
|
|
|
tmp = process_llamacpp_cache(shared.model.model, input_ids[-1].tolist(), shared.model.model._input_ids.tolist())
|
2024-03-08 22:25:33 -05:00
|
|
|
shared.model.past_seq = torch.tensor(tmp)
|
|
|
|
shared.model.save_cache()
|
|
|
|
|
2023-05-05 17:53:03 -04:00
|
|
|
t0 = time.time()
|
2023-03-12 00:31:45 -05:00
|
|
|
try:
|
2023-06-16 18:00:37 -04:00
|
|
|
if not is_chat and not shared.is_seq2seq:
|
2023-05-11 16:07:20 -04:00
|
|
|
yield ''
|
2023-05-05 17:53:03 -04:00
|
|
|
|
2023-03-12 00:31:45 -05:00
|
|
|
# Generate the entire reply at once.
|
2023-05-05 17:53:03 -04:00
|
|
|
if not state['stream']:
|
2023-02-23 10:05:25 -05:00
|
|
|
with torch.no_grad():
|
2023-03-14 15:04:17 -04:00
|
|
|
output = shared.model.generate(**generate_params)[0]
|
|
|
|
if cuda:
|
|
|
|
output = output.cuda()
|
2023-04-16 13:24:49 -04:00
|
|
|
|
2023-12-05 13:05:54 -05:00
|
|
|
starting_from = 0 if shared.is_seq2seq else len(input_ids[0])
|
|
|
|
yield get_reply_from_output_ids(output, state, starting_from=starting_from)
|
2023-03-08 00:46:35 -05:00
|
|
|
|
2023-03-12 00:31:45 -05:00
|
|
|
# Stream the reply 1 token at a time.
|
|
|
|
# This is based on the trick of using 'stopping_criteria' to create an iterator.
|
2023-05-05 17:53:03 -04:00
|
|
|
else:
|
2023-03-12 00:31:45 -05:00
|
|
|
|
2023-06-16 20:44:56 -04:00
|
|
|
def generate_with_callback(callback=None, *args, **kwargs):
|
2023-03-12 00:31:45 -05:00
|
|
|
kwargs['stopping_criteria'].append(Stream(callback_func=callback))
|
|
|
|
clear_torch_cache()
|
|
|
|
with torch.no_grad():
|
|
|
|
shared.model.generate(**kwargs)
|
|
|
|
|
|
|
|
def generate_with_streaming(**kwargs):
|
2023-06-16 20:44:56 -04:00
|
|
|
return Iteratorize(generate_with_callback, [], kwargs, callback=None)
|
2023-03-12 00:31:45 -05:00
|
|
|
|
2023-03-14 15:04:17 -04:00
|
|
|
with generate_with_streaming(**generate_params) as generator:
|
2023-12-04 22:00:40 -05:00
|
|
|
cumulative_reply = ''
|
2023-12-05 13:05:54 -05:00
|
|
|
starting_from = 0 if shared.is_seq2seq else len(input_ids[0])
|
2023-03-12 00:31:45 -05:00
|
|
|
for output in generator:
|
2023-03-12 13:54:58 -04:00
|
|
|
if output[-1] in eos_token_ids:
|
2023-03-12 00:31:45 -05:00
|
|
|
break
|
2023-04-16 13:24:49 -04:00
|
|
|
|
2023-12-08 07:50:53 -05:00
|
|
|
new_content = get_reply_from_output_ids(output, state, starting_from=starting_from)
|
|
|
|
# check the partial unicode character
|
|
|
|
if chr(0xfffd) in new_content:
|
|
|
|
continue
|
|
|
|
|
|
|
|
cumulative_reply += new_content
|
2023-12-04 22:00:40 -05:00
|
|
|
starting_from = len(output)
|
|
|
|
yield cumulative_reply
|
2023-10-07 18:46:42 -04:00
|
|
|
|
2023-05-05 17:53:03 -04:00
|
|
|
except Exception:
|
|
|
|
traceback.print_exc()
|
|
|
|
finally:
|
|
|
|
t1 = time.time()
|
|
|
|
original_tokens = len(original_input_ids[0])
|
2023-06-16 18:00:37 -04:00
|
|
|
new_tokens = len(output) - (original_tokens if not shared.is_seq2seq else 0)
|
2023-05-05 17:53:03 -04:00
|
|
|
print(f'Output generated in {(t1-t0):.2f} seconds ({new_tokens/(t1-t0):.2f} tokens/s, {new_tokens} tokens, context {original_tokens}, seed {seed})')
|
|
|
|
return
|
|
|
|
|
|
|
|
|
2023-06-24 08:43:00 -04:00
|
|
|
def generate_reply_custom(question, original_question, seed, state, stopping_strings=None, is_chat=False):
|
2023-08-06 20:49:27 -04:00
|
|
|
"""
|
|
|
|
For models that do not use the transformers library for sampling
|
|
|
|
"""
|
2023-05-05 17:53:03 -04:00
|
|
|
seed = set_manual_seed(state['seed'])
|
2023-05-22 18:37:24 -04:00
|
|
|
|
2023-05-05 17:53:03 -04:00
|
|
|
t0 = time.time()
|
2023-05-19 13:46:18 -04:00
|
|
|
reply = ''
|
2023-05-05 17:53:03 -04:00
|
|
|
try:
|
2023-05-11 14:37:04 -04:00
|
|
|
if not is_chat:
|
2023-05-11 16:07:20 -04:00
|
|
|
yield ''
|
2023-05-05 17:53:03 -04:00
|
|
|
|
|
|
|
if not state['stream']:
|
2023-06-16 19:35:38 -04:00
|
|
|
reply = shared.model.generate(question, state)
|
2023-05-05 17:53:03 -04:00
|
|
|
yield reply
|
|
|
|
else:
|
2023-06-16 19:35:38 -04:00
|
|
|
for reply in shared.model.generate_with_streaming(question, state):
|
2023-05-05 17:53:03 -04:00
|
|
|
yield reply
|
|
|
|
|
|
|
|
except Exception:
|
|
|
|
traceback.print_exc()
|
|
|
|
finally:
|
|
|
|
t1 = time.time()
|
|
|
|
original_tokens = len(encode(original_question)[0])
|
2023-05-11 16:07:20 -04:00
|
|
|
new_tokens = len(encode(original_question + reply)[0]) - original_tokens
|
2023-05-05 17:53:03 -04:00
|
|
|
print(f'Output generated in {(t1-t0):.2f} seconds ({new_tokens/(t1-t0):.2f} tokens/s, {new_tokens} tokens, context {original_tokens}, seed {seed})')
|
|
|
|
return
|
2024-05-18 12:57:00 -04:00
|
|
|
|
|
|
|
|
|
|
|
def print_prompt(prompt, max_chars=2000):
|
|
|
|
DARK_YELLOW = "\033[38;5;3m"
|
|
|
|
RESET = "\033[0m"
|
|
|
|
|
|
|
|
if len(prompt) > max_chars:
|
|
|
|
half_chars = max_chars // 2
|
|
|
|
hidden_len = len(prompt[half_chars:-half_chars])
|
|
|
|
hidden_msg = f"{DARK_YELLOW}[...{hidden_len} characters hidden...]{RESET}"
|
|
|
|
print(prompt[:half_chars] + hidden_msg + prompt[-half_chars:])
|
|
|
|
else:
|
|
|
|
print(prompt)
|
|
|
|
|
|
|
|
print()
|