CoolFace
Apppublic

forestcalled/text-generation-webui

sourceHugging Faceupdated 3y agoView on Hugging Face
0likes
GPTQ_loader.py172 linesDownload Raw Back to modules
1import inspect2import re3from pathlib import Path4 5import accelerate6import torch7import transformers8from accelerate.utils import is_xpu_available9from gptq_for_llama import llama_inference_offload10from gptq_for_llama.modelutils import find_layers11from gptq_for_llama.quant import make_quant12from transformers import AutoConfig, AutoModelForCausalLM13 14import modules.shared as shared15from modules.logging_colors import logger16 17 18# This function is a replacement for the load_quant function in the19# GPTQ-for_LLaMa repository. It supports more models and branches.20def _load_quant(model, checkpoint, wbits, groupsize=-1, faster_kernel=False, exclude_layers=None, kernel_switch_threshold=128, eval=True):21    exclude_layers = exclude_layers or ['lm_head']22 23    def noop(*args, **kwargs):24        pass25 26    config = AutoConfig.from_pretrained(model, trust_remote_code=shared.args.trust_remote_code)27    torch.nn.init.kaiming_uniform_ = noop28    torch.nn.init.uniform_ = noop29    torch.nn.init.normal_ = noop30 31    torch.set_default_dtype(torch.half)32    transformers.modeling_utils._init_weights = False33    torch.set_default_dtype(torch.half)34    model = AutoModelForCausalLM.from_config(config, trust_remote_code=shared.args.trust_remote_code)35    torch.set_default_dtype(torch.float)36    if eval:37        model = model.eval()38 39    layers = find_layers(model)40    for name in exclude_layers:41        if name in layers:42            del layers[name]43 44    gptq_args = inspect.getfullargspec(make_quant).args45 46    make_quant_kwargs = {47        'module': model,48        'names': layers,49        'bits': wbits,50    }51    if 'groupsize' in gptq_args:52        make_quant_kwargs['groupsize'] = groupsize53    if 'faster' in gptq_args:54        make_quant_kwargs['faster'] = faster_kernel55    if 'kernel_switch_threshold' in gptq_args:56        make_quant_kwargs['kernel_switch_threshold'] = kernel_switch_threshold57 58    make_quant(**make_quant_kwargs)59 60    del layers61    if checkpoint.endswith('.safetensors'):62        from safetensors.torch import load_file as safe_load63        model.load_state_dict(safe_load(checkpoint), strict=False)64    else:65        model.load_state_dict(torch.load(checkpoint, weights_only=True), strict=False)66 67    model.seqlen = 204868    return model69 70 71# Used to locate the .pt/.safetensors quantized file72def find_quantized_model_file(model_name):73    if shared.args.checkpoint:74        return Path(shared.args.checkpoint)75 76    path_to_model = Path(f'{shared.args.model_dir}/{model_name}')77    pt_path = None78    priority_name_list = [79        Path(f'{shared.args.model_dir}/{model_name}{hyphen}{shared.args.wbits}bit{group}{ext}')80        for group in ([f'-{shared.args.groupsize}g', ''] if shared.args.groupsize > 0 else [''])81        for ext in ['.safetensors', '.pt']82        for hyphen in ['-', f'/{model_name}-', '/']83    ]84 85    for path in priority_name_list:86        if path.exists():87            pt_path = path88            break89 90    # If the model hasn't been found with a well-behaved name, pick the last .pt91    # or the last .safetensors found in its folder as a last resort92    if not pt_path:93        for ext in ['.pt', '.safetensors']:94            found = list(path_to_model.glob(f"*{ext}"))95            if len(found) > 0:96                if len(found) > 1:97                    logger.warning(f'More than one {ext} model has been found. The last one will be selected. It could be wrong.')98 99                pt_path = found[-1]100                break101 102    return pt_path103 104 105# The function that loads the model in modules/models.py106def load_quantized(model_name):107    if shared.args.model_type is None:108        logger.error("The model could not be loaded because its type could not be inferred from its name.")109        logger.error("Please specify the type manually using the --model_type argument.")110        return None111 112    # Select the appropriate load_quant function113    model_type = shared.args.model_type.lower()114    if shared.args.pre_layer and model_type == 'llama':115        load_quant = llama_inference_offload.load_quant116    elif model_type in ('llama', 'opt', 'gptj'):117        if shared.args.pre_layer:118            logger.warning("Ignoring --pre_layer because it only works for llama model type.")119 120        load_quant = _load_quant121    else:122        logger.error("Unknown pre-quantized model type specified. Only 'llama', 'opt' and 'gptj' are supported")123        exit()124 125    # Find the quantized model weights file (.pt/.safetensors)126    path_to_model = Path(f'{shared.args.model_dir}/{model_name}')127    pt_path = find_quantized_model_file(model_name)128    if not pt_path:129        logger.error("Could not find the quantized model in .pt or .safetensors format. Exiting.")130        exit()131    else:132        logger.info(f"Found the following quantized model: {pt_path}")133 134    # qwopqwop200's offload135    if model_type == 'llama' and shared.args.pre_layer:136        if len(shared.args.pre_layer) == 1:137            pre_layer = shared.args.pre_layer[0]138        else:139            pre_layer = shared.args.pre_layer140 141        model = load_quant(str(path_to_model), str(pt_path), shared.args.wbits, shared.args.groupsize, pre_layer)142    else:143        threshold = False if model_type == 'gptj' else 128144        model = load_quant(str(path_to_model), str(pt_path), shared.args.wbits, shared.args.groupsize, kernel_switch_threshold=threshold)145 146        # accelerate offload (doesn't work properly)147        if shared.args.gpu_memory or torch.cuda.device_count() > 1 or (is_xpu_available() and torch.xpu.device_count() > 1):148            if shared.args.gpu_memory:149                memory_map = list(map(lambda x: x.strip(), shared.args.gpu_memory))150                max_cpu_memory = shared.args.cpu_memory.strip() if shared.args.cpu_memory is not None else '99GiB'151                max_memory = {}152                for i in range(len(memory_map)):153                    max_memory[i] = f'{memory_map[i]}GiB' if not re.match('.*ib$', memory_map[i].lower()) else memory_map[i]154 155                max_memory['cpu'] = f'{max_cpu_memory}GiB' if not re.match('.*ib$', max_cpu_memory.lower()) else max_cpu_memory156            else:157                max_memory = accelerate.utils.get_balanced_memory(model)158 159            device_map = accelerate.infer_auto_device_map(model, max_memory=max_memory, no_split_module_classes=["LlamaDecoderLayer"])160            logger.info("Using the following device map for the quantized model:", device_map)161            # https://huggingface.co/docs/accelerate/package_reference/big_modeling#accelerate.dispatch_model162            model = accelerate.dispatch_model(model, device_map=device_map, offload_buffers=True)163 164        # No offload165        elif not shared.args.cpu:166            if is_xpu_available():167                model = model.to(torch.device("xpu:0"))168            else:169                model = model.to(torch.device('cuda:0'))170 171    return model172