run-original-model.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. #!/usr/bin/env python3
  2. import argparse
  3. import os
  4. import numpy as np
  5. import importlib
  6. from pathlib import Path
  7. from transformers import AutoTokenizer, AutoConfig, AutoModel
  8. import torch
  9. unreleased_model_name = os.getenv('UNRELEASED_MODEL_NAME')
  10. parser = argparse.ArgumentParser(description='Process model with specified path')
  11. parser.add_argument('--model-path', '-m', help='Path to the model')
  12. parser.add_argument('--prompts-file', '-p', help='Path to file containing prompts (one per line)')
  13. args = parser.parse_args()
  14. def read_prompt_from_file(file_path):
  15. try:
  16. with open(file_path, 'r', encoding='utf-8') as f:
  17. return f.read().strip()
  18. except FileNotFoundError:
  19. print(f"Error: Prompts file '{file_path}' not found")
  20. exit(1)
  21. except Exception as e:
  22. print(f"Error reading prompts file: {e}")
  23. exit(1)
  24. model_path = os.environ.get('EMBEDDING_MODEL_PATH', args.model_path)
  25. if model_path is None:
  26. parser.error("Model path must be specified either via --model-path argument or EMBEDDING_MODEL_PATH environment variable")
  27. tokenizer = AutoTokenizer.from_pretrained(model_path)
  28. config = AutoConfig.from_pretrained(model_path)
  29. # This can be used to override the sliding window size for manual testing. This
  30. # can be useful to verify the sliding window attention mask in the original model
  31. # and compare it with the converted .gguf model.
  32. if hasattr(config, 'sliding_window'):
  33. original_sliding_window = config.sliding_window
  34. #original_sliding_window = 6
  35. print(f"Modified sliding window: {original_sliding_window} -> {config.sliding_window}")
  36. print(f"Using unreleased model: {unreleased_model_name}")
  37. if unreleased_model_name:
  38. model_name_lower = unreleased_model_name.lower()
  39. unreleased_module_path = f"transformers.models.{model_name_lower}.modular_{model_name_lower}"
  40. class_name = f"{unreleased_model_name}Model"
  41. print(f"Importing unreleased model module: {unreleased_module_path}")
  42. try:
  43. model_class = getattr(importlib.import_module(unreleased_module_path), class_name)
  44. model = model_class.from_pretrained(model_path, config=config)
  45. except (ImportError, AttributeError) as e:
  46. print(f"Failed to import or load model: {e}")
  47. exit(1)
  48. else:
  49. model = AutoModel.from_pretrained(model_path, config=config)
  50. print(f"Model class: {type(model)}")
  51. print(f"Model file: {type(model).__module__}")
  52. # Verify the model is using the correct sliding window
  53. if hasattr(model.config, 'sliding_window'):
  54. print(f"Model's sliding_window: {model.config.sliding_window}")
  55. else:
  56. print("Model config does not have sliding_window attribute")
  57. model_name = os.path.basename(model_path)
  58. if args.prompts_file:
  59. prompt_text = read_prompt_from_file(args.prompts_file)
  60. texts = [prompt_text]
  61. else:
  62. texts = ["Hello world today"]
  63. encoded = tokenizer(
  64. texts,
  65. padding=True,
  66. truncation=True,
  67. return_tensors="pt"
  68. )
  69. tokens = encoded['input_ids'][0]
  70. token_strings = tokenizer.convert_ids_to_tokens(tokens)
  71. for i, (token_id, token_str) in enumerate(zip(tokens, token_strings)):
  72. print(f"{token_id:6d} -> '{token_str}'")
  73. with torch.no_grad():
  74. outputs = model(**encoded)
  75. hidden_states = outputs.last_hidden_state # Shape: [batch_size, seq_len, hidden_size]
  76. # Extract embeddings for each token (matching LLAMA_POOLING_TYPE_NONE behavior)
  77. all_embeddings = hidden_states[0].cpu().numpy() # Shape: [seq_len, hidden_size]
  78. print(f"Hidden states shape: {hidden_states.shape}")
  79. print(f"All embeddings shape: {all_embeddings.shape}")
  80. print(f"Embedding dimension: {all_embeddings.shape[1]}")
  81. # Print embeddings exactly like embedding.cpp does for LLAMA_POOLING_TYPE_NONE
  82. n_embd = all_embeddings.shape[1]
  83. n_embd_count = all_embeddings.shape[0]
  84. print() # Empty line to match C++ output
  85. for j in range(n_embd_count):
  86. embedding = all_embeddings[j]
  87. print(f"embedding {j}: ", end="")
  88. # Print first 3 values
  89. for i in range(min(3, n_embd)):
  90. print(f"{embedding[i]:9.6f} ", end="")
  91. print(" ... ", end="")
  92. # Print last 3 values
  93. for i in range(n_embd - 3, n_embd):
  94. print(f"{embedding[i]:9.6f} ", end="")
  95. print() # New line
  96. print() # Final empty line to match C++ output
  97. data_dir = Path("data")
  98. data_dir.mkdir(exist_ok=True)
  99. bin_filename = data_dir / f"pytorch-{model_name}-embeddings.bin"
  100. txt_filename = data_dir / f"pytorch-{model_name}-embeddings.txt"
  101. # Save all embeddings flattened (matching what embedding.cpp would save if it did)
  102. flattened_embeddings = all_embeddings.flatten()
  103. flattened_embeddings.astype(np.float32).tofile(bin_filename)
  104. with open(txt_filename, "w") as f:
  105. f.write(f"# Model class: {model_name}\n")
  106. f.write(f"# Tokens: {token_strings}\n")
  107. f.write(f"# Shape: {all_embeddings.shape}\n")
  108. f.write(f"# n_embd_count: {n_embd_count}, n_embd: {n_embd}\n\n")
  109. for j in range(n_embd_count):
  110. f.write(f"# Token {j} ({token_strings[j]}):\n")
  111. for i, value in enumerate(all_embeddings[j]):
  112. f.write(f"{j}_{i}: {value:.6f}\n")
  113. f.write("\n")
  114. print(f"Total values: {len(flattened_embeddings)} ({n_embd_count} tokens × {n_embd} dimensions)")
  115. print("")
  116. print(f"Saved bin embeddings to: {bin_filename}")
  117. print(f"Saved txt embeddings to: {txt_filename}")