torch_function.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. from typing import Optional
  2. import torch
  3. import torch.nn as nn
  4. import numpy as np
  5. class MakePadMask(nn.Module):
  6. def __init__(self, max_seq_len=512, flip=True):
  7. super().__init__()
  8. if flip:
  9. self.mask_pad = torch.Tensor(1 - np.tri(max_seq_len)).type(torch.bool)
  10. else:
  11. self.mask_pad = torch.Tensor(np.tri(max_seq_len)).type(torch.bool)
  12. def forward(self, lengths, xs=None, length_dim=-1, maxlen=None):
  13. """Make mask tensor containing indices of padded part.
  14. This implementation creates the same mask tensor with original make_pad_mask,
  15. which can be converted into onnx format.
  16. Dimension length of xs should be 2 or 3.
  17. """
  18. if length_dim == 0:
  19. raise ValueError("length_dim cannot be 0: {}".format(length_dim))
  20. if xs is not None and len(xs.shape) == 3:
  21. if length_dim == 1:
  22. lengths = lengths.unsqueeze(1).expand(
  23. *xs.transpose(1, 2).shape[:2])
  24. else:
  25. lengths = lengths.unsqueeze(1).expand(*xs.shape[:2])
  26. if maxlen is not None:
  27. m = maxlen
  28. elif xs is not None:
  29. m = xs.shape[-1]
  30. else:
  31. m = torch.max(lengths)
  32. mask = self.mask_pad[lengths - 1][..., :m].type(torch.float32)
  33. if length_dim == 1:
  34. return mask.transpose(1, 2)
  35. else:
  36. return mask
  37. class sequence_mask(nn.Module):
  38. def __init__(self, max_seq_len=512, flip=True):
  39. super().__init__()
  40. def forward(self, lengths, max_seq_len=None, dtype=torch.float32, device=None):
  41. if max_seq_len is None:
  42. max_seq_len = lengths.max()
  43. row_vector = torch.arange(0, max_seq_len, 1).to(lengths.device)
  44. matrix = torch.unsqueeze(lengths, dim=-1)
  45. mask = row_vector < matrix
  46. return mask.type(dtype).to(device) if device is not None else mask.type(dtype)
  47. def normalize(input: torch.Tensor, p: float = 2.0, dim: int = 1, out: Optional[torch.Tensor] = None) -> torch.Tensor:
  48. if out is None:
  49. denom = input.norm(p, dim, keepdim=True).expand_as(input)
  50. return input / denom
  51. else:
  52. denom = input.norm(p, dim, keepdim=True).expand_as(input)
  53. return torch.div(input, denom, out=out)
  54. def subsequent_mask(size: torch.Tensor):
  55. return torch.ones(size, size).tril()
  56. def MakePadMask_test():
  57. feats_length = torch.tensor([10]).type(torch.long)
  58. mask_fn = MakePadMask()
  59. mask = mask_fn(feats_length)
  60. print(mask)
  61. if __name__ == '__main__':
  62. MakePadMask_test()