Download export_coreml_stream.py from Reza2kn/Shenava-Rizeh-v1.5-CoreML-iOS15-fp16: direct link, hf CLI and curl.
- Browser
- Download file 3.22 kB
-
https://huggingface.co/Reza2kn/Shenava-Rizeh-v1.5-CoreML-iOS15-fp16/resolve/main/export_coreml_stream.py
- Command line
-
hf download hf://Reza2kn/Shenava-Rizeh-v1.5-CoreML-iOS15-fp16/export_coreml_stream.py
-
curl -L -o export_coreml_stream.py https://huggingface.co/Reza2kn/Shenava-Rizeh-v1.5-CoreML-iOS15-fp16/resolve/main/export_coreml_stream.py
3.22 kB
| """CoreML streaming step (iOS15 NeuralNetwork, fp16 weights) of Shenava Rizeh v1.5: one 320 ms chunk in -> encoder frames + next caches out. | |
| Decoder/joiner: same as the fp16 package but converted to neuralnetwork too. usage: export_coreml_stream.py model.tzf outdir [chunk] [left]""" | |
| import sys,os,json,numpy as np,torch,torch.nn as nn,coremltools as ct | |
| tzf,out=sys.argv[1],sys.argv[2];CH=int(sys.argv[3]) if len(sys.argv)>3 else 16;LC=int(sys.argv[4]) if len(sys.argv)>4 else 128 | |
| OUTDIR=out;os.makedirs(out,exist_ok=True) | |
| src=open(os.path.join(os.path.dirname(os.path.abspath(__file__)),'export_onnx_streaming.py')).read().split("f=f'{out}/encoder.onnx'")[0] | |
| sys.argv=['x',tzf,'/tmp/_unused_stream',str(CH),str(LC)];exec(src) | |
| E.encoder.__class__.forward=E.encoder.__class__.streaming_forward | |
| st=E.get_init_states();names=[] | |
| for i in range((len(st)-2)//6): | |
| names+= [f'{k}_{i}' for k in ['cached_key','cached_nonlin_attn','cached_val1','cached_val2','cached_conv1','cached_conv2']] | |
| names+=['embed_states','processed_lens'] | |
| class Flat(nn.Module): | |
| def __init__(s,E): super().__init__();s.E=E | |
| def forward(s,x,*states): | |
| eo,ns=s.E(x,list(states));return (eo,*ns) | |
| F=Flat(E).eval();T=CH*2+13;x=torch.rand(1,T,80) | |
| st=[t.to(torch.int32) if t.dtype==torch.int64 else t for t in st] | |
| ref=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_utils | |
| ml16=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), | |
| 'inputs':{n:list(t.shape) for n,t in zip(['x']+names,[x]+st)},'state_dtypes':{n:str(t.dtype) for n,t in zip(names,st)}},open(fn.replace('.mlmodel','_manifest.json'),'w'),indent=1) | |
| print('saved',fn,ref[0].shape) | |