tiny-dictation-en / runtime /cochlear_frontend.py
Hansda's picture
Release Tiny Dictation English and complete benchmarks
531b9c5 verified
Raw History Blame Contribute Delete
7.32 kB
'Gammatone band envelopes and a small residual projection for ASR features.'
import math
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
SAMPLE_RATE = 16_000
FEATURE_HOP = 160
BANDS = 80
ENVELOPE_STRIDE = 8
def center_frequencies():
"""Space the channels equally on the ERB-rate scale, from 50 Hz to 7.8 kHz."""
endpoints = 21.4 * torch.log10(1 + 0.00437 * torch.tensor([50.0, 7800.0]))
positions = torch.linspace(endpoints[0], endpoints[1], BANDS)
return (10 ** (positions / 21.4) - 1) / 0.00437
def filter_bank(centers, width):
# Align the peak of each fourth-order gammatone's envelope with the output timestamp.
damping = 2 * math.pi * 1.019 * (24.7 + 0.108 * centers[:, None])
offsets = torch.arange(width, dtype=torch.float32) - width // 2
time = 3 / damping - offsets[None, :] / SAMPLE_RATE
envelope = time.clamp_min(0).pow(3) * (-damping * time.clamp_min(0)).exp()
phase = 2 * math.pi * centers[:, None] * time
envelope = envelope / envelope.sum(-1, keepdim=True)
return torch.cat((envelope * phase.cos(), envelope * phase.sin()))[:, None, :].contiguous()
def running_energy(values, width):
"""Return the trailing average using only frames that exist at the start."""
summed = F.pad(values.cumsum(-1), (1, 0))
stop = torch.arange(1, values.size(-1) + 1, device=values.device)
start = (stop - width).clamp_min(0)
return (summed.index_select(-1, stop) - summed.index_select(-1, start)) / (stop - start)
def normalize_channels(values, lengths):
valid = torch.arange(values.size(-1), device=values.device)[None, None, :] < lengths[:, None, None]
counts = lengths[:, None, None].clamp_min(1)
mean = (values * valid).sum(-1, keepdim=True) / counts
centered = (values - mean) * valid
variance = centered.square().sum(-1, keepdim=True) / (counts - 1).clamp_min(1)
return centered / (variance.sqrt() + 1e-5)
class CochlearFeatures(nn.Module):
def __init__(self):
super().__init__()
# Low bands ring longer. Use shorter kernels for higher bands.
groups = zip(center_frequencies().split(20), (1537, 1025, 513, 257))
for index, (centers, width) in enumerate(groups):
self.register_buffer(f"filters_{index}", filter_bank(centers, width), persistent=False)
@torch.no_grad()
def power(self, waveform, frames):
samples_per_frame = FEATURE_HOP // ENVELOPE_STRIDE
pad = (samples_per_frame // 2) * ENVELOPE_STRIDE
waveform = F.pad(waveform[:, None].float(), (pad, 0))
powers = []
for filters in self.buffers():
response = F.conv1d(waveform, filters, padding=filters.size(-1) // 2, stride=ENVELOPE_STRIDE)
real, imag = response.chunk(2, dim=1)
power = real.square() + imag.square()
average = F.avg_pool1d(power, samples_per_frame, stride=samples_per_frame)
powers.append(average[..., :frames])
return torch.cat(powers, dim=1)
def forward(self, waveform, lengths, frames):
power = self.power(waveform, frames)
fast = (power + 1e-8).log()
slow = (running_energy(power, 8).clamp_min(0) + 1e-8).log()
return torch.cat((normalize_channels(fast, lengths), normalize_channels(fast - slow, lengths)), dim=1)
def stored_precision(value):
return value.half().float().detach() + (value - value.detach())
def stored_linear(inputs, layer):
bias = stored_precision(layer.bias) if layer.bias is not None else None
return F.linear(inputs, stored_precision(layer.weight), bias)
class FrequencyAttention(nn.Module):
"""Reweight each band's energy and contrast using the other bands in a 40 ms block."""
def __init__(self):
super().__init__()
self.width = 32
self.heads = 4
self.embed = nn.Linear(2, self.width)
self.band_positions = nn.Parameter(torch.empty(BANDS, self.width))
nn.init.normal_(self.band_positions, std=0.1)
self.qkv = nn.Linear(self.width, 3 * self.width, bias=False)
self.readout = nn.Linear(self.width, 2)
nn.init.zeros_(self.readout.weight)
nn.init.zeros_(self.readout.bias)
def forward(self, features, lengths):
batch, _, frames = features.shape
block = 4
pad = -frames % block
counts = (lengths[:, None] - block * torch.arange((frames + 3) // block, device=features.device)).clamp(1, block)
pooled = F.pad(features, (0, pad)).reshape(batch, 2, BANDS, -1, block).sum(-1)
tokens = (pooled / counts[:, None, None, :]).permute(0, 3, 2, 1).reshape(-1, BANDS, 2)
embedded = stored_linear(tokens, self.embed) + stored_precision(self.band_positions)
qkv = stored_linear(embedded, self.qkv).reshape(-1, BANDS, 3, self.heads, self.width // self.heads)
query, key, value = qkv.permute(2, 0, 3, 1, 4).unbind(0)
if features.is_cuda:
attended = F.scaled_dot_product_attention(query.bfloat16(), key.bfloat16(), value.bfloat16()).float()
else:
attended = F.scaled_dot_product_attention(query, key, value)
context = attended.transpose(1, 2).reshape(-1, BANDS, self.width)
gains = 2 * stored_linear(context, self.readout).sigmoid()
gains = gains.reshape(batch, -1, BANDS, 2).permute(0, 3, 2, 1).reshape(batch, 2 * BANDS, -1)
return features * gains.repeat_interleave(block, dim=-1)[..., :frames]
class FrontendProjection(nn.Module):
"""A zero-initialized residual adapter with the same size for both feature experiments."""
def __init__(self, mode):
super().__init__()
if mode not in ("mel", "cochlear", "cochlear-attention"):
raise ValueError(f"Unknown front end {mode}")
self.mode = mode
self.cochlear = CochlearFeatures() if mode != "mel" else None
self.attention = FrequencyAttention() if mode == "cochlear-attention" else None
self.projection = nn.Conv1d(2 * BANDS, BANDS, 1)
nn.init.zeros_(self.projection.weight)
nn.init.zeros_(self.projection.bias)
@torch.no_grad()
def load_parameters(self, data):
weights = np.frombuffer(data, dtype="<f2").astype(np.float32)
if len(weights) != sum(parameter.numel() for parameter in self.parameters()):
raise ValueError("Unexpected front-end weights")
offset = 0
for parameter in self.parameters():
end = offset + parameter.numel()
parameter.copy_(torch.from_numpy(weights[offset:end]).reshape(parameter.shape))
offset = end
def forward(self, mel, lengths, waveform=None):
if self.cochlear is None:
contrast = normalize_channels(mel - running_energy(mel, 8), lengths)
auxiliary = torch.cat((mel, contrast), dim=1)
else:
auxiliary = self.cochlear(waveform, lengths, mel.size(-1))
if self.attention is not None:
auxiliary = self.attention(auxiliary, lengths)
weight = stored_precision(self.projection.weight)
bias = stored_precision(self.projection.bias)
delta = F.conv1d(auxiliary, weight, bias)
valid = torch.arange(mel.size(-1), device=mel.device)[None, None, :] < lengths[:, None, None]
return mel + delta * valid