1
0

run-org-model.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. #!/usr/bin/env python3
  2. import argparse
  3. import os
  4. import sys
  5. import importlib
  6. from pathlib import Path
  7. # Add parent directory to path for imports
  8. sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
  9. from transformers import AutoTokenizer, AutoModelForCausalLM, AutoModelForImageTextToText, AutoConfig
  10. import torch
  11. import numpy as np
  12. from utils.common import debug_hook
  13. parser = argparse.ArgumentParser(description="Process model with specified path")
  14. parser.add_argument("--model-path", "-m", help="Path to the model")
  15. parser.add_argument("--prompt-file", "-f", help="Optional prompt file", required=False)
  16. parser.add_argument("--verbose", "-v", action="store_true", help="Enable verbose debug output")
  17. args = parser.parse_args()
  18. model_path = os.environ.get("MODEL_PATH", args.model_path)
  19. if model_path is None:
  20. parser.error(
  21. "Model path must be specified either via --model-path argument or MODEL_PATH environment variable"
  22. )
  23. ### If you want to dump RoPE activations, uncomment the following lines:
  24. ### === START ROPE DEBUG ===
  25. # from utils.common import setup_rope_debug
  26. # setup_rope_debug("transformers.models.apertus.modeling_apertus")
  27. ### == END ROPE DEBUG ===
  28. print("Loading model and tokenizer using AutoTokenizer:", model_path)
  29. tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
  30. config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
  31. multimodal = False
  32. full_config = config
  33. print("Model type: ", config.model_type)
  34. if "vocab_size" not in config and "text_config" in config:
  35. config = config.text_config
  36. multimodal = True
  37. print("Vocab size: ", config.vocab_size)
  38. print("Hidden size: ", config.hidden_size)
  39. print("Number of layers: ", config.num_hidden_layers)
  40. print("BOS token id: ", config.bos_token_id)
  41. print("EOS token id: ", config.eos_token_id)
  42. unreleased_model_name = os.getenv("UNRELEASED_MODEL_NAME")
  43. if unreleased_model_name:
  44. model_name_lower = unreleased_model_name.lower()
  45. unreleased_module_path = (
  46. f"transformers.models.{model_name_lower}.modular_{model_name_lower}"
  47. )
  48. class_name = f"{unreleased_model_name}ForCausalLM"
  49. print(f"Importing unreleased model module: {unreleased_module_path}")
  50. try:
  51. model_class = getattr(
  52. importlib.import_module(unreleased_module_path), class_name
  53. )
  54. model = model_class.from_pretrained(
  55. model_path
  56. ) # Note: from_pretrained, not fromPretrained
  57. except (ImportError, AttributeError) as e:
  58. print(f"Failed to import or load model: {e}")
  59. exit(1)
  60. else:
  61. if multimodal:
  62. model = AutoModelForImageTextToText.from_pretrained(
  63. model_path, device_map="auto", offload_folder="offload", trust_remote_code=True, config=full_config
  64. )
  65. else:
  66. model = AutoModelForCausalLM.from_pretrained(
  67. model_path, device_map="auto", offload_folder="offload", trust_remote_code=True, config=config
  68. )
  69. if args.verbose:
  70. for name, module in model.named_modules():
  71. if len(list(module.children())) == 0: # only leaf modules
  72. module.register_forward_hook(debug_hook(name))
  73. model_name = os.path.basename(model_path)
  74. # Printing the Model class to allow for easier debugging. This can be useful
  75. # when working with models that have not been publicly released yet and this
  76. # migth require that the concrete class is imported and used directly instead
  77. # of using AutoModelForCausalLM.
  78. print(f"Model class: {model.__class__.__name__}")
  79. device = next(model.parameters()).device
  80. if args.prompt_file:
  81. with open(args.prompt_file, encoding='utf-8') as f:
  82. prompt = f.read()
  83. elif os.getenv("MODEL_TESTING_PROMPT"):
  84. prompt = os.getenv("MODEL_TESTING_PROMPT")
  85. else:
  86. prompt = "Hello, my name is"
  87. input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
  88. print(f"Input tokens: {input_ids}")
  89. print(f"Input text: {repr(prompt)}")
  90. print(f"Tokenized: {tokenizer.convert_ids_to_tokens(input_ids[0])}")
  91. batch_size = 512
  92. with torch.no_grad():
  93. past = None
  94. outputs = None
  95. for i in range(0, input_ids.size(1), batch_size):
  96. print(f"Processing chunk with tokens {i} to {i + batch_size}")
  97. chunk = input_ids[:, i:i + batch_size]
  98. outputs = model(chunk.to(model.device), past_key_values=past, use_cache=True)
  99. past = outputs.past_key_values
  100. logits = outputs.logits # type: ignore
  101. # Extract logits for the last token (next token prediction)
  102. last_logits = logits[0, -1, :].float().cpu().numpy()
  103. print(f"Logits shape: {logits.shape}")
  104. print(f"Last token logits shape: {last_logits.shape}")
  105. print(f"Vocab size: {len(last_logits)}")
  106. data_dir = Path("data")
  107. data_dir.mkdir(exist_ok=True)
  108. bin_filename = data_dir / f"pytorch-{model_name}.bin"
  109. txt_filename = data_dir / f"pytorch-{model_name}.txt"
  110. # Save to file for comparison
  111. last_logits.astype(np.float32).tofile(bin_filename)
  112. # Also save as text file for easy inspection
  113. with open(txt_filename, "w") as f:
  114. for i, logit in enumerate(last_logits):
  115. f.write(f"{i}: {logit:.6f}\n")
  116. # Print some sample logits for quick verification
  117. print(f"First 10 logits: {last_logits[:10]}")
  118. print(f"Last 10 logits: {last_logits[-10:]}")
  119. # Show top 5 predicted tokens
  120. top_indices = np.argsort(last_logits)[-5:][::-1]
  121. print("Top 5 predictions:")
  122. for idx in top_indices:
  123. token = tokenizer.decode([idx])
  124. print(f" Token {idx} ({repr(token)}): {last_logits[idx]:.6f}")
  125. print(f"Saved bin logits to: {bin_filename}")
  126. print(f"Saved txt logist to: {txt_filename}")