'Batched inference for the NVIDIA small Conformer models.' import math import torch from torch import nn from torch.nn import functional as F from torch.nn.utils.rnn import pad_sequence from upstream.conformer_ctc_small.nemo_small import NemoSmall from upstream.conformer_ctc_small.nemo_small import rel_pos_emb class BatchedConformer(nn.Module): @staticmethod def feed_forward(x, norm, up, down, input_basis=None, output_basis=None, bias=None): x = norm(x) if input_basis is not None: x = F.linear(x, input_basis) x = down(F.silu(up(x))) return F.linear(x, output_basis, bias) if output_basis is not None else x def macaron(self, x, layer, index, factorized): norm = getattr(layer, f"norm_feed_forward{index}") if hasattr(layer, "shared_macaron"): return layer.shared_macaron(norm(x), index - 1) first = getattr(layer, f"ff{index}_l1") second = getattr(layer, f"ff{index}_l2") if factorized: return self.feed_forward(x, norm, first, second, layer.ff_input_basis.weight, layer.ff_output_basis.weight, getattr(layer, f"ff{index}_bias")) return self.feed_forward(x, norm, first, second) def features(self, waveforms): features = [] for wave in waveforms: wave = F.pad(torch.from_numpy(wave), (0, max(0, 320 - len(wave)))) features.append(self.encoder.pre(wave.to(self.encoder.pre.window.device))) lengths = torch.tensor([len(value) for value in features], device=features[0].device) return pad_sequence(features, batch_first=True), lengths def encode_hidden(self, x, lengths, layer_outputs=None): encoder = self.encoder x = self.subsample(encoder.conv0, x[:, None], (lengths + 1) // 2) lengths = (lengths + 3) // 4 x = self.subsample(encoder.conv2, x, lengths) x = x.permute(0, 2, 1, 3).flatten(2) x = encoder.sub_out(x) * math.sqrt(encoder.d) if encoder.stack == 2: valid = torch.arange(x.size(1), device=x.device)[None] < lengths[:, None] x = x * valid[..., None] x = encoder.stack_frames(x) lengths = (lengths + encoder.stack - 1) // encoder.stack batch, frames, channels = x.shape positions = torch.arange(frames, device=x.device) valid = positions[None, :] < lengths[:, None] relative = (frames - 1) - positions[:, None] + positions[None, :] position_features = rel_pos_emb(frames, channels).to(x.device) factorized = encoder.cfg.get("ff_rank") is not None for layer in encoder.layers: x = x + 0.5 * self.macaron(x, layer, 1, factorized) attention = layer.norm_self_att(x) shape = (batch, frames, layer.h, layer.dk) q = layer.linear_q(attention).reshape(shape).transpose(1, 2) k = layer.linear_k(attention).reshape(shape).transpose(1, 2) v = layer.linear_v(attention).reshape(shape).transpose(1, 2) p = layer.linear_pos(position_features).reshape(-1, layer.h, layer.dk).transpose(0, 1) content = (q + layer.pos_bias_u[:, None, :]) @ k.transpose(-1, -2) position = (q + layer.pos_bias_v[:, None, :]) @ p.transpose(-1, -2) position = position.gather(-1, relative.expand(batch, layer.h, -1, -1)) scores = ((content + position) / math.sqrt(layer.dk)).masked_fill(~valid[:, None, None, :], -torch.inf) context = (scores.softmax(-1) @ v).transpose(1, 2).reshape(batch, frames, channels) x = x + layer.linear_out(context) conv = F.glu(layer.pw1(layer.norm_conv(x)), dim=-1) * valid[..., None] conv = F.silu(layer.dw(conv.transpose(1, 2)).transpose(1, 2)) x = x + layer.pw2(conv) x = x + 0.5 * self.macaron(x, layer, 2, factorized) x = layer.norm_out(x) if layer_outputs is not None: layer_outputs.append(x) return x, lengths @staticmethod def subsample(conv, audio, lengths): result = F.relu(conv(audio)) valid = torch.arange(result.size(2), device=audio.device)[None] < lengths[:, None] return result * valid[:, None, :, None] class ConformerCTC(BatchedConformer): def __init__(self, encoder): super().__init__() self.encoder = encoder self.blank = encoder.vocab if rank := encoder.cfg.get("macaron_delta_rank"): from conformer_macaron_delta import attach_delta_macaron attach_delta_macaron(self, rank) def encode(self, features, lengths, layer_outputs=None): hidden, lengths = self.encode_hidden(features, lengths, layer_outputs) return self.encoder.head(hidden).float().log_softmax(-1), lengths @torch.inference_mode() def greedy(self, features, lengths): logits, lengths = self.encode(features, lengths) paths = logits.argmax(-1) result = [] for path, length in zip(paths, lengths.tolist()): tokens = torch.unique_consecutive(path[:length]) result.append(tokens[tokens != self.blank].tolist()) return result class ConformerRNNT(BatchedConformer): def __init__(self, encoder_cfg, hidden): super().__init__() self.encoder = NemoSmall(cfg=encoder_cfg) del self.encoder.head self.blank = encoder_cfg["vocab"] self.embed = nn.Embedding(self.blank + 1, hidden) self.predictor = nn.LSTM(hidden, hidden, batch_first=True) self.encoder_projection = nn.Linear(self.encoder.d, hidden) self.predictor_projection = nn.Linear(hidden, hidden) self.output = nn.Linear(hidden, self.blank + 1) if rank := encoder_cfg.get("ff_rank"): self.set_ff_rank(rank) if encoder_cfg.get("shared_macaron"): from rnnt_shared_macaron import share_macaron share_macaron(self, initialize=False) def set_ff_rank(self, rank): width = self.encoder.d if not 0 < rank <= width: raise ValueError("Feed-forward factor rank must be within the encoder width") for layer in self.encoder.layers: device = layer.ff1_l1.weight.device layer.ff_input_basis = nn.Linear(width, rank, bias=False, device=device) layer.ff_output_basis = nn.Linear(rank, width, bias=False, device=device) for index in (1, 2): first, second = f"ff{index}_l1", f"ff{index}_l2" units = getattr(layer, first).out_features setattr(layer, first, nn.Linear(rank, units, device=device)) setattr(layer, second, nn.Linear(units, rank, bias=False, device=device)) layer.register_parameter(f"ff{index}_bias", nn.Parameter(torch.zeros(width, device=device))) self.encoder.cfg["ff_rank"] = rank @classmethod @torch.no_grad() def from_nemo(cls, state): state = dict(state) vocab, hidden = state["decoder.prediction.embed.weight"].shape width = state["joint.enc.weight"].shape[1] state["decoder.decoder_layers.0.weight"] = torch.zeros(vocab, width, 1) state["decoder.decoder_layers.0.bias"] = torch.zeros(vocab) encoder = NemoSmall(state) model = cls(encoder.cfg, hidden) del encoder.head model.encoder = encoder model.embed.weight.copy_(state["decoder.prediction.embed.weight"]) model.predictor.load_state_dict({ name: state[f"decoder.prediction.dec_rnn.lstm.{name}"] for name in model.predictor.state_dict() }) for layer, prefix in ((model.encoder_projection, "joint.enc"), (model.predictor_projection, "joint.pred"), (model.output, "joint.joint_net.2")): layer.load_state_dict({name: state[f"{prefix}.{name}"] for name in layer.state_dict()}) return model def encode(self, x, lengths, layer_outputs=None): hidden, lengths = self.encode_hidden(x, lengths, layer_outputs) return self.encoder_projection(hidden), lengths def predict(self, labels): tokens = F.pad(self.embed(labels), (0, 0, 1, 0)) prediction, _ = self.predictor(tokens) return self.predictor_projection(prediction) @torch.inference_mode() def greedy(self, features, lengths, max_symbols=5, allowed=None): encoded, lengths = self.encode(features, lengths) batch, frames, hidden = encoded.shape first, state = self.predictor(encoded.new_zeros(batch, 1, hidden)) prediction = self.predictor_projection(first[:, 0]) tokens = torch.full((batch, frames * max_symbols), self.blank, dtype=torch.long, device=encoded.device) for frame in range(frames): active = lengths > frame for symbol in range(max_symbols): logits = self.output(F.relu(encoded[:, frame] + prediction)) if allowed is not None: logits = logits.masked_fill(~allowed, -torch.inf) code = logits.argmax(-1) active = active & (code != self.blank) if not active.any(): break tokens[:, frame * max_symbols + symbol] = torch.where(active, code, self.blank) output, next_state = self.predictor(self.embed(code)[:, None], state) state = tuple(torch.where(active[None, :, None], new, old) for new, old in zip(next_state, state)) new_prediction = self.predictor_projection(output[:, 0]) prediction = torch.where(active[:, None], new_prediction, prediction) return [[code for code in row if code != self.blank] for row in tokens.tolist()]