import tensorflow as tf import numpy as np import argparse import os def quantize_v4s_scale_int8(model_path, calib_path, output_path): """ Quantization script for MobileNetV4-Small (Scale Metrology) - INT8. Optimized for 1024x1024 resolution. """ print(f"Loading calibration data: {calib_path}") # Load NCHW [100, 3, 1024, 1024] and transpose to NHWC [100, 1024, 1024, 3] calib_data = np.load(calib_path).astype(np.float32).transpose(0, 2, 3, 1) def representative_dataset(): for i in range(len(calib_data)): yield [calib_data[i:i+1]] converter = tf.lite.TFLiteConverter.from_saved_model(model_path) converter.representative_dataset = representative_dataset converter.optimizations = [tf.lite.Optimize.DEFAULT] # Force Full Integer I/O converter.inference_input_type = tf.int8 converter.inference_output_type = tf.int8 converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8] # 100% NPU Hardware Compliance (Exynos Eden NCP 24/25, Google Tensor, Qualcomm Hexagon) # FullyConnected layers require per-tensor quantization (TENSOR_QUANT8_ASYMM_SIGNED) if hasattr(converter, "_experimental_disable_per_channel_quantization_for_dense_layers"): converter._experimental_disable_per_channel_quantization_for_dense_layers = True print("Converting MobileNetV4-Small Scale to INT8 TFLite (100% NPU compatible)...") tflite_model = converter.convert() with open(output_path, "wb") as f: f.write(tflite_model) print(f"Successfully saved INT8 model to {output_path}") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Lithotheque V4S Scale INT8 Quantizer") parser.add_argument("--model", type=str, required=True, help="Path to FP32 SavedModel") parser.add_argument("--calib", type=str, default="calib_echelle.npy", help="Path to calibration .npy") parser.add_argument("--out", type=str, default="echelle_v4s_int8.tflite", help="Output path") args = parser.parse_args() if os.path.exists(args.model): quantize_v4s_scale_int8(args.model, args.calib, args.out) else: print(f"Error: {args.model} not found.")