check-nmse.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. #!/usr/bin/env python3
  2. import numpy as np
  3. import sys
  4. import os
  5. import argparse
  6. from pathlib import Path
  7. def calculate_nmse(reference, test):
  8. mse = np.mean((test - reference) ** 2)
  9. ref_var = np.var(reference)
  10. if ref_var == 0:
  11. nmse = float('inf') if mse > 0 else 0.0
  12. return mse, mse, ref_var
  13. nmse = mse / ref_var
  14. return nmse, mse, ref_var
  15. def load_logits(file_path):
  16. if not os.path.exists(file_path):
  17. raise FileNotFoundError(f"File not found: {file_path}")
  18. if file_path.suffix == '.npy':
  19. return np.load(file_path)
  20. elif file_path.suffix == '.bin':
  21. return np.fromfile(file_path, dtype=np.float32)
  22. else:
  23. # Try to load as text file
  24. try:
  25. # If it has index format "0: value", extract just values
  26. data = []
  27. with open(file_path, 'r') as f:
  28. for line in f:
  29. if ':' in line:
  30. # Format: "index: value"
  31. value = float(line.split(':')[1].strip())
  32. else:
  33. # Just the value
  34. value = float(line.strip())
  35. data.append(value)
  36. return np.array(data, dtype=np.float32)
  37. except:
  38. return np.loadtxt(file_path, dtype=np.float32)
  39. def interpret_nmse(nmse):
  40. """Provide interpretation of NMSE value"""
  41. if nmse == 0:
  42. return "Perfect match", "🎉"
  43. elif nmse < 1e-6:
  44. return "Essentially identical", "✅"
  45. elif nmse < 1e-4:
  46. return "Excellent match", "✅"
  47. elif nmse < 1e-3:
  48. return "Very good match", "👍"
  49. elif nmse < 1e-2:
  50. return "Good match", "👍"
  51. elif nmse < 0.1:
  52. return "Acceptable match", "⚠️"
  53. elif nmse < 1.0:
  54. return "Poor match", "❌"
  55. else:
  56. return "Very poor match (worse than noise)", "❌"
  57. def main():
  58. parser = argparse.ArgumentParser(description='Validate model logits')
  59. parser.add_argument('-m', '--model-path', required=True, help='Path to the model directory')
  60. args = parser.parse_args()
  61. model_name = os.path.basename(args.model_path)
  62. data_dir = Path("data")
  63. pytorch_file = data_dir / f"pytorch-{model_name}.bin"
  64. llamacpp_file = data_dir / f"llamacpp-{model_name}.bin"
  65. print(f"Model name: {model_name}")
  66. print(f"PyTorch logits file: {pytorch_file}")
  67. print(f"llama.cpp logits file: {llamacpp_file}")
  68. reference_file = pytorch_file
  69. test_file = llamacpp_file
  70. print("📊 NMSE Check for Model Comparison")
  71. print("=" * 50)
  72. print(f"Reference (ground truth): {reference_file}")
  73. print(f"Test (to evaluate): {test_file}")
  74. print()
  75. try:
  76. print("Loading reference logits...")
  77. reference = load_logits(reference_file)
  78. print(f" Shape: {reference.shape}, Type: {reference.dtype}")
  79. print("Loading test logits...")
  80. test = load_logits(test_file)
  81. print(f" Shape: {test.shape}, Type: {test.dtype}")
  82. # Check shapes match
  83. if reference.shape != test.shape:
  84. print(f"\n❌ Error: Shape mismatch!")
  85. print(f" Reference: {reference.shape}")
  86. print(f" Test: {test.shape}")
  87. sys.exit(1)
  88. print(f"\n✅ Shapes match: {reference.shape}")
  89. nmse, mse, ref_var = calculate_nmse(reference, test)
  90. # Additional metrics
  91. max_abs_error = np.max(np.abs(test - reference))
  92. mean_abs_error = np.mean(np.abs(test - reference))
  93. # Results
  94. print(f"\n📈 METRICS")
  95. print("=" * 30)
  96. print(f"MSE (Mean Squared Error): {mse:.6e}")
  97. print(f"Reference Variance: {ref_var:.6e}")
  98. print(f"NMSE: {nmse:.6e}")
  99. print(f"Max Absolute Error: {max_abs_error:.6f}")
  100. print(f"Mean Absolute Error: {mean_abs_error:.6f}")
  101. # NMSE in dB (common in signal processing)
  102. if nmse > 0:
  103. nmse_db = 10 * np.log10(nmse)
  104. print(f"NMSE (dB): {nmse_db:.2f} dB")
  105. # Interpretation
  106. interpretation, emoji = interpret_nmse(nmse)
  107. print(f"\n🎯 INTERPRETATION")
  108. print("=" * 30)
  109. print(f"{emoji} {interpretation}")
  110. # Detailed guidance
  111. print(f"\n📋 GUIDANCE")
  112. print("=" * 30)
  113. if nmse < 1e-3:
  114. print("✅ EXCELLENT: Your GGML conversion is working very well!")
  115. print(" The differences are negligible for practical use.")
  116. elif nmse < 1e-2:
  117. print("👍 GOOD: Your GGML conversion is working well.")
  118. print(" Small differences are likely due to precision/quantization.")
  119. elif nmse < 0.1:
  120. print("⚠️ ACCEPTABLE: Conversion is working but with some differences.")
  121. print(" Check if you're using quantization (Q4, Q8, etc.)")
  122. print(" Test generation quality to see if it's acceptable.")
  123. else:
  124. print("❌ PROBLEMATIC: Large differences detected.")
  125. print(" Check your conversion process for potential issues.")
  126. print(" Verify you're using the same model weights.")
  127. # NMSE benchmarks
  128. print(f"\n📚 NMSE BENCHMARKS")
  129. print("=" * 30)
  130. print("< 1e-6: Essentially identical")
  131. print("< 1e-4: Excellent (typical for good conversions)")
  132. print("< 1e-3: Very good")
  133. print("< 1e-2: Good (acceptable for most use cases)")
  134. print("< 0.1: Acceptable (may need verification)")
  135. print("> 1.0: Poor (worse than random)")
  136. # Exit code based on NMSE
  137. if nmse < 1e-2:
  138. print(f"\n✅ RESULT: PASS (NMSE = {nmse:.2e})")
  139. sys.exit(0)
  140. else:
  141. print(f"\n❌ RESULT: NEEDS REVIEW (NMSE = {nmse:.2e})")
  142. sys.exit(1)
  143. except Exception as e:
  144. print(f"❌ Error: {e}")
  145. sys.exit(1)
  146. if __name__ == "__main__":
  147. main()