Add int8 NeuralNetwork encoder and iOS18 int4 streaming encoder
Browse filesFiles changed (8)
- README.md+16-7
- cmq2.pyAdded+20
- export_coreml_stream.py+6
- ios18/shenava_rizeh_v1_5_encoder_streaming_c16_l128_ios18_int4.mlpackage/Data/com.apple.CoreML/model.mlmodelAdded+3
- ios18/shenava_rizeh_v1_5_encoder_streaming_c16_l128_ios18_int4.mlpackage/Data/com.apple.CoreML/weights/weight.binAdded+3
- ios18/shenava_rizeh_v1_5_encoder_streaming_c16_l128_ios18_int4.mlpackage/Manifest.jsonAdded+18
- run_coreml_stream.py+1-1
- shenava_rizeh_v1_5_encoder_streaming_c16_l128_ios15_int8.mlmodelAdded+3
41 unmodified lines424344454647484950514546474849505152535455565758596061626341 unmodified lines
## Files
- `shenava_rizeh_v1_5_encoder_streaming_c16_l128_ios15_fp16.mlmodel`: encoder step. - Inputs: `x` (1, 45, 80) fbank plus 92 cache tensors. - Outputs: `encoder_out` (1, 8, 512) plus `new_<cache>` for each cache.- `..._manifest.json`: every input shape. Start all caches at zero; `processed_lens` is int32.- `shenava_rizeh_v1_5_decoder_ios15_fp16.mlmodel`: `y` int32 (1, 2) → `decoder_out` (1, 512).- `shenava_rizeh_v1_5_joiner_ios15_fp16.mlmodel`: (`encoder_out` (1, 512), `decoder_out` (1, 512)) → `logit` (1, 2080).- `tokens.txt`, `run_coreml_stream.py`, `reference/`, and the export scripts.| Encoder step | Format / target | Size | Error vs onnxruntime fp32 (8 clips, every chunk) | Tokens identical | M2 ms per 320 ms step (CPU / GPU / ALL) ||---|---|---|---|---|---|| `shenava_rizeh_v1_5_encoder_streaming_c16_l128_ios15_fp16.mlmodel` | NeuralNetwork, iOS 15+ | 109 MB | 0.08 % | 8/8 | 15.6 / 16.4 / 16.5 || `shenava_rizeh_v1_5_encoder_streaming_c16_l128_ios15_int8.mlmodel` | NeuralNetwork, iOS 15+, int8 weights | 56 MB | 1.5 % | 8/8 | 16.0 / 16.7 / 16.7 || `ios18/shenava_rizeh_v1_5_encoder_streaming_c16_l128_ios18_int4.mlpackage` | ML Program, iOS 18+, int4 weights (blocks of 32) | 34 MB | see note | n/a | **7.4** / 18.8 / 18.5 |
**int4 note:** on the M2 this package reproduces a PyTorch model with the same int4 weights to within 0.1 %. That model's streaming score on the held-out half is **TT 5.37**, vs 5.31 for fp32 (official TT, no LM). The NeuralNetwork format has no block-wise int4, so int4 needs iOS 18.
**Other files:**
- `..._manifest.json`: input shapes. All 92 caches start at zero; `processed_lens` is int32.- The decoder and joiner (`*_ios15_fp16.mlmodel`) are shared by every encoder.- Decoder: `y` int32 (1, 2) → `decoder_out` (1, 512).- Joiner: (`encoder_out` (1, 512), `decoder_out` (1, 512)) → `logit` (1, 2080).- Encoder step I/O: `x` (1, 45, 80) + caches → `encoder_out` (1, 8, 512) + `new_<cache>`.- `tokens.txt`, `run_coreml_stream.py [encoder file]`, `reference/`, `export_coreml_stream.py` (`MLPROGRAM=1 FQ=1` gives the iOS 18 int4 base), `cmq2.py`.
## Streaming loop
1234567891011121314151617181920"""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 ctoimport coremltools.optimize._utils as Ufrom coremltools.converters.mil.mil import types_orig=U.quantize_weight_by_dtypedef 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=exact4import coremltools.optimize.coreml._quantization_passes as QPif hasattr(QP,'quantize_weight_by_dtype'): QP.quantize_weight_by_dtype=exact4import syssrc,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)18 unmodified lines19202122232425262728293031323318 unmodified linesref=F(x,*st);tr=torch.jit.trace(F,(x,*st))inputs=[ct.TensorType(name='x',shape=(1,T,80))]+[ct.TensorType(name=n,shape=tuple(t.shape),dtype=np.int32 if t.dtype==torch.int32 else np.float32) for n,t in zip(names,st)]outputs=[ct.TensorType(name='encoder_out')]+[ct.TensorType(name='new_'+n) for n in names]if __import__('os').environ.get('MLPROGRAM'): KEEP={'reduce_mean','reduce_sum','reduce_max','softmax','pow','rsqrt','sqrt','real_div','exp','log','reduce_sum_square','reduce_l2_norm'} mp=ct.convert(tr,inputs=inputs,outputs=outputs,convert_to='mlprogram',minimum_deployment_target=ct.target.iOS18,compute_precision=ct.transform.FP16ComputePrecision(op_selector=lambda op: op.op_type not in KEEP)) mp.save(f'{OUTDIR}/stream_mlprogram_ios18_fp16.mlpackage');print('saved mlprogram');sys.exit(0)ml=ct.convert(tr,inputs=inputs,outputs=outputs,convert_to='neuralnetwork',minimum_deployment_target=ct.target.iOS14)from coremltools.models.neural_network import quantization_utilsml16=quantization_utils.quantize_weights(ml,nbits=16)for nb,mode,tag in [(8,'linear','int8'),(4,'kmeans','int4lut')]: quantization_utils.quantize_weights(ml,nbits=nb,quantization_mode=mode).save(f'{OUTDIR}/shenava_rizeh_v1_5_encoder_streaming_c{CH}_l{LC}_ios15_{tag}.mlmodel');print('saved',tag,flush=True)fn=f'{OUTDIR}/shenava_rizeh_v1_5_encoder_streaming_c{CH}_l{LC}_ios15_fp16.mlmodel';ml16.save(fn)json.dump({'format':'CoreML NeuralNetwork (iOS14 target, runs on iOS15+) fp16-weight cache-aware streaming Zipformer2 encoder step','chunk_frames_after_subsampling':CH,'left_context_frames':LC, 'feature_frames_per_step':T,'feature_shift_per_step':CH*2,'ms_per_step':CH*2*10,'encoder_out':list(ref[0].shape),123version https://git-lfs.github.com/spec/v1oid sha256:5c08dc67578952605a444cf6b720184f6ffb421705e0b9ce4859d880acd6c81fsize 1112178123version https://git-lfs.github.com/spec/v1oid sha256:21b52d047834924196c293ba45dd14c965b5aa09ff3d9c67439605a774b26ee8size 33648384123456789101112131415161718{ "fileFormatVersion": "1.0.0", "itemInfoEntries": { "342fa6ea-f688-4be1-a9ad-88c42b4faf68": { "author": "com.apple.CoreML", "description": "CoreML Model Weights", "name": "weights", "path": "com.apple.CoreML/weights" }, "cf6ea933-48c7-4bc5-a743-17aac2fb223d": { "author": "com.apple.CoreML", "description": "CoreML Model Specification", "name": "model.mlmodel", "path": "com.apple.CoreML/model.mlmodel" } }, "rootModelIdentifier": "cf6ea933-48c7-4bc5-a743-17aac2fb223d"}1 unmodified line234556781 unmodified lineFeeds the stored reference chunks (45 fbank frames each, hop 32 = 320 ms) through the encoder step, threading all caches,greedy RNN-T with the English block masked; prints whether tokens match the onnxruntime reference."""import json,glob,numpy as np,coremltools as ctenc=ct.models.MLModel(glob.glob('*encoder_streaming*.mlmodel')[0]);dec=ct.models.MLModel(glob.glob('*decoder*.mlmodel')[0]);joi=ct.models.MLModel(glob.glob('*joiner*.mlmodel')[0])import sys;enc=ct.models.MLModel(sys.argv[1] if len(sys.argv)>1 else glob.glob('*encoder_streaming*_fp16.mlmodel')[0]);dec=ct.models.MLModel(glob.glob('*decoder*.mlmodel')[0]);joi=ct.models.MLModel(glob.glob('*joiner*.mlmodel')[0])man=json.load(open(glob.glob('*_manifest.json')[0]));exp=json.load(open('reference/expected.json',encoding='utf-8'))toks=[l.rstrip('\n').rsplit(' ',1)[0] for l in open('tokens.txt',encoding='utf-8')]names=[k for k in man['inputs'] if k!='x']123version https://git-lfs.github.com/spec/v1oid sha256:2ff5b5d589be237f9e421444df509f26b47727e4818af7aa58b2a04a071b8036size 58215188README.md+16-7
cmq2.pyAdded+20
export_coreml_stream.py+6
ios18/shenava_rizeh_v1_5_encoder_streaming_c16_l128_ios18_int4.mlpackage/Data/com.apple.CoreML/model.mlmodelAdded+3
ios18/shenava_rizeh_v1_5_encoder_streaming_c16_l128_ios18_int4.mlpackage/Data/com.apple.CoreML/weights/weight.binAdded+3
ios18/shenava_rizeh_v1_5_encoder_streaming_c16_l128_ios18_int4.mlpackage/Manifest.jsonAdded+18
run_coreml_stream.py+1-1
shenava_rizeh_v1_5_encoder_streaming_c16_l128_ios15_int8.mlmodelAdded+3