mirror of
https://github.com/ggerganov/llama.cpp
synced 2026-03-20 14:10:47 +01:00
* examples : add debug utility/example
This commit introduces a new example named llama-debug which is a
utility that is intended to be used to assist with developing/debugging
a converted model.
The motivation for this utilitiy is to assist in model conversion work
to verify that the model produces the expected outputs. It is intended
to replace logits.cpp in examples/model-conversion.
Example usage:
```console
./build/bin/llama-debug \
-m models/Qwen2.5-0.5B-Instruct.gguf \
--prompt "Hello, my name is" \
--save-logits
...
Model add_bos: false
Input prompt: "Hello, my name is"
Token ids (5):
Hello(9707) ,(11) my(847) name(829) is(374)
Data saved to data/llamacpp-Qwen2.5-0.5B-Instruct.bin
Data saved to data/llamacpp-Qwen2.5-0.5B-Instruct.txt
Prompt saved to data/llamacpp-Qwen2.5-0.5B-Instruct-prompt.txt
Tokens saved to data/llamacpp-Qwen2.5-0.5B-Instruct-tokens.bin
```
For more details about the options available for this example, please
refer to examples/debug/README.md.
* throw runtime error instead of logging error
* remove params.warmup and enable the warmup/nowarmup option
* model-conversion : remove logits.cpp
This commit removes logits.cpp in favor of using llama-debug for
generating logits and embeddings.
* examples : remove model-conversion directory
This was missed in the previous commit.
* model-conversion : add support for saving prompt and token ids
This commit add support for storing the prompt and the token ids for the
prompt when running the original models.
The motivation for this is that this will allow us to compare the prompt
and the tokens generated for the prompt when verifing the converted
model. Currently it is possible that even if the same prompt is used
that the tokens generated are different if there is a difference in the
tokenization between the original and converted model which would
currently go unnoticed (the verification will most likely fail but it
might not be obvious why).
* squash! model-conversion : add support for saving prompt and token ids
fix pyright errors.
* model-conversion : add compare_tokens utility
This commit adds a script to compare token outputs between original and
converted models.
Example usage:
```console
(venv) $ ./scripts/utils/compare_tokens.py pytorch-gemma-3-270m-it llamacpp-gemma-3-270m-it-bf16
Comparing tokens between:
Original : pytorch-gemma-3-270m-it (6 tokens)
Converted: llamacpp-gemma-3-270m-it-bf16 (6 tokens)
✅ All 6 tokens match!
```
And there is a verbose flag that will also print out the prompts:
```console
(venv) $ ./scripts/utils/compare_tokens.py pytorch-gemma-3-270m-it llamacpp-gemma-3-270m-it-bf16 -v
Original model prompt (pytorch-gemma-3-270m-it):
prompt: Hello, my name is
n_tokens: 6
token ids: 2, 9259, 236764, 1041, 1463, 563
Converted model prompt (llamacpp-gemma-3-270m-it-bf16):
prompt: Hello, my name is
n_tokens: 6
token ids: 2, 9259, 236764, 1041, 1463, 563
Comparing tokens between:
Original : pytorch-gemma-3-270m-it (6 tokens)
Converted: llamacpp-gemma-3-270m-it-bf16 (6 tokens)
✅ All 6 tokens match!
```
* model-conversion : add token comparison to verifiction scripts
This commit add the calling of the compare_tokens function in
compare-logits.py and semantic_check.py to ensure that the token ids
that the tokenizers procoduce are the same before proceeding with
verifying the logits/embeddings.
Placing them in the existing scripts instead calling them separately
ensures that the token comparison is always done prior to the
logit/embedding verifications.
Follow up commit/pr could refactor the causal logits verification into
a single script instead of the two that exist now. This would reduce the
code and make it consistent with the embeddings verficiation which only
has a single script.
* debug : use llama_model_n_embd_out
This commit updates the debug example to use the new function
llama_model_n_embd_out instead of llama_model_n_embd.
The motivation for this change is to support late interation retriever
models, like LFM2-ColBert-350M, where the output embeddings are down
projected to a lower dimension.
* debug : add print_usage function
This commit adds a print_usage function that is passed to the
common_params_parse.
The motivation for this is that this enables a specific usage message
which will be printed after all the options, for example:
```console
example usage:
Print tensors:
./build/bin/llama-debug -m model.gguf -p "Hello my name is" --verbose
The tensors to be printed can be filtered with --tensor-filter option.
Save logits/embeddings:
./build/bin/llama-debug -m model.gguf -p "Hello my name is" --save-logits
Add --embedding to save embeddings
```
169 lines
6.1 KiB
Python
Executable File
169 lines
6.1 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
|
|
import argparse
|
|
import os
|
|
import sys
|
|
import importlib
|
|
import torch
|
|
import numpy as np
|
|
|
|
from transformers import AutoTokenizer, AutoModelForCausalLM, AutoModelForImageTextToText, AutoConfig
|
|
|
|
# Add parent directory to path for imports
|
|
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
|
|
from utils.common import debug_hook, save_output_data
|
|
|
|
def parse_arguments():
|
|
parser = argparse.ArgumentParser(description="Process model with specified path")
|
|
parser.add_argument("--model-path", "-m", help="Path to the model")
|
|
parser.add_argument("--prompt-file", "-f", help="Optional prompt file", required=False)
|
|
parser.add_argument("--verbose", "-v", action="store_true", help="Enable verbose debug output")
|
|
parser.add_argument("--device", "-d", help="Device to use (cpu, cuda, mps, auto)", default="auto")
|
|
return parser.parse_args()
|
|
|
|
def load_model_and_tokenizer(model_path, device="auto"):
|
|
print("Loading model and tokenizer using AutoTokenizer:", model_path)
|
|
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
|
config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
|
|
multimodal = False
|
|
full_config = config
|
|
|
|
# Determine device_map based on device argument
|
|
if device == "cpu":
|
|
device_map = {"": "cpu"}
|
|
print("Forcing CPU usage")
|
|
elif device == "auto":
|
|
device_map = "auto"
|
|
else:
|
|
device_map = {"": device}
|
|
|
|
print("Model type: ", config.model_type)
|
|
if "vocab_size" not in config and "text_config" in config:
|
|
config = config.text_config
|
|
multimodal = True
|
|
|
|
print("Vocab size: ", config.vocab_size)
|
|
print("Hidden size: ", config.hidden_size)
|
|
print("Number of layers: ", config.num_hidden_layers)
|
|
print("BOS token id: ", config.bos_token_id)
|
|
print("EOS token id: ", config.eos_token_id)
|
|
|
|
unreleased_model_name = os.getenv("UNRELEASED_MODEL_NAME")
|
|
if unreleased_model_name:
|
|
model_name_lower = unreleased_model_name.lower()
|
|
unreleased_module_path = (
|
|
f"transformers.models.{model_name_lower}.modular_{model_name_lower}"
|
|
)
|
|
class_name = f"{unreleased_model_name}ForCausalLM"
|
|
print(f"Importing unreleased model module: {unreleased_module_path}")
|
|
|
|
try:
|
|
model_class = getattr(importlib.import_module(unreleased_module_path), class_name)
|
|
model = model_class.from_pretrained(
|
|
model_path,
|
|
device_map=device_map,
|
|
offload_folder="offload",
|
|
trust_remote_code=True,
|
|
config=config
|
|
)
|
|
except (ImportError, AttributeError) as e:
|
|
print(f"Failed to import or load model: {e}")
|
|
exit(1)
|
|
else:
|
|
if multimodal:
|
|
model = AutoModelForImageTextToText.from_pretrained(
|
|
model_path,
|
|
device_map=device_map,
|
|
offload_folder="offload",
|
|
trust_remote_code=True,
|
|
config=full_config
|
|
)
|
|
else:
|
|
model = AutoModelForCausalLM.from_pretrained(
|
|
model_path,
|
|
device_map=device_map,
|
|
offload_folder="offload",
|
|
trust_remote_code=True,
|
|
config=config
|
|
)
|
|
|
|
print(f"Model class: {model.__class__.__name__}")
|
|
|
|
return model, tokenizer, config
|
|
|
|
def enable_torch_debugging(model):
|
|
for name, module in model.named_modules():
|
|
if len(list(module.children())) == 0: # only leaf modules
|
|
module.register_forward_hook(debug_hook(name))
|
|
|
|
def get_prompt(args):
|
|
if args.prompt_file:
|
|
with open(args.prompt_file, encoding='utf-8') as f:
|
|
return f.read()
|
|
elif os.getenv("MODEL_TESTING_PROMPT"):
|
|
return os.getenv("MODEL_TESTING_PROMPT")
|
|
else:
|
|
return "Hello, my name is"
|
|
|
|
def main():
|
|
args = parse_arguments()
|
|
model_path = os.environ.get("MODEL_PATH", args.model_path)
|
|
if model_path is None:
|
|
print("Error: Model path must be specified either via --model-path argument or MODEL_PATH environment variable")
|
|
sys.exit(1)
|
|
|
|
|
|
model, tokenizer, config = load_model_and_tokenizer(model_path, args.device)
|
|
|
|
if args.verbose:
|
|
enable_torch_debugging(model)
|
|
|
|
model_name = os.path.basename(model_path)
|
|
|
|
# Iterate over the model parameters (the tensors) and get the first one
|
|
# and use it to get the device the model is on.
|
|
device = next(model.parameters()).device
|
|
prompt = get_prompt(args)
|
|
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
|
|
token_ids = input_ids[0].cpu().tolist()
|
|
|
|
print(f"Input tokens: {input_ids}")
|
|
print(f"Input text: {repr(prompt)}")
|
|
print(f"Tokenized: {tokenizer.convert_ids_to_tokens(input_ids[0])}")
|
|
|
|
batch_size = 512
|
|
|
|
with torch.no_grad():
|
|
past = None
|
|
outputs = None
|
|
for i in range(0, input_ids.size(1), batch_size):
|
|
print(f"Processing chunk with tokens {i} to {i + batch_size}")
|
|
chunk = input_ids[:, i:i + batch_size]
|
|
outputs = model(chunk.to(model.device), past_key_values=past, use_cache=True)
|
|
past = outputs.past_key_values
|
|
|
|
logits = outputs.logits # type: ignore
|
|
|
|
# Extract logits for the last token (next token prediction)
|
|
last_logits = logits[0, -1, :].float().cpu().numpy()
|
|
|
|
print(f"Logits shape: {logits.shape}")
|
|
print(f"Last token logits shape: {last_logits.shape}")
|
|
print(f"Vocab size: {len(last_logits)}")
|
|
|
|
# Print some sample logits for quick verification
|
|
print(f"First 10 logits: {last_logits[:10]}")
|
|
print(f"Last 10 logits: {last_logits[-10:]}")
|
|
|
|
# Show top 5 predicted tokens
|
|
top_indices = np.argsort(last_logits)[-5:][::-1]
|
|
print("Top 5 predictions:")
|
|
for idx in top_indices:
|
|
token = tokenizer.decode([idx])
|
|
print(f" Token {idx} ({repr(token)}): {last_logits[idx]:.6f}")
|
|
|
|
save_output_data(last_logits, token_ids, prompt, model_name)
|
|
|
|
if __name__ == "__main__":
|
|
main()
|