"""Build an icefall Zipformer2 transducer matching a tinyasr .tzf and load its dequantized weights.""" import sys,os,torch,torch.nn as nn,numpy as np H=os.path.dirname(os.path.abspath(__file__)) sys.path[:0]=[H+'/shim',H+'/icefall',H] from tzf_io import read_tzf from zipformer import Zipformer2 from subsampling import Conv2dSubsampling from decoder import Decoder from joiner import Joiner def tup(cfg,k,n): return tuple(cfg[f'{k}.{i}'] for i in range(n)) class TinyRNNT(nn.Module): def __init__(s,cfg): super().__init__();n=cfg['n_stacks'];ed=tup(cfg,'encoder_dim',n) s.encoder_embed=Conv2dSubsampling(in_channels=80,out_channels=ed[0],dropout=0.1) s.encoder=Zipformer2(output_downsampling_factor=2,downsampling_factor=tup(cfg,'downsampling_factor',n),encoder_dim=ed, num_encoder_layers=tup(cfg,'num_encoder_layers',n),encoder_unmasked_dim=tuple(min(d,256) if i else d for i,d in enumerate(ed)), query_head_dim=tup(cfg,'query_head_dim',n),pos_head_dim=tup(cfg,'pos_head_dim',n),value_head_dim=tup(cfg,'value_head_dim',n), num_heads=tup(cfg,'num_heads',n),feedforward_dim=tup(cfg,'feedforward_dim',n),cnn_module_kernel=tup(cfg,'cnn_module_kernel',n), pos_dim=cfg['pos_dim'],dropout=0.1,warmup_batches=4000.0,causal=True,chunk_size=(cfg['chunk'],),left_context_frames=(cfg['left_context'],)) s.decoder=Decoder(vocab_size=cfg['vocab'],decoder_dim=cfg['decoder_dim'],blank_id=cfg['blank'],context_size=cfg['context']) s.joiner=Joiner(encoder_dim=max(ed),decoder_dim=cfg['decoder_dim'],joiner_dim=cfg['joiner_dim'],vocab_size=cfg['vocab']) s.lang_embed=nn.Embedding(16,ed[0]) def encode(s,feats,lens,lang,chunk_size=-1): x,xl=s.encoder_embed(feats,lens) x=x+s.lang_embed.weight[lang] s.encoder.chunk_size=(chunk_size,); x=x.permute(1,0,2);mask=torch.arange(x.shape[0],device=x.device)[None,:]>=xl[:,None] e,el=s.encoder(x,xl,mask);return e.permute(1,0,2),el def load(tzf,device='cpu'): d=read_tzf(tzf);m=TinyRNNT(d['cfg']) sd=m.state_dict();T=d['tensors'];miss=[];shape=[] for k,v in sd.items(): if k in T: w=torch.from_numpy(T[k]['f32']).reshape(v.shape) if T[k]['f32'].size==v.numel() else None if w is None: shape.append((k,tuple(v.shape),T[k]['dims']));continue sd[k]=w else: miss.append(k) extra=[k for k in T if k not in sd] m.load_state_dict(sd);m.eval().to(device) return m,d,miss,extra,shape if __name__=='__main__': m,d,miss,extra,shape=load(sys.argv[1]) print('missing in tzf',len(miss),miss[:20]);print('extra in tzf',extra);print('shape mismatch',shape) print('params',sum(p.numel() for p in m.parameters()))