mirror of
https://github.com/k2-fsa/icefall.git
synced 2025-08-09 01:52:41 +00:00
Merge 00ed2b7567783a4e9565f06a94342b2d0e5f6d38 into 34fc1fdf0d8ff520e2bb18267d046ca207c78ef9
This commit is contained in:
commit
5959fe25e0
@ -0,0 +1 @@
|
|||||||
|
../pruned_transducer_stateless2/asr_datamodule.py
|
2402
egs/librispeech/ASR/pruned_transducer_stateless9/beam_search.py
Normal file
2402
egs/librispeech/ASR/pruned_transducer_stateless9/beam_search.py
Normal file
File diff suppressed because it is too large
Load Diff
1017
egs/librispeech/ASR/pruned_transducer_stateless9/decode.py
Executable file
1017
egs/librispeech/ASR/pruned_transducer_stateless9/decode.py
Executable file
File diff suppressed because it is too large
Load Diff
141
egs/librispeech/ASR/pruned_transducer_stateless9/decoder.py
Normal file
141
egs/librispeech/ASR/pruned_transducer_stateless9/decoder.py
Normal file
@ -0,0 +1,141 @@
|
|||||||
|
# Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang)
|
||||||
|
#
|
||||||
|
# See ../../../../LICENSE for clarification regarding multiple authors
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
|
||||||
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
import torch.nn.functional as F
|
||||||
|
|
||||||
|
|
||||||
|
class Decoder(nn.Module):
|
||||||
|
"""This class modifies the stateless decoder from the following paper:
|
||||||
|
|
||||||
|
RNN-transducer with stateless prediction network
|
||||||
|
https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=9054419
|
||||||
|
|
||||||
|
It removes the recurrent connection from the decoder, i.e., the prediction
|
||||||
|
network. Different from the above paper, it adds an extra Conv1d
|
||||||
|
right after the embedding layer.
|
||||||
|
|
||||||
|
TODO: Implement https://arxiv.org/pdf/2109.07513.pdf
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
vocab_size: int,
|
||||||
|
decoder_dim: int,
|
||||||
|
blank_id: int,
|
||||||
|
context_size: int,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
vocab_size:
|
||||||
|
Number of tokens of the modeling unit including blank.
|
||||||
|
decoder_dim:
|
||||||
|
Dimension of the input embedding, and of the decoder output.
|
||||||
|
blank_id:
|
||||||
|
The ID of the blank symbol.
|
||||||
|
context_size:
|
||||||
|
Number of previous words to use to predict the next word.
|
||||||
|
1 means bigram; 2 means trigram. n means (n+1)-gram.
|
||||||
|
"""
|
||||||
|
super().__init__()
|
||||||
|
|
||||||
|
self.embedding = nn.Embedding(
|
||||||
|
num_embeddings=vocab_size,
|
||||||
|
embedding_dim=decoder_dim,
|
||||||
|
padding_idx=blank_id,
|
||||||
|
)
|
||||||
|
self.blank_id = blank_id
|
||||||
|
|
||||||
|
assert context_size >= 1, context_size
|
||||||
|
self.context_size = context_size
|
||||||
|
self.vocab_size = vocab_size
|
||||||
|
if context_size > 1:
|
||||||
|
self.conv = nn.Conv1d(
|
||||||
|
in_channels=decoder_dim,
|
||||||
|
out_channels=decoder_dim,
|
||||||
|
kernel_size=context_size,
|
||||||
|
padding=0,
|
||||||
|
groups=decoder_dim // 4, # group size == 4
|
||||||
|
bias=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.repeat_param = nn.Parameter(torch.randn(decoder_dim))
|
||||||
|
|
||||||
|
def _add_repeat_param(
|
||||||
|
self,
|
||||||
|
embedding_out: torch.Tensor,
|
||||||
|
k: torch.Tensor,
|
||||||
|
) -> torch.Tensor:
|
||||||
|
"""
|
||||||
|
Add the repeat parameter to the embedding_out tensor.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
embedding_out:
|
||||||
|
A tensor of shape (N, U, decoder_dim).
|
||||||
|
k:
|
||||||
|
A tensor of shape (N, U).
|
||||||
|
Should be (N, S + 1) during training.
|
||||||
|
Should be (N, 1) during inference.
|
||||||
|
is_training:
|
||||||
|
Whether it is training.
|
||||||
|
Returns:
|
||||||
|
Return a tensor of shape (N, U, decoder_dim).
|
||||||
|
"""
|
||||||
|
return embedding_out + (k / (1 + k)).unsqueeze(2) * self.repeat_param
|
||||||
|
|
||||||
|
def forward(
|
||||||
|
self,
|
||||||
|
y: torch.Tensor,
|
||||||
|
k: torch.Tensor,
|
||||||
|
need_pad: bool = True,
|
||||||
|
) -> torch.Tensor:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
y:
|
||||||
|
A 2-D tensor of shape (N, U).
|
||||||
|
k:
|
||||||
|
A 2-D tensor, statistic given the context_size with respect to utt.
|
||||||
|
Should be (N, S + 1) during training.
|
||||||
|
Should be (N, 1) during inference.
|
||||||
|
need_pad:
|
||||||
|
Whether to left pad the input.
|
||||||
|
Should be True during training.
|
||||||
|
Should be False during inference.
|
||||||
|
Returns:
|
||||||
|
Return a tensor of shape (N, U, decoder_dim).
|
||||||
|
"""
|
||||||
|
y = y.to(torch.int64)
|
||||||
|
# this stuff about clamp() is a temporary fix for a mismatch
|
||||||
|
# at utterance start, we use negative ids in beam_search.py
|
||||||
|
embedding_out = self.embedding(y.clamp(min=0)) * (y >= 0).unsqueeze(-1)
|
||||||
|
if self.context_size > 1:
|
||||||
|
embedding_out = embedding_out.permute(0, 2, 1)
|
||||||
|
if need_pad is True:
|
||||||
|
embedding_out = F.pad(embedding_out, pad=(self.context_size - 1, 0))
|
||||||
|
else:
|
||||||
|
# During inference time, there is no need to do extra padding
|
||||||
|
# as we only need one output
|
||||||
|
assert embedding_out.size(-1) == self.context_size
|
||||||
|
embedding_out = self.conv(embedding_out)
|
||||||
|
embedding_out = embedding_out.permute(0, 2, 1)
|
||||||
|
|
||||||
|
embedding_out = self._add_repeat_param(
|
||||||
|
embedding_out=embedding_out,
|
||||||
|
k=k,
|
||||||
|
)
|
||||||
|
embedding_out = F.relu(embedding_out)
|
||||||
|
return embedding_out
|
@ -0,0 +1 @@
|
|||||||
|
../pruned_transducer_stateless2/encoder_interface.py
|
1
egs/librispeech/ASR/pruned_transducer_stateless9/joiner.py
Symbolic link
1
egs/librispeech/ASR/pruned_transducer_stateless9/joiner.py
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../pruned_transducer_stateless7/joiner.py
|
225
egs/librispeech/ASR/pruned_transducer_stateless9/model.py
Normal file
225
egs/librispeech/ASR/pruned_transducer_stateless9/model.py
Normal file
@ -0,0 +1,225 @@
|
|||||||
|
# Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang, Wei Kang)
|
||||||
|
#
|
||||||
|
# See ../../../../LICENSE for clarification regarding multiple authors
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
|
||||||
|
|
||||||
|
import random
|
||||||
|
|
||||||
|
import k2
|
||||||
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
import torch.nn.functional as F
|
||||||
|
from encoder_interface import EncoderInterface
|
||||||
|
from scaling import penalize_abs_values_gt
|
||||||
|
|
||||||
|
from icefall.utils import add_sos
|
||||||
|
|
||||||
|
|
||||||
|
class Transducer(nn.Module):
|
||||||
|
"""It implements https://arxiv.org/pdf/1211.3711.pdf
|
||||||
|
"Sequence Transduction with Recurrent Neural Networks"
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
encoder: EncoderInterface,
|
||||||
|
decoder: nn.Module,
|
||||||
|
joiner: nn.Module,
|
||||||
|
encoder_dim: int,
|
||||||
|
decoder_dim: int,
|
||||||
|
joiner_dim: int,
|
||||||
|
vocab_size: int,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
encoder:
|
||||||
|
It is the transcription network in the paper. Its accepts
|
||||||
|
two inputs: `x` of (N, T, encoder_dim) and `x_lens` of shape (N,).
|
||||||
|
It returns two tensors: `logits` of shape (N, T, encoder_dm) and
|
||||||
|
`logit_lens` of shape (N,).
|
||||||
|
decoder:
|
||||||
|
It is the prediction network in the paper. Its input shape
|
||||||
|
is (N, U) and its output shape is (N, U, decoder_dim).
|
||||||
|
It should contain one attribute: `blank_id`.
|
||||||
|
joiner:
|
||||||
|
It has two inputs with shapes: (N, T, encoder_dim) and (N, U, decoder_dim).
|
||||||
|
Its output shape is (N, T, U, vocab_size). Note that its output contains
|
||||||
|
unnormalized probs, i.e., not processed by log-softmax.
|
||||||
|
"""
|
||||||
|
super().__init__()
|
||||||
|
assert isinstance(encoder, EncoderInterface), type(encoder)
|
||||||
|
assert hasattr(decoder, "blank_id")
|
||||||
|
|
||||||
|
self.encoder = encoder
|
||||||
|
self.decoder = decoder
|
||||||
|
self.joiner = joiner
|
||||||
|
|
||||||
|
self.simple_am_proj = nn.Linear(
|
||||||
|
encoder_dim,
|
||||||
|
vocab_size,
|
||||||
|
)
|
||||||
|
self.simple_lm_proj = nn.Linear(decoder_dim, vocab_size)
|
||||||
|
|
||||||
|
def _compute_k(
|
||||||
|
self,
|
||||||
|
y: torch.Tensor,
|
||||||
|
context_size: int = 2,
|
||||||
|
) -> torch.Tensor:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
y:
|
||||||
|
A 2-D tensor of shape (N, U).
|
||||||
|
context_size:
|
||||||
|
Number of previous words to use to predict the next word.
|
||||||
|
1 means bigram; 2 means trigram. n means (n+1)-gram.
|
||||||
|
Returns:
|
||||||
|
Return a tensor of shape (N, U).
|
||||||
|
"""
|
||||||
|
y_shift = F.pad(
|
||||||
|
y, (context_size, 0), mode="constant", value=-1
|
||||||
|
)[:, :-context_size]
|
||||||
|
mask = y_shift != y
|
||||||
|
|
||||||
|
T_arange = torch.arange(y.size(1)).expand_as(y).to(device=y.device)
|
||||||
|
cummax_out = (T_arange * mask).cummax(dim=-1)[0]
|
||||||
|
k = T_arange - cummax_out
|
||||||
|
|
||||||
|
return k
|
||||||
|
|
||||||
|
def forward(
|
||||||
|
self,
|
||||||
|
x: torch.Tensor,
|
||||||
|
x_lens: torch.Tensor,
|
||||||
|
y: k2.RaggedTensor,
|
||||||
|
prune_range: int = 5,
|
||||||
|
am_scale: float = 0.0,
|
||||||
|
lm_scale: float = 0.0,
|
||||||
|
) -> torch.Tensor:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
x:
|
||||||
|
A 3-D tensor of shape (N, T, C).
|
||||||
|
x_lens:
|
||||||
|
A 1-D tensor of shape (N,). It contains the number of frames in `x`
|
||||||
|
before padding.
|
||||||
|
y:
|
||||||
|
A ragged tensor with 2 axes [utt][label]. It contains labels of each
|
||||||
|
utterance.
|
||||||
|
prune_range:
|
||||||
|
The prune range for rnnt loss, it means how many symbols(context)
|
||||||
|
we are considering for each frame to compute the loss.
|
||||||
|
am_scale:
|
||||||
|
The scale to smooth the loss with am (output of encoder network)
|
||||||
|
part
|
||||||
|
lm_scale:
|
||||||
|
The scale to smooth the loss with lm (output of predictor network)
|
||||||
|
part
|
||||||
|
Returns:
|
||||||
|
Return the transducer loss.
|
||||||
|
|
||||||
|
Note:
|
||||||
|
Regarding am_scale & lm_scale, it will make the loss-function one of
|
||||||
|
the form:
|
||||||
|
lm_scale * lm_probs + am_scale * am_probs +
|
||||||
|
(1-lm_scale-am_scale) * combined_probs
|
||||||
|
"""
|
||||||
|
assert x.ndim == 3, x.shape
|
||||||
|
assert x_lens.ndim == 1, x_lens.shape
|
||||||
|
assert y.num_axes == 2, y.num_axes
|
||||||
|
|
||||||
|
assert x.size(0) == x_lens.size(0) == y.dim0
|
||||||
|
|
||||||
|
encoder_out, x_lens = self.encoder(x, x_lens)
|
||||||
|
assert torch.all(x_lens > 0)
|
||||||
|
|
||||||
|
# Now for the decoder, i.e., the prediction network
|
||||||
|
row_splits = y.shape.row_splits(1)
|
||||||
|
y_lens = row_splits[1:] - row_splits[:-1]
|
||||||
|
|
||||||
|
blank_id = self.decoder.blank_id
|
||||||
|
sos_y = add_sos(y, sos_id=blank_id)
|
||||||
|
|
||||||
|
# sos_y_padded: [B, S + 1], start with SOS.
|
||||||
|
sos_y_padded = sos_y.pad(mode="constant", padding_value=blank_id)
|
||||||
|
|
||||||
|
# compute k
|
||||||
|
k = self._compute_k(sos_y_padded, context_size=self.decoder.context_size)
|
||||||
|
|
||||||
|
# decoder_out: [B, S + 1, decoder_dim]
|
||||||
|
decoder_out = self.decoder(sos_y_padded, k)
|
||||||
|
|
||||||
|
# Note: y does not start with SOS
|
||||||
|
# y_padded : [B, S]
|
||||||
|
y_padded = y.pad(mode="constant", padding_value=0)
|
||||||
|
|
||||||
|
y_padded = y_padded.to(torch.int64)
|
||||||
|
boundary = torch.zeros((x.size(0), 4), dtype=torch.int64, device=x.device)
|
||||||
|
boundary[:, 2] = y_lens
|
||||||
|
boundary[:, 3] = x_lens
|
||||||
|
|
||||||
|
lm = self.simple_lm_proj(decoder_out)
|
||||||
|
am = self.simple_am_proj(encoder_out)
|
||||||
|
|
||||||
|
# if self.training and random.random() < 0.25:
|
||||||
|
# lm = penalize_abs_values_gt(lm, 100.0, 1.0e-04)
|
||||||
|
# if self.training and random.random() < 0.25:
|
||||||
|
# am = penalize_abs_values_gt(am, 30.0, 1.0e-04)
|
||||||
|
|
||||||
|
with torch.cuda.amp.autocast(enabled=False):
|
||||||
|
simple_loss, (px_grad, py_grad) = k2.rnnt_loss_smoothed(
|
||||||
|
lm=lm.float(),
|
||||||
|
am=am.float(),
|
||||||
|
symbols=y_padded,
|
||||||
|
termination_symbol=blank_id,
|
||||||
|
lm_only_scale=lm_scale,
|
||||||
|
am_only_scale=am_scale,
|
||||||
|
boundary=boundary,
|
||||||
|
reduction="sum",
|
||||||
|
return_grad=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# ranges : [B, T, prune_range]
|
||||||
|
ranges = k2.get_rnnt_prune_ranges(
|
||||||
|
px_grad=px_grad,
|
||||||
|
py_grad=py_grad,
|
||||||
|
boundary=boundary,
|
||||||
|
s_range=prune_range,
|
||||||
|
)
|
||||||
|
|
||||||
|
# am_pruned : [B, T, prune_range, encoder_dim]
|
||||||
|
# lm_pruned : [B, T, prune_range, decoder_dim]
|
||||||
|
am_pruned, lm_pruned = k2.do_rnnt_pruning(
|
||||||
|
am=self.joiner.encoder_proj(encoder_out),
|
||||||
|
lm=self.joiner.decoder_proj(decoder_out),
|
||||||
|
ranges=ranges,
|
||||||
|
)
|
||||||
|
|
||||||
|
# logits : [B, T, prune_range, vocab_size]
|
||||||
|
|
||||||
|
# project_input=False since we applied the decoder's input projections
|
||||||
|
# prior to do_rnnt_pruning (this is an optimization for speed).
|
||||||
|
logits = self.joiner(am_pruned, lm_pruned, project_input=False)
|
||||||
|
|
||||||
|
with torch.cuda.amp.autocast(enabled=False):
|
||||||
|
pruned_loss = k2.rnnt_loss_pruned(
|
||||||
|
logits=logits.float(),
|
||||||
|
symbols=y_padded,
|
||||||
|
ranges=ranges,
|
||||||
|
termination_symbol=blank_id,
|
||||||
|
boundary=boundary,
|
||||||
|
reduction="sum",
|
||||||
|
)
|
||||||
|
|
||||||
|
return (simple_loss, pruned_loss)
|
1
egs/librispeech/ASR/pruned_transducer_stateless9/optim.py
Symbolic link
1
egs/librispeech/ASR/pruned_transducer_stateless9/optim.py
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../pruned_transducer_stateless7/optim.py
|
1
egs/librispeech/ASR/pruned_transducer_stateless9/scaling.py
Symbolic link
1
egs/librispeech/ASR/pruned_transducer_stateless9/scaling.py
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../pruned_transducer_stateless7/scaling.py
|
@ -0,0 +1 @@
|
|||||||
|
../pruned_transducer_stateless7/scaling_converter.py
|
1258
egs/librispeech/ASR/pruned_transducer_stateless9/train.py
Executable file
1258
egs/librispeech/ASR/pruned_transducer_stateless9/train.py
Executable file
File diff suppressed because it is too large
Load Diff
1
egs/librispeech/ASR/pruned_transducer_stateless9/zipformer.py
Symbolic link
1
egs/librispeech/ASR/pruned_transducer_stateless9/zipformer.py
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../pruned_transducer_stateless7/zipformer.py
|
Loading…
x
Reference in New Issue
Block a user