File size: 6,330 Bytes
11ec365
 
 
 
 
 
 
 
 
 
 
 
 
 
392a164
 
 
 
 
 
 
 
11ec365
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
392a164
 
 
11ec365
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"""CoreML export of Shenava Rizeh v1.5: encoder (fbank in, encoder_out projected), decoder, joiner. fp16, iOS16+ mlprogram (and iOS15 neuralnetwork for decoder/joiner)."""
import sys,os,torch,torch.nn as nn,numpy as np,coremltools as ct
H=os.path.dirname(os.path.abspath(__file__));sys.path.insert(0,H)
from build_model import load
from scaling_converter import convert_scaled_to_non_scaled
tzf,out=sys.argv[1],sys.argv[2];os.makedirs(out,exist_ok=True)
m,d,*_=load(tzf);m.eval();torch.set_grad_enabled(False)
for x in m.modules():
    if hasattr(x,'batch_count'): x.batch_count=1e6
LANG=list(d['text'].values()).index('fa')
_js=torch.jit.script;torch.jit.script=lambda q,*a,**k:q
convert_scaled_to_non_scaled(m,inplace=True,is_onnx=True)
torch.jit.script=_js
m.encoder.chunk_size=(-1,);m.encoder.left_context_frames=(-1,)
FQ=__import__('os').environ.get('FQ')  # weight-only int4 on every nn.Linear, AFTER scaled->non-scaled conversion so the grid survives export: -8..7 codes, scale=max(-min/8,max/7), blocks of 32 along the input dim
if FQ:
    for mod in m.modules():
        if (isinstance(mod,nn.Linear) or type(mod).__name__=='ActivationDropoutAndLinear') and mod.weight.numel()>=2048 and mod.weight.shape[1]%32==0:
            w=mod.weight.data;g=w.reshape(w.shape[0],-1,32)
            s=torch.maximum(-g.amin(-1,keepdim=True)/8,g.amax(-1,keepdim=True)/7).half().float();s=torch.where(s>0,s,torch.ones_like(s));q=torch.clamp(torch.round(g/s),-8,7)
            mod.weight.data=(q*s).reshape(w.shape)

_G={}
_DS=[type(q) for q in m.modules() if type(q).__name__=='SimpleDownsample'][0];_dso=_DS.forward
def _dsf(self,src):
    # src (T,B,C) at embed frame rate: replace frames past the true length with the last valid frame (= what an unpadded input sees)
    xl=_G['xl'];T=src.shape[0];ar=torch.arange(T)[:,None]
    valid=(ar<xl[None,:]).to(src.dtype)[...,None]; last=(src*(ar==(xl-1)[None,:]).to(src.dtype)[...,None]).sum(0,keepdim=True)
    src=src*valid+last*(1-valid)  # gather-free (CoreML-friendly)
    return _dso(self,src)
_DS.forward=_dsf
from scaling_converter import NonStreamingChunkCausalDepthwiseConv1d as _NS
def _nsf(self,x,chunk_size:int=-1):
    # length-aware version: the chunk edge scales must sit at the TRUE sequence end, not at the padded end
    B,C,S=x.shape;K=self.kernel_size;lp=K//2
    xp=torch.nn.functional.pad(x,(lp,0));xc=self.causal_conv(xp[...,:lp+S]);xk=self.chunkwise_conv(xp[...,lp:])
    ds=max(1,round(int(_G['T'])/int(S)));L=(_G['xl']+ds-1)//ds  # (B,)
    p=torch.arange(S)
    le=self.chunkwise_conv_scale[0];re_=self.chunkwise_conv_scale[1]   # (C,K)
    li=torch.clamp(p,max=K-1);lv=(p<K).to(x.dtype)
    left=le[:,li]*lv                                                     # (C,S)
    j=p[None,:]-(L[:,None]-K)                                            # (B,S)
    oh=(j[...,None]==torch.arange(K)[None,None,:]).to(x.dtype)            # (B,S,K) one-hot, zero outside the edge window
    right=torch.einsum('ck,bsk->bcs',re_,oh)
    return xk*(1.0+left[None]+right)+xc
_NS.forward=_nsf
class Enc(nn.Module):
    def __init__(s,m): super().__init__();s.embed=m.encoder_embed;s.enc=m.encoder;s.proj=m.joiner.encoder_proj;s.register_buffer('lv',m.lang_embed.weight[LANG].clone())
    def forward(s,x,x_lens):
        xl=x_lens.to(torch.int64)
        em=s.embed;xl=(xl-7)//2
        h=em.conv(x.unsqueeze(1))
        h=h*(torch.arange(h.shape[2])[None,None,:,None]<xl[:,None,None,None]).to(h.dtype)  # zero padded frames so ConvNeXt edge matches unpadded input
        h=em.convnext(h);b,c,t,f=h.size();x=em.out_norm(em.out_whiten(em.out(h.transpose(1,2).reshape(b,t,c*f))))
        x=x+s.lv;_G["xl"]=xl;_G["T"]=x.shape[1]
        mask=torch.arange(x.shape[1])[None,:]>=xl[:,None]
        e,el=s.enc(x.permute(1,0,2),xl,mask)
        return s.proj(e.permute(1,0,2)),el.to(torch.int32)
class Dec(nn.Module):
    def __init__(s,m): super().__init__();s.dec=m.decoder;s.proj=m.joiner.decoder_proj
    def forward(s,y): return s.proj(s.dec(y,need_pad=False).squeeze(1))
class Join(nn.Module):
    def __init__(s,m): super().__init__();s.lin=m.joiner.output_linear
    def forward(s,e,dd): return s.lin(torch.tanh(e+dd))
class PosConst(nn.Module):
    def __init__(s,inner): super().__init__();s.inner=inner;s.register_buffer('pe',None,persistent=False);s.L=-1
    def forward(s,x,left_context_len:int=0):
        if s.pe is None: s.pe=s.inner(x,left_context_len).detach().clone();s.L=int(x.shape[0])
        assert int(x.shape[0])==s.L
        return s.pe
_n=0
for q in list(m.modules()):
    if hasattr(q,'encoder_pos'): q.encoder_pos=PosConst(q.encoder_pos);_n+=1
print('wrapped pos',_n)
E=Enc(m).eval();TF=3000
x=torch.randn(1,TF,80);xl=torch.tensor([TF],dtype=torch.int32);ref=E(x,xl)[0];tr=torch.jit.trace(E,(x,xl))
# reductions/softmax/normalisation stay fp32: in pure fp16 the Neural Engine path drifts ~12% (3/8 clips decode differently); mixed is 0.08% on CPU, GPU and ANE
KEEP={'reduce_mean','reduce_sum','reduce_max','softmax','pow','rsqrt','sqrt','real_div','exp','log','reduce_sum_square','reduce_l2_norm'}
em=ct.convert(tr,inputs=[ct.TensorType(name='x',shape=(1,TF,80)),ct.TensorType(name='x_lens',shape=(1,),dtype=np.int32)],outputs=[ct.TensorType(name='encoder_out'),ct.TensorType(name='encoder_out_lens')],compute_precision=ct.transform.FP16ComputePrecision(op_selector=lambda op: op.op_type not in KEEP),minimum_deployment_target=ct.target.iOS16,convert_to='mlprogram')
em.save(f'{out}/encoder.mlpackage');print('encoder ok',ref.shape)
D=Dec(m).eval();y=torch.zeros(1,2,dtype=torch.int32)
dm=ct.convert(torch.jit.trace(D,y.long()),inputs=[ct.TensorType(name='y',shape=(1,2),dtype=np.int32)],outputs=[ct.TensorType(name='decoder_out')],compute_precision=ct.precision.FLOAT16,minimum_deployment_target=ct.target.iOS16,convert_to='mlprogram')
dm.save(f'{out}/decoder.mlpackage');print('decoder ok')
J=Join(m).eval();a=torch.rand(1,512)
jm=ct.convert(torch.jit.trace(J,(a,a)),inputs=[ct.TensorType(name='encoder_out',shape=(1,512)),ct.TensorType(name='decoder_out',shape=(1,512))],outputs=[ct.TensorType(name='logit')],compute_precision=ct.precision.FLOAT16,minimum_deployment_target=ct.target.iOS16,convert_to='mlprogram')
jm.save(f'{out}/joiner.mlpackage');print('joiner ok')
np.save(f'{out}/ref_x.npy',x.numpy());np.save(f'{out}/ref_encoder_out.npy',ref.numpy())