File size: 9,818 Bytes
531b9c5 | 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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | '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()]
|