char-fork/llama.cpp
git clone https://git.t4t.associates/char-fork/llama.cpp
667b69427
char/aliceai-t5-moe
1#!/usr/bin/env python3 2 3import argparse 4import os 5import sys 6import importlib 7import torch 8import numpy as np 9 10from transformers import AutoTokenizer ,AutoModelForCausalLM ,AutoModelForImageTextToText ,AutoConfig 11 12# Add parent directory to path for imports 13sys .path .insert (0 ,os .path .join (os .path .dirname (__file__ ),'..' )) 14from utils .common import debug_hook ,save_output_data 15 16def parse_arguments (): 17parser = argparse .ArgumentParser (description = "Process model with specified path" ) 18parser .add_argument ("--model-path" ,"-m" ,help = "Path to the model" ) 19parser .add_argument ("--prompt-file" ,"-f" ,help = "Optional prompt file" ,required = False ) 20parser .add_argument ("--verbose" ,"-v" ,action = "store_true" ,help = "Enable verbose debug output" ) 21parser .add_argument ("--device" ,"-d" ,help = "Device to use (cpu, cuda, mps, auto)" ,default = "auto" ) 22return parser .parse_args () 23 24def load_model_and_tokenizer (model_path ,device = "auto" ): 25"Loading model and tokenizer using AutoTokenizer:" ,model_path ) 26tokenizer = AutoTokenizer .from_pretrained (model_path ,trust_remote_code = True ) 27config = AutoConfig .from_pretrained (model_path ,trust_remote_code = True ) 28multimodal = False 29full_config = config 30 31# Determine device_map based on device argument 32if device == "cpu" : 33device_map = {"" :"cpu" } 34"Forcing CPU usage" ) 35elif device == "auto" : 36device_map = "auto" 37else : 38device_map = {"" :device } 39 40"Model type: " ,config .model_type ) 41if "vocab_size" not in config and "text_config" in config : 42config = config .text_config 43multimodal = True 44 45def print_if_exists (label ,obj ,attr ,default = "N/A" ): 46val = getattr (obj ,attr )if hasattr (obj ,attr )else default 47f" { label } " ,val ) 48 49print_if_exists ("Vocab size: " ,config ,"vocab_size" ) 50print_if_exists ("Hidden size: " ,config ,"hidden_size" ) 51print_if_exists ("Number of layers: " ,config ,"num_hidden_layers" ) 52print_if_exists ("BOS token id: " ,config ,"bos_token_id" ) 53print_if_exists ("EOS token id: " ,config ,"eos_token_id" ) 54 55unreleased_model_name = os .getenv ("UNRELEASED_MODEL_NAME" ) 56if unreleased_model_name : 57model_name_lower = unreleased_model_name .lower () 58unreleased_module_path = ( 59f"transformers.models. { model_name_lower } .modular_ { model_name_lower } " 60 ) 61class_name = f" { unreleased_model_name } ForCausalLM" 62f"Importing unreleased model module: { unreleased_module_path } " ) 63 64try : 65model_class = getattr (importlib .import_module (unreleased_module_path ),class_name ) 66model = model_class .from_pretrained ( 67model_path , 68device_map = device_map , 69offload_folder = "offload" , 70trust_remote_code = True , 71config = config 72 ) 73except (ImportError ,AttributeError )as e : 74f"Failed to import or load model: { e } " ) 75exit (1 ) 76else : 77if multimodal : 78model = AutoModelForImageTextToText .from_pretrained ( 79model_path , 80device_map = device_map , 81offload_folder = "offload" , 82trust_remote_code = True , 83config = full_config 84 ) 85else : 86model = AutoModelForCausalLM .from_pretrained ( 87model_path , 88device_map = device_map , 89offload_folder = "offload" , 90trust_remote_code = True , 91config = config 92 ) 93 94f"Model class: { model . __class__ . __name__ } " ) 95 96return model ,tokenizer ,config 97 98def enable_torch_debugging (model ): 99for name ,module in model .named_modules (): 100if len (list (module .children ()))== 0 :# only leaf modules 101module .register_forward_hook (debug_hook (name )) 102 103def get_prompt (args ): 104if args .prompt_file : 105with open (args .prompt_file ,encoding = 'utf-8' )as f : 106return f .read () 107elif os .getenv ("MODEL_TESTING_PROMPT" ): 108return os .getenv ("MODEL_TESTING_PROMPT" ) 109else : 110return "Hello, my name is" 111 112def main (): 113args = parse_arguments () 114model_path = os .environ .get ("MODEL_PATH" ,args .model_path ) 115if model_path is None : 116"Error: Model path must be specified either via --model-path argument or MODEL_PATH environment variable" ) 117sys .exit (1 ) 118 119 120model ,tokenizer ,config = load_model_and_tokenizer (model_path ,args .device ) 121 122if args .verbose : 123enable_torch_debugging (model ) 124 125model_name = os .path .basename (model_path ) 126 127# Iterate over the model parameters (the tensors) and get the first one 128# and use it to get the device the model is on. 129device = next (model .parameters ()).device 130prompt = get_prompt (args ) 131input_ids = tokenizer (prompt ,return_tensors = "pt" ).input_ids .to (device ) 132token_ids = input_ids [0 ].cpu ().tolist () 133 134f"Input tokens: { input_ids } " ) 135f"Input text: { repr ( prompt ) } " ) 136f"Tokenized: { tokenizer . convert_ids_to_tokens ( input_ids [ 0 ]) } " ) 137 138batch_size = 512 139 140with torch .no_grad (): 141past = None 142outputs = None 143for i in range (0 ,input_ids .size (1 ),batch_size ): 144f"Processing chunk with tokens { i } to { i + batch_size } " ) 145chunk = input_ids [:,i :i + batch_size ] 146outputs = model (chunk .to (model .device ),past_key_values = past ,use_cache = True ) 147past = outputs .past_key_values 148 149logits = outputs .logits # type: ignore 150 151# Extract logits for the last token (next token prediction) 152last_logits = logits [0 ,- 1 , :].float ().cpu ().numpy () 153 154f"Logits shape: { logits . shape } " ) 155f"Last token logits shape: { last_logits . shape } " ) 156f"Vocab size: { len ( last_logits ) } " ) 157 158# Print some sample logits for quick verification 159f"First 10 logits: { last_logits [: 10 ] } " ) 160f"Last 10 logits: { last_logits [ - 10 :] } " ) 161 162# Show top 5 predicted tokens 163top_indices = np .argsort (last_logits )[- 5 :][::- 1 ] 164"Top 5 predictions:" ) 165for idx in top_indices : 166token = tokenizer .decode ([idx ]) 167f" Token { idx } ( { repr ( token ) } ): { last_logits [ idx ]:.6f } " ) 168 169save_output_data (last_logits ,token_ids ,prompt ,model_name ) 170 171if __name__ == "__main__" : 172main ()