2023-09-28 22:19:47 -04:00
|
|
|
import json
|
2023-06-16 18:00:37 -04:00
|
|
|
import re
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
import yaml
|
|
|
|
|
2023-12-12 15:23:14 -05:00
|
|
|
from modules import chat, loaders, metadata_gguf, shared, ui
|
2023-06-16 18:00:37 -04:00
|
|
|
|
|
|
|
|
2023-09-11 17:49:30 -04:00
|
|
|
def get_fallback_settings():
|
|
|
|
return {
|
|
|
|
'wbits': 'None',
|
|
|
|
'groupsize': 'None',
|
2023-09-29 09:14:16 -04:00
|
|
|
'desc_act': False,
|
|
|
|
'model_type': 'None',
|
2023-09-28 22:19:47 -04:00
|
|
|
'max_seq_len': 2048,
|
2023-09-11 17:49:30 -04:00
|
|
|
'n_ctx': 2048,
|
|
|
|
'rope_freq_base': 0,
|
2023-09-12 16:02:42 -04:00
|
|
|
'compress_pos_emb': 1,
|
2023-09-29 09:14:16 -04:00
|
|
|
'truncation_length': shared.settings['truncation_length'],
|
|
|
|
'skip_special_tokens': shared.settings['skip_special_tokens'],
|
|
|
|
'custom_stopping_strings': shared.settings['custom_stopping_strings'],
|
2023-09-11 17:49:30 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
def get_model_metadata(model):
|
2023-06-16 18:00:37 -04:00
|
|
|
model_settings = {}
|
2023-09-11 17:49:30 -04:00
|
|
|
|
|
|
|
# Get settings from models/config.yaml and models/config-user.yaml
|
|
|
|
settings = shared.model_config
|
2023-06-16 18:00:37 -04:00
|
|
|
for pat in settings:
|
|
|
|
if re.match(pat.lower(), model.lower()):
|
|
|
|
for k in settings[pat]:
|
|
|
|
model_settings[k] = settings[pat][k]
|
|
|
|
|
2023-12-05 22:01:01 -05:00
|
|
|
path = Path(f'{shared.args.model_dir}/{model}/config.json')
|
|
|
|
if path.exists():
|
2023-12-30 23:34:32 -05:00
|
|
|
hf_metadata = json.loads(open(path, 'r', encoding='utf-8').read())
|
2023-12-05 22:01:01 -05:00
|
|
|
else:
|
|
|
|
hf_metadata = None
|
|
|
|
|
2023-09-11 17:49:30 -04:00
|
|
|
if 'loader' not in model_settings:
|
2023-12-05 22:01:01 -05:00
|
|
|
if hf_metadata is not None and 'quip_params' in hf_metadata:
|
2023-12-30 23:57:06 -05:00
|
|
|
loader = 'QuIP#'
|
2023-12-05 22:01:01 -05:00
|
|
|
else:
|
|
|
|
loader = infer_loader(model, model_settings)
|
2023-09-11 17:49:30 -04:00
|
|
|
|
2023-12-30 23:57:06 -05:00
|
|
|
model_settings['loader'] = loader
|
2023-09-11 17:49:30 -04:00
|
|
|
|
2023-12-05 22:01:01 -05:00
|
|
|
# GGUF metadata
|
2024-04-04 19:23:58 -04:00
|
|
|
if model_settings['loader'] in ['llama.cpp', 'llamacpp_HF']:
|
2023-09-11 17:49:30 -04:00
|
|
|
path = Path(f'{shared.args.model_dir}/{model}')
|
|
|
|
if path.is_file():
|
|
|
|
model_file = path
|
|
|
|
else:
|
|
|
|
model_file = list(path.glob('*.gguf'))[0]
|
|
|
|
|
|
|
|
metadata = metadata_gguf.load_metadata(model_file)
|
2024-05-19 13:57:42 -04:00
|
|
|
|
2024-04-11 00:36:32 -04:00
|
|
|
for k in metadata:
|
|
|
|
if k.endswith('context_length'):
|
|
|
|
model_settings['n_ctx'] = metadata[k]
|
|
|
|
elif k.endswith('rope.freq_base'):
|
|
|
|
model_settings['rope_freq_base'] = metadata[k]
|
|
|
|
elif k.endswith('rope.scale_linear'):
|
|
|
|
model_settings['compress_pos_emb'] = metadata[k]
|
2024-05-19 13:57:42 -04:00
|
|
|
elif k.endswith('block_count'):
|
|
|
|
model_settings['n_gpu_layers'] = metadata[k] + 1
|
|
|
|
|
2023-12-17 23:51:58 -05:00
|
|
|
if 'tokenizer.chat_template' in metadata:
|
|
|
|
template = metadata['tokenizer.chat_template']
|
|
|
|
eos_token = metadata['tokenizer.ggml.tokens'][metadata['tokenizer.ggml.eos_token_id']]
|
|
|
|
bos_token = metadata['tokenizer.ggml.tokens'][metadata['tokenizer.ggml.bos_token_id']]
|
|
|
|
template = template.replace('eos_token', "'{}'".format(eos_token))
|
|
|
|
template = template.replace('bos_token', "'{}'".format(bos_token))
|
|
|
|
|
|
|
|
template = re.sub(r'raise_exception\([^)]*\)', "''", template)
|
2024-04-24 04:34:11 -04:00
|
|
|
template = re.sub(r'{% if add_generation_prompt %}.*', '', template, flags=re.DOTALL)
|
2023-12-17 23:51:58 -05:00
|
|
|
model_settings['instruction_template'] = 'Custom (obtained from model metadata)'
|
|
|
|
model_settings['instruction_template_str'] = template
|
2023-09-14 15:15:52 -04:00
|
|
|
|
2023-09-28 22:19:47 -04:00
|
|
|
else:
|
2023-12-05 22:01:01 -05:00
|
|
|
# Transformers metadata
|
|
|
|
if hf_metadata is not None:
|
2023-12-30 23:34:32 -05:00
|
|
|
metadata = json.loads(open(path, 'r', encoding='utf-8').read())
|
2024-04-11 00:36:32 -04:00
|
|
|
for k in ['max_position_embeddings', 'model_max_length', 'max_seq_len']:
|
2024-03-31 00:33:16 -04:00
|
|
|
if k in metadata:
|
|
|
|
model_settings['truncation_length'] = metadata[k]
|
|
|
|
model_settings['max_seq_len'] = metadata[k]
|
2023-09-28 22:19:47 -04:00
|
|
|
|
2023-09-29 09:14:16 -04:00
|
|
|
if 'rope_theta' in metadata:
|
|
|
|
model_settings['rope_freq_base'] = metadata['rope_theta']
|
2024-04-01 23:25:31 -04:00
|
|
|
elif 'attn_config' in metadata and 'rope_theta' in metadata['attn_config']:
|
|
|
|
model_settings['rope_freq_base'] = metadata['attn_config']['rope_theta']
|
2023-09-29 09:14:16 -04:00
|
|
|
|
|
|
|
if 'rope_scaling' in metadata and type(metadata['rope_scaling']) is dict and all(key in metadata['rope_scaling'] for key in ('type', 'factor')):
|
|
|
|
if metadata['rope_scaling']['type'] == 'linear':
|
|
|
|
model_settings['compress_pos_emb'] = metadata['rope_scaling']['factor']
|
|
|
|
|
2024-03-31 00:51:39 -04:00
|
|
|
# Read GPTQ metadata for old GPTQ loaders
|
|
|
|
if 'quantization_config' in metadata and metadata['quantization_config'].get('quant_method', '') != 'exl2':
|
2023-09-29 09:14:16 -04:00
|
|
|
if 'bits' in metadata['quantization_config']:
|
|
|
|
model_settings['wbits'] = metadata['quantization_config']['bits']
|
|
|
|
if 'group_size' in metadata['quantization_config']:
|
|
|
|
model_settings['groupsize'] = metadata['quantization_config']['group_size']
|
|
|
|
if 'desc_act' in metadata['quantization_config']:
|
|
|
|
model_settings['desc_act'] = metadata['quantization_config']['desc_act']
|
|
|
|
|
|
|
|
# Read AutoGPTQ metadata
|
|
|
|
path = Path(f'{shared.args.model_dir}/{model}/quantize_config.json')
|
|
|
|
if path.exists():
|
2023-12-30 23:34:32 -05:00
|
|
|
metadata = json.loads(open(path, 'r', encoding='utf-8').read())
|
2023-09-29 09:14:16 -04:00
|
|
|
if 'bits' in metadata:
|
|
|
|
model_settings['wbits'] = metadata['bits']
|
|
|
|
if 'group_size' in metadata:
|
|
|
|
model_settings['groupsize'] = metadata['group_size']
|
|
|
|
if 'desc_act' in metadata:
|
|
|
|
model_settings['desc_act'] = metadata['desc_act']
|
|
|
|
|
2023-12-12 15:23:14 -05:00
|
|
|
# Try to find the Jinja instruct template
|
|
|
|
path = Path(f'{shared.args.model_dir}/{model}') / 'tokenizer_config.json'
|
|
|
|
if path.exists():
|
2023-12-30 23:34:32 -05:00
|
|
|
metadata = json.loads(open(path, 'r', encoding='utf-8').read())
|
2023-12-12 15:23:14 -05:00
|
|
|
if 'chat_template' in metadata:
|
|
|
|
template = metadata['chat_template']
|
2024-04-06 10:32:17 -04:00
|
|
|
if isinstance(template, list):
|
|
|
|
template = template[0]['template']
|
|
|
|
|
2023-12-12 15:23:14 -05:00
|
|
|
for k in ['eos_token', 'bos_token']:
|
|
|
|
if k in metadata:
|
|
|
|
value = metadata[k]
|
|
|
|
if type(value) is dict:
|
|
|
|
value = value['content']
|
|
|
|
|
|
|
|
template = template.replace(k, "'{}'".format(value))
|
|
|
|
|
|
|
|
template = re.sub(r'raise_exception\([^)]*\)', "''", template)
|
2024-04-24 04:34:11 -04:00
|
|
|
template = re.sub(r'{% if add_generation_prompt %}.*', '', template, flags=re.DOTALL)
|
2023-12-12 15:23:14 -05:00
|
|
|
model_settings['instruction_template'] = 'Custom (obtained from model metadata)'
|
|
|
|
model_settings['instruction_template_str'] = template
|
|
|
|
|
|
|
|
if 'instruction_template' not in model_settings:
|
|
|
|
model_settings['instruction_template'] = 'Alpaca'
|
|
|
|
|
2023-10-10 16:57:40 -04:00
|
|
|
# Ignore rope_freq_base if set to the default value
|
2023-10-10 17:08:11 -04:00
|
|
|
if 'rope_freq_base' in model_settings and model_settings['rope_freq_base'] == 10000:
|
2023-10-10 16:57:40 -04:00
|
|
|
model_settings.pop('rope_freq_base')
|
|
|
|
|
2023-09-14 15:15:52 -04:00
|
|
|
# Apply user settings from models/config-user.yaml
|
|
|
|
settings = shared.user_config
|
|
|
|
for pat in settings:
|
|
|
|
if re.match(pat.lower(), model.lower()):
|
|
|
|
for k in settings[pat]:
|
|
|
|
model_settings[k] = settings[pat][k]
|
2023-09-11 17:49:30 -04:00
|
|
|
|
2024-04-18 23:24:46 -04:00
|
|
|
# Load instruction template if defined by name rather than by value
|
|
|
|
if model_settings['instruction_template'] != 'Custom (obtained from model metadata)':
|
|
|
|
model_settings['instruction_template_str'] = chat.load_instruction_template(model_settings['instruction_template'])
|
|
|
|
|
2023-06-16 18:00:37 -04:00
|
|
|
return model_settings
|
|
|
|
|
|
|
|
|
2023-09-11 17:49:30 -04:00
|
|
|
def infer_loader(model_name, model_settings):
|
2023-06-16 18:00:37 -04:00
|
|
|
path_to_model = Path(f'{shared.args.model_dir}/{model_name}')
|
|
|
|
if not path_to_model.exists():
|
|
|
|
loader = None
|
2023-09-28 22:32:35 -04:00
|
|
|
elif (path_to_model / 'quantize_config.json').exists() or ('wbits' in model_settings and type(model_settings['wbits']) is int and model_settings['wbits'] > 0):
|
2023-12-30 23:57:06 -05:00
|
|
|
loader = 'ExLlamav2_HF'
|
2023-10-05 12:22:37 -04:00
|
|
|
elif (path_to_model / 'quant_config.json').exists() or re.match(r'.*-awq', model_name.lower()):
|
2023-10-05 12:19:18 -04:00
|
|
|
loader = 'AutoAWQ'
|
2024-02-16 12:29:26 -05:00
|
|
|
elif len(list(path_to_model.glob('*.gguf'))) > 0 and path_to_model.is_dir() and (path_to_model / 'tokenizer_config.json').exists():
|
|
|
|
loader = 'llamacpp_HF'
|
2023-09-11 10:30:56 -04:00
|
|
|
elif len(list(path_to_model.glob('*.gguf'))) > 0:
|
2023-06-16 18:00:37 -04:00
|
|
|
loader = 'llama.cpp'
|
2023-09-11 10:30:56 -04:00
|
|
|
elif re.match(r'.*\.gguf', model_name.lower()):
|
2023-06-16 18:00:37 -04:00
|
|
|
loader = 'llama.cpp'
|
2023-09-23 16:04:27 -04:00
|
|
|
elif re.match(r'.*exl2', model_name.lower()):
|
|
|
|
loader = 'ExLlamav2_HF'
|
2023-12-18 19:23:16 -05:00
|
|
|
elif re.match(r'.*-hqq', model_name.lower()):
|
|
|
|
return 'HQQ'
|
2023-06-16 18:00:37 -04:00
|
|
|
else:
|
|
|
|
loader = 'Transformers'
|
|
|
|
|
|
|
|
return loader
|
|
|
|
|
|
|
|
|
|
|
|
def update_model_parameters(state, initial=False):
|
2023-11-15 18:51:37 -05:00
|
|
|
'''
|
|
|
|
UI: update the command-line arguments based on the interface values
|
|
|
|
'''
|
2023-06-16 18:00:37 -04:00
|
|
|
elements = ui.list_model_elements() # the names of the parameters
|
|
|
|
gpu_memories = []
|
|
|
|
|
|
|
|
for i, element in enumerate(elements):
|
|
|
|
if element not in state:
|
|
|
|
continue
|
|
|
|
|
|
|
|
value = state[element]
|
|
|
|
if element.startswith('gpu_memory'):
|
|
|
|
gpu_memories.append(value)
|
|
|
|
continue
|
|
|
|
|
2023-09-19 16:11:46 -04:00
|
|
|
if initial and element in shared.provided_arguments:
|
2023-06-16 18:00:37 -04:00
|
|
|
continue
|
|
|
|
|
|
|
|
# Setting null defaults
|
|
|
|
if element in ['wbits', 'groupsize', 'model_type'] and value == 'None':
|
|
|
|
value = vars(shared.args_defaults)[element]
|
|
|
|
elif element in ['cpu_memory'] and value == 0:
|
|
|
|
value = vars(shared.args_defaults)[element]
|
|
|
|
|
|
|
|
# Making some simple conversions
|
|
|
|
if element in ['wbits', 'groupsize', 'pre_layer']:
|
|
|
|
value = int(value)
|
|
|
|
elif element == 'cpu_memory' and value is not None:
|
|
|
|
value = f"{value}MiB"
|
|
|
|
|
|
|
|
if element in ['pre_layer']:
|
|
|
|
value = [value] if value > 0 else None
|
|
|
|
|
|
|
|
setattr(shared.args, element, value)
|
|
|
|
|
|
|
|
found_positive = False
|
|
|
|
for i in gpu_memories:
|
|
|
|
if i > 0:
|
|
|
|
found_positive = True
|
|
|
|
break
|
|
|
|
|
|
|
|
if not (initial and vars(shared.args)['gpu_memory'] != vars(shared.args_defaults)['gpu_memory']):
|
|
|
|
if found_positive:
|
|
|
|
shared.args.gpu_memory = [f"{i}MiB" for i in gpu_memories]
|
|
|
|
else:
|
|
|
|
shared.args.gpu_memory = None
|
|
|
|
|
|
|
|
|
|
|
|
def apply_model_settings_to_state(model, state):
|
2023-11-15 18:51:37 -05:00
|
|
|
'''
|
|
|
|
UI: update the state variable with the model settings
|
|
|
|
'''
|
2023-09-11 17:49:30 -04:00
|
|
|
model_settings = get_model_metadata(model)
|
|
|
|
if 'loader' in model_settings:
|
|
|
|
loader = model_settings.pop('loader')
|
2023-06-16 18:00:37 -04:00
|
|
|
|
2023-08-24 15:27:36 -04:00
|
|
|
# If the user is using an alternative loader for the same model type, let them keep using it
|
2024-04-04 19:23:58 -04:00
|
|
|
if not (loader == 'ExLlamav2_HF' and state['loader'] in ['GPTQ-for-LLaMa', 'ExLlamav2', 'AutoGPTQ']):
|
2023-06-16 18:00:37 -04:00
|
|
|
state['loader'] = loader
|
|
|
|
|
|
|
|
for k in model_settings:
|
|
|
|
if k in state:
|
2023-07-11 22:27:38 -04:00
|
|
|
if k in ['wbits', 'groupsize']:
|
|
|
|
state[k] = str(model_settings[k])
|
|
|
|
else:
|
|
|
|
state[k] = model_settings[k]
|
2023-06-16 18:00:37 -04:00
|
|
|
|
|
|
|
return state
|
|
|
|
|
|
|
|
|
|
|
|
def save_model_settings(model, state):
|
2023-11-15 18:51:37 -05:00
|
|
|
'''
|
|
|
|
Save the settings for this model to models/config-user.yaml
|
|
|
|
'''
|
2023-06-16 18:00:37 -04:00
|
|
|
if model == 'None':
|
2024-02-16 12:21:17 -05:00
|
|
|
yield ("Not saving the settings because no model is selected in the menu.")
|
2023-06-16 18:00:37 -04:00
|
|
|
return
|
|
|
|
|
2024-02-16 12:21:17 -05:00
|
|
|
user_config = shared.load_user_config()
|
|
|
|
model_regex = model + '$' # For exact matches
|
|
|
|
if model_regex not in user_config:
|
|
|
|
user_config[model_regex] = {}
|
|
|
|
|
|
|
|
for k in ui.list_model_elements():
|
|
|
|
if k == 'loader' or k in loaders.loaders_and_params[state['loader']]:
|
|
|
|
user_config[model_regex][k] = state[k]
|
2023-06-16 18:00:37 -04:00
|
|
|
|
2024-02-16 12:21:17 -05:00
|
|
|
shared.user_config = user_config
|
2023-06-16 18:00:37 -04:00
|
|
|
|
2024-02-16 12:21:17 -05:00
|
|
|
output = yaml.dump(user_config, sort_keys=False)
|
|
|
|
p = Path(f'{shared.args.model_dir}/config-user.yaml')
|
|
|
|
with open(p, 'w') as f:
|
|
|
|
f.write(output)
|
2023-09-14 15:15:52 -04:00
|
|
|
|
2024-02-16 12:21:17 -05:00
|
|
|
yield (f"Settings for `{model}` saved to `{p}`.")
|
2023-06-16 18:00:37 -04:00
|
|
|
|
|
|
|
|
2024-02-16 12:21:17 -05:00
|
|
|
def save_instruction_template(model, template):
|
|
|
|
'''
|
|
|
|
Similar to the function above, but it saves only the instruction template.
|
|
|
|
'''
|
|
|
|
if model == 'None':
|
|
|
|
yield ("Not saving the template because no model is selected in the menu.")
|
|
|
|
return
|
|
|
|
|
|
|
|
user_config = shared.load_user_config()
|
|
|
|
model_regex = model + '$' # For exact matches
|
|
|
|
if model_regex not in user_config:
|
|
|
|
user_config[model_regex] = {}
|
|
|
|
|
|
|
|
if template == 'None':
|
|
|
|
user_config[model_regex].pop('instruction_template', None)
|
|
|
|
else:
|
|
|
|
user_config[model_regex]['instruction_template'] = template
|
|
|
|
|
|
|
|
shared.user_config = user_config
|
|
|
|
|
|
|
|
output = yaml.dump(user_config, sort_keys=False)
|
|
|
|
p = Path(f'{shared.args.model_dir}/config-user.yaml')
|
|
|
|
with open(p, 'w') as f:
|
|
|
|
f.write(output)
|
|
|
|
|
|
|
|
if template == 'None':
|
|
|
|
yield (f"Instruction template for `{model}` unset in `{p}`, as the value for template was `{template}`.")
|
|
|
|
else:
|
|
|
|
yield (f"Instruction template for `{model}` saved to `{p}` as `{template}`.")
|