compare-logits.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/env python3
  2. import numpy as np
  3. import sys
  4. import os
  5. from pathlib import Path
  6. def quick_logits_check(pytorch_file, llamacpp_file):
  7. """Lightweight sanity check before NMSE"""
  8. try:
  9. pytorch_logits = np.fromfile(pytorch_file, dtype=np.float32)
  10. llamacpp_logits = np.fromfile(llamacpp_file, dtype=np.float32)
  11. except Exception as e:
  12. print(f"❌ NOK: Failed to load files - {e}")
  13. return False
  14. # Check shapes match
  15. if pytorch_logits.shape != llamacpp_logits.shape:
  16. print(f"❌ NOK: Shape mismatch - PyTorch: {pytorch_logits.shape}, llama.cpp: {llamacpp_logits.shape}")
  17. return False
  18. # Calculate key metrics
  19. diff = pytorch_logits - llamacpp_logits
  20. abs_diff = np.abs(diff)
  21. max_diff = np.max(abs_diff)
  22. # Get top 10 predictions from both models
  23. pytorch_top10 = np.argsort(pytorch_logits)[-10:][::-1]
  24. llamacpp_top10 = np.argsort(llamacpp_logits)[-10:][::-1]
  25. print(f"Top 10 PyTorch logits: {pytorch_logits[pytorch_top10]}")
  26. print(f"Top 10 llama.cpp logits: {llamacpp_logits[llamacpp_top10]}")
  27. print(f"Max absolute difference: {max_diff:.4f}")
  28. return True
  29. def main():
  30. model_path = os.getenv('MODEL_PATH')
  31. if not model_path:
  32. print("Error: MODEL_PATH environment variable not set")
  33. sys.exit(1)
  34. if not os.path.exists(model_path):
  35. print(f"Error: Model file not found: {model_path}")
  36. sys.exit(1)
  37. model_name = os.path.basename(model_path)
  38. data_dir = Path("data")
  39. pytorch_file = data_dir / f"pytorch-{model_name}.bin"
  40. llamacpp_file = data_dir / f"llamacpp-{model_name}.bin"
  41. if not pytorch_file.exists():
  42. print(f"Error: PyTorch logits file not found: {pytorch_file}")
  43. print("Please run scripts/run-org-model.sh first to generate this file.")
  44. sys.exit(1)
  45. if not llamacpp_file.exists():
  46. print(f"Error: llama.cpp logits file not found: {llamacpp_file}")
  47. print("Please run scripts/run-converted-model.sh first to generate this file.")
  48. sys.exit(1)
  49. print("Checked all required files were found. Proceeding...\n")
  50. print("🔍 GGML Model Validation for model ", model_name)
  51. print("=" * 40)
  52. print(f"PyTorch logits : {pytorch_file}")
  53. print(f"llama.cpp logits: {llamacpp_file}")
  54. print()
  55. success = quick_logits_check(pytorch_file, llamacpp_file)
  56. # Exit with appropriate code
  57. if success:
  58. print("✅ OK: Lightweight model check successful!")
  59. print(" Ok to proceed with NMSE check...")
  60. sys.exit(0)
  61. else:
  62. print(f"❌ NOK: Top 10 predictions don't match - generation will differ")
  63. sys.exit(1)
  64. if __name__ == "__main__":
  65. main()