"""int4 Core ML weights that land exactly on Shenava v1.5's own int4 grid (tzf: symmetric codes -8..7, groups of 64 along the input dim). coremltools' symmetric mode uses absmax/7 (codes -7..7) and so re-rounds already-quantized weights; patch the scale to max(-min/8, max/7).""" import numpy as np,coremltools as ct,coremltools.optimize.coreml as cto import coremltools.optimize._utils as U from coremltools.converters.mil.mil import types _orig=U.quantize_weight_by_dtype def exact4(weight,axes,dtype,mode): if mode=='LINEAR_SYMMETRIC' and types.is_int(dtype) and not dtype.is_unsigned() and dtype.get_bitwidth()==4: w=weight.astype(np.float32);mn=np.amin(w,axis=axes,keepdims=True);mx=np.amax(w,axis=axes,keepdims=True) s=np.maximum(np.maximum(-mn/8.0,mx/7.0),1e-12);q=np.clip(np.round(w/s),-8,7) return q,s.astype(weight.dtype).squeeze(),None return _orig(weight,axes,dtype,mode) U.quantize_weight_by_dtype=exact4 import coremltools.optimize.coreml._quantization_passes as QP if hasattr(QP,'quantize_weight_by_dtype'): QP.quantize_weight_by_dtype=exact4 import sys src,dst=sys.argv[1],sys.argv[2] ml=ct.models.MLModel(src,skip_model_load=True) cfg=cto.OpLinearQuantizerConfig(mode='linear_symmetric',dtype='int4',granularity='per_block',block_size=int(__import__("os").environ.get("BLK","32")),weight_threshold=2048) cto.linear_quantize_weights(ml,cto.OptimizationConfig(op_type_configs={'linear':cfg})).save(dst);print('saved',dst)