attention.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """Multi-Head Attention layer definition."""
  4. import math
  5. import numpy
  6. import torch
  7. from torch import nn
  8. from typing import Optional, Tuple
  9. import torch.nn.functional as F
  10. from funasr.models.transformer.utils.nets_utils import make_pad_mask
  11. import funasr.models.lora.layers as lora
  12. class CosineDistanceAttention(nn.Module):
  13. """ Compute Cosine Distance between spk decoder output and speaker profile
  14. Args:
  15. profile_path: speaker profile file path (.npy file)
  16. """
  17. def __init__(self):
  18. super().__init__()
  19. self.softmax = nn.Softmax(dim=-1)
  20. def forward(self, spk_decoder_out, profile, profile_lens=None):
  21. """
  22. Args:
  23. spk_decoder_out(torch.Tensor):(B, L, D)
  24. spk_profiles(torch.Tensor):(B, N, D)
  25. """
  26. x = spk_decoder_out.unsqueeze(2) # (B, L, 1, D)
  27. if profile_lens is not None:
  28. mask = (make_pad_mask(profile_lens)[:, None, :]).to(profile.device)
  29. min_value = float(
  30. numpy.finfo(torch.tensor(0, dtype=x.dtype).numpy().dtype).min
  31. )
  32. weights_not_softmax=F.cosine_similarity(x, profile.unsqueeze(1), dim=-1).masked_fill(mask, min_value)
  33. weights = self.softmax(weights_not_softmax).masked_fill(mask, 0.0) # (B, L, N)
  34. else:
  35. x = x[:, -1:, :, :]
  36. weights_not_softmax=F.cosine_similarity(x, profile.unsqueeze(1).to(x.device), dim=-1)
  37. weights = self.softmax(weights_not_softmax) # (B, 1, N)
  38. spk_embedding = torch.matmul(weights, profile.to(weights.device)) # (B, L, D)
  39. return spk_embedding, weights