Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 8 additions & 9 deletions funasr/models/seaco_paraformer/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,17 +324,16 @@ def _seaco_decode_with_ASF(
hotword_scores = self.seaco_decoder.forward_asf6(
contextual_info, _contextual_length, decoder_hidden, ys_pad_lens
)
hotword_scores = hotword_scores[0].sum(0).sum(0)
# rank hotwords per utterance, leaving out padded token positions
token_pad_mask = make_pad_mask(ys_pad_lens, maxlen=hotword_scores.shape[2])
token_pad_mask = token_pad_mask[:, :, None].to(hotword_scores.device)
hotword_scores = hotword_scores.sum(1).masked_fill(token_pad_mask, 0).sum(1)
# hotword_scores /= torch.sqrt(torch.tensor(hw_lengths)[:-1].float()).to(hotword_scores.device)
dec_filter = torch.topk(hotword_scores, min(nfilter, num_hot_word - 1))[1].tolist()
add_filter = dec_filter
add_filter.append(len(hw_list_pad) - 1)
# Reserve the final no-bias entry; only genuine hotwords compete for top-k.
dec_filter = hotword_scores[:, :-1].topk(nfilter, dim=-1).indices
no_bias = dec_filter.new_full((dec_filter.shape[0], 1), len(hw_list_pad) - 1)
# filter hotword embedding
selected = selected[add_filter]
# again
contextual_info = (
selected.squeeze(0).repeat(encoder_out.shape[0], 1, 1).to(encoder_out.device)
)
contextual_info = selected[torch.cat([dec_filter, no_bias], dim=1)]
num_hot_word = contextual_info.shape[1]
_contextual_length = (
torch.Tensor([num_hot_word])
Expand Down
78 changes: 78 additions & 0 deletions tests/test_seaco_hotword_filter_batch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import unittest

import torch

from funasr.models.seaco_paraformer.model import SeacoParaformer

NUM_HOTWORDS = 6 # the last entry is the no-bias hotword


class _AttentionStub(torch.nn.Module):
"""SeACo decoder stand-in: attention is the softmax of token/hotword dot products."""

def __init__(self):
super().__init__()
self.seen = []

def forward_asf6(self, contextual_info, contextual_length, tokens, token_lengths):
return torch.softmax(tokens @ contextual_info.transpose(1, 2), dim=-1).unsqueeze(1)

def forward(self, contextual_info, contextual_length, tokens, token_lengths):
self.seen.append((contextual_info, contextual_length))
return torch.zeros_like(tokens), None


class _Seaco(SeacoParaformer):
def __init__(self):
torch.nn.Module.__init__(self)
self.seaco_decoder = _AttentionStub()
self.hotword_output_layer = torch.nn.Identity()
self.NO_BIAS = 0

def decoder(self, encoder_out, encoder_out_lens, tokens, token_lengths, **kwargs):
return torch.zeros_like(tokens), tokens, None

def _hotword_representation(self, hotword_pad, hotword_lengths):
return torch.eye(NUM_HOTWORDS)


def _candidates(utterances):
"""Run ASF on utterances given as lists of the hotword index each token attends to."""
model = _Seaco()
lengths = torch.tensor([len(u) for u in utterances])
# padded positions point at hotword 4, which no utterance contains
tokens = 5.0 * torch.eye(NUM_HOTWORDS)[4].repeat(len(utterances), int(lengths.max()), 1)
for i, utterance in enumerate(utterances):
tokens[i, : len(utterance)] = 5.0 * torch.eye(NUM_HOTWORDS)[utterance]
model._seaco_decode_with_ASF(
torch.zeros(len(utterances), 1, 1),
torch.ones(len(utterances)),
tokens,
lengths,
hw_list=[[1]] * NUM_HOTWORDS,
nfilter=2,
)
contextual_info, contextual_length = model.seaco_decoder.seen[-1]
assert contextual_length.tolist() == [3] * len(utterances)
# the stub hotword embeddings are one-hot, so argmax recovers the hotword index
return [sorted(row) for row in contextual_info.argmax(-1).tolist()]


class TestSeacoHotwordFilterBatch(unittest.TestCase):
def test_each_utterance_keeps_its_own_hotword_candidates(self):
short = [0, 1]
long = [2, 2, 2, 3, 3, 3]
alone = _candidates([short]) + _candidates([long])
self.assertEqual(alone, [[0, 1, 5], [2, 3, 5]])
self.assertEqual(_candidates([short, long]), alone)
self.assertEqual(_candidates([long, short]), alone[::-1])

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both utterances below give the no-bias entry a high attention score; each must still retain two real hotwords.

Suggested change
self.assertEqual(_candidates([long, short]), alone[::-1])
self.assertEqual(_candidates([long, short]), alone[::-1])
def test_no_bias_does_not_consume_a_real_hotword_slot(self):
# Entry 5 is no-bias. It ranks first, but is appended separately.
first = [5, 5, 5, 1, 0]
second = [5, 5, 2, 3]
self.assertEqual(_candidates([first, second]), [[0, 1, 5], [2, 3, 5]])


def test_no_bias_does_not_consume_a_real_hotword_slot(self):
# Entry 5 is no-bias. It ranks first, but is appended separately.
first = [5, 5, 5, 1, 0]
second = [5, 5, 2, 3]
self.assertEqual(_candidates([first, second]), [[0, 1, 5], [2, 3, 5]])


if __name__ == "__main__":
unittest.main()
Loading