data_utils.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. # Copyright (c) Facebook, Inc. and its affiliates.
  2. #
  3. # This source code is licensed under the MIT license found in the
  4. # LICENSE file in the root directory of this source tree.
  5. from typing import Optional, Tuple
  6. import numpy as np
  7. import torch
  8. def compute_mask_indices(
  9. shape: Tuple[int, int],
  10. padding_mask: Optional[torch.Tensor],
  11. mask_prob: float,
  12. mask_length: int,
  13. mask_type: str = "static",
  14. mask_other: float = 0.0,
  15. min_masks: int = 0,
  16. no_overlap: bool = False,
  17. min_space: int = 0,
  18. require_same_masks: bool = True,
  19. mask_dropout: float = 0.0,
  20. ) -> np.ndarray:
  21. """
  22. Computes random mask spans for a given shape
  23. Args:
  24. shape: the the shape for which to compute masks.
  25. should be of size 2 where first element is batch size and 2nd is timesteps
  26. padding_mask: optional padding mask of the same size as shape, which will prevent masking padded elements
  27. mask_prob: probability for each token to be chosen as start of the span to be masked. this will be multiplied by
  28. number of timesteps divided by length of mask span to mask approximately this percentage of all elements.
  29. however due to overlaps, the actual number will be smaller (unless no_overlap is True)
  30. mask_type: how to compute mask lengths
  31. static = fixed size
  32. uniform = sample from uniform distribution [mask_other, mask_length*2]
  33. normal = sample from normal distribution with mean mask_length and stdev mask_other. mask is min 1 element
  34. poisson = sample from possion distribution with lambda = mask length
  35. min_masks: minimum number of masked spans
  36. no_overlap: if false, will switch to an alternative recursive algorithm that prevents spans from overlapping
  37. min_space: only used if no_overlap is True, this is how many elements to keep unmasked between spans
  38. require_same_masks: if true, will randomly drop out masks until same amount of masks remains in each sample
  39. mask_dropout: randomly dropout this percentage of masks in each example
  40. """
  41. bsz, all_sz = shape
  42. mask = np.full((bsz, all_sz), False)
  43. all_num_mask = int(
  44. # add a random number for probabilistic rounding
  45. mask_prob * all_sz / float(mask_length)
  46. + np.random.rand()
  47. )
  48. all_num_mask = max(min_masks, all_num_mask)
  49. mask_idcs = []
  50. for i in range(bsz):
  51. if padding_mask is not None:
  52. sz = all_sz - padding_mask[i].long().sum().item()
  53. num_mask = int(
  54. # add a random number for probabilistic rounding
  55. mask_prob * sz / float(mask_length)
  56. + np.random.rand()
  57. )
  58. num_mask = max(min_masks, num_mask)
  59. else:
  60. sz = all_sz
  61. num_mask = all_num_mask
  62. if mask_type == "static":
  63. lengths = np.full(num_mask, mask_length)
  64. elif mask_type == "uniform":
  65. lengths = np.random.randint(mask_other, mask_length * 2 + 1, size=num_mask)
  66. elif mask_type == "normal":
  67. lengths = np.random.normal(mask_length, mask_other, size=num_mask)
  68. lengths = [max(1, int(round(x))) for x in lengths]
  69. elif mask_type == "poisson":
  70. lengths = np.random.poisson(mask_length, size=num_mask)
  71. lengths = [int(round(x)) for x in lengths]
  72. else:
  73. raise Exception("unknown mask selection " + mask_type)
  74. if sum(lengths) == 0:
  75. lengths[0] = min(mask_length, sz - 1)
  76. if no_overlap:
  77. mask_idc = []
  78. def arrange(s, e, length, keep_length):
  79. span_start = np.random.randint(s, e - length)
  80. mask_idc.extend(span_start + i for i in range(length))
  81. new_parts = []
  82. if span_start - s - min_space >= keep_length:
  83. new_parts.append((s, span_start - min_space + 1))
  84. if e - span_start - length - min_space > keep_length:
  85. new_parts.append((span_start + length + min_space, e))
  86. return new_parts
  87. parts = [(0, sz)]
  88. min_length = min(lengths)
  89. for length in sorted(lengths, reverse=True):
  90. lens = np.fromiter(
  91. (e - s if e - s >= length + min_space else 0 for s, e in parts),
  92. np.int32,
  93. )
  94. l_sum = np.sum(lens)
  95. if l_sum == 0:
  96. break
  97. probs = lens / np.sum(lens)
  98. c = np.random.choice(len(parts), p=probs)
  99. s, e = parts.pop(c)
  100. parts.extend(arrange(s, e, length, min_length))
  101. mask_idc = np.asarray(mask_idc)
  102. else:
  103. min_len = min(lengths)
  104. if sz - min_len <= num_mask:
  105. min_len = sz - num_mask - 1
  106. mask_idc = np.random.choice(sz - min_len, num_mask, replace=False)
  107. mask_idc = np.asarray(
  108. [
  109. mask_idc[j] + offset
  110. for j in range(len(mask_idc))
  111. for offset in range(lengths[j])
  112. ]
  113. )
  114. mask_idcs.append(np.unique(mask_idc[mask_idc < sz]))
  115. min_len = min([len(m) for m in mask_idcs])
  116. for i, mask_idc in enumerate(mask_idcs):
  117. if len(mask_idc) > min_len and require_same_masks:
  118. mask_idc = np.random.choice(mask_idc, min_len, replace=False)
  119. if mask_dropout > 0:
  120. num_holes = np.rint(len(mask_idc) * mask_dropout).astype(int)
  121. mask_idc = np.random.choice(
  122. mask_idc, len(mask_idc) - num_holes, replace=False
  123. )
  124. mask[i, mask_idc] = True
  125. return mask