char-fork/llama.cpp
git clone https://git.t4t.associates/char-fork/llama.cpp
1138b851f
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 ,AutoConfig ,AutoModelForCausalLM 11 12sys .path .insert (0 ,os .path .join (os .path .dirname (__file__ ),'..' )) 13from utils .common import save_output_data 14 15unreleased_model_name = os .getenv ('UNRELEASED_MODEL_NAME' ) 16 17parser = argparse .ArgumentParser (description = 'Process model with specified path' ) 18parser .add_argument ('--model-path' ,'-m' ,help = 'Path to the model' ) 19args = parser .parse_args () 20 21model_path = os .environ .get ('MODEL_PATH' ,args .model_path ) 22if model_path is None : 23parser .error ("Model path must be specified either via --model-path argument or MODEL_PATH environment variable" ) 24 25config = AutoConfig .from_pretrained (model_path ) 26 27"Model type: " ,config .model_type ) 28"Vocab size: " ,config .vocab_size ) 29"Hidden size: " ,config .hidden_size ) 30"Number of layers: " ,config .num_hidden_layers ) 31"BOS token id: " ,config .bos_token_id ) 32"EOS token id: " ,config .eos_token_id ) 33 34"Loading model and tokenizer using AutoTokenizer:" ,model_path ) 35tokenizer = AutoTokenizer .from_pretrained (model_path ) 36 37if unreleased_model_name : 38model_name_lower = unreleased_model_name .lower () 39unreleased_module_path = f"transformers.models. { model_name_lower } .modular_ { model_name_lower } " 40class_name = f" { unreleased_model_name } ForCausalLM" 41f"Importing unreleased model module: { unreleased_module_path } " ) 42 43try : 44model_class = getattr (importlib .import_module (unreleased_module_path ),class_name ) 45model = model_class .from_pretrained (model_path ) 46except (ImportError ,AttributeError )as e : 47f"Failed to import or load model: { e } " ) 48"Falling back to AutoModelForCausalLM" ) 49model = AutoModelForCausalLM .from_pretrained (model_path ) 50else : 51model = AutoModelForCausalLM .from_pretrained (model_path ) 52f"Model class: { type ( model ) } " ) 53#print(f"Model file: {type(model).__module__}") 54 55model_name = os .path .basename (model_path ) 56f"Model name: { model_name } " ) 57 58prompt = "Hello world today" 59input_ids = tokenizer (prompt ,return_tensors = "pt" ).input_ids # ty: ignore[call-non-callable] 60token_ids = input_ids [0 ].cpu ().tolist () 61f"Input tokens: { input_ids } " ) 62f"Input text: { repr ( prompt ) } " ) 63f"Tokenized: { tokenizer . convert_ids_to_tokens ( input_ids [ 0 ]) } " )# ty: ignore[unresolved-attribute] 64 65with torch .no_grad (): 66outputs = model (input_ids ,output_hidden_states = True ) 67 68# Extract hidden states from the last layer 69# outputs.hidden_states is a tuple of (num_layers + 1) tensors 70# Index -1 gets the last layer, shape: [batch_size, seq_len, hidden_size] 71last_hidden_states = outputs .hidden_states [- 1 ] 72 73# Get embeddings for all tokens 74token_embeddings = last_hidden_states [0 ].float ().cpu ().numpy ()# Remove batch dimension 75 76f"Hidden states shape: { last_hidden_states . shape } " ) 77f"Token embeddings shape: { token_embeddings . shape } " ) 78f"Hidden dimension: { token_embeddings . shape [ - 1 ] } " ) 79f"Number of tokens: { token_embeddings . shape [ 0 ] } " ) 80 81token_embeddings ) 82save_output_data (token_embeddings ,token_ids ,prompt ,model_name ,type_suffix = "-embeddings" ) 83 84# Print embeddings per token in the requested format 85"\nToken embeddings:" ) 86tokens = tokenizer .convert_ids_to_tokens (input_ids [0 ])# ty: ignore[unresolved-attribute] 87for i ,embedding in enumerate (token_embeddings ): 88# Format: show first few values, ..., then last few values 89if len (embedding )> 10 : 90# Show first 3 and last 3 values with ... in between 91first_vals = " " .join (f" { val :8.6f } " for val in embedding [:3 ]) 92last_vals = " " .join (f" { val :8.6f } " for val in embedding [- 3 :]) 93f"embedding { i } : { first_vals } ... { last_vals } " ) 94else : 95# If embedding is short, show all values 96vals = " " .join (f" { val :8.6f } " for val in embedding ) 97f"embedding { i } : { vals } " ) 98 99# Also show token info for reference 100f"\nToken reference:" ) 101for i ,token in enumerate (tokens ): 102f" Token { i } : { repr ( token ) } " ) 103