embedding.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Copyright 2019 Shigeki Karita
  4. # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
  5. """Positional Encoding Module."""
  6. import math
  7. import torch
  8. import torch.nn.functional as F
  9. def _pre_hook(
  10. state_dict,
  11. prefix,
  12. local_metadata,
  13. strict,
  14. missing_keys,
  15. unexpected_keys,
  16. error_msgs,
  17. ):
  18. """Perform pre-hook in load_state_dict for backward compatibility.
  19. Note:
  20. We saved self.pe until v.0.5.2 but we have omitted it later.
  21. Therefore, we remove the item "pe" from `state_dict` for backward compatibility.
  22. """
  23. k = prefix + "pe"
  24. if k in state_dict:
  25. state_dict.pop(k)
  26. class PositionalEncoding(torch.nn.Module):
  27. """Positional encoding.
  28. Args:
  29. d_model (int): Embedding dimension.
  30. dropout_rate (float): Dropout rate.
  31. max_len (int): Maximum input length.
  32. reverse (bool): Whether to reverse the input position. Only for
  33. the class LegacyRelPositionalEncoding. We remove it in the current
  34. class RelPositionalEncoding.
  35. """
  36. def __init__(self, d_model, dropout_rate, max_len=5000, reverse=False):
  37. """Construct an PositionalEncoding object."""
  38. super(PositionalEncoding, self).__init__()
  39. self.d_model = d_model
  40. self.reverse = reverse
  41. self.xscale = math.sqrt(self.d_model)
  42. self.dropout = torch.nn.Dropout(p=dropout_rate)
  43. self.pe = None
  44. self.extend_pe(torch.tensor(0.0).expand(1, max_len))
  45. self._register_load_state_dict_pre_hook(_pre_hook)
  46. def extend_pe(self, x):
  47. """Reset the positional encodings."""
  48. if self.pe is not None:
  49. if self.pe.size(1) >= x.size(1):
  50. if self.pe.dtype != x.dtype or self.pe.device != x.device:
  51. self.pe = self.pe.to(dtype=x.dtype, device=x.device)
  52. return
  53. pe = torch.zeros(x.size(1), self.d_model)
  54. if self.reverse:
  55. position = torch.arange(
  56. x.size(1) - 1, -1, -1.0, dtype=torch.float32
  57. ).unsqueeze(1)
  58. else:
  59. position = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1)
  60. div_term = torch.exp(
  61. torch.arange(0, self.d_model, 2, dtype=torch.float32)
  62. * -(math.log(10000.0) / self.d_model)
  63. )
  64. pe[:, 0::2] = torch.sin(position * div_term)
  65. pe[:, 1::2] = torch.cos(position * div_term)
  66. pe = pe.unsqueeze(0)
  67. self.pe = pe.to(device=x.device, dtype=x.dtype)
  68. def forward(self, x: torch.Tensor):
  69. """Add positional encoding.
  70. Args:
  71. x (torch.Tensor): Input tensor (batch, time, `*`).
  72. Returns:
  73. torch.Tensor: Encoded tensor (batch, time, `*`).
  74. """
  75. self.extend_pe(x)
  76. x = x * self.xscale + self.pe[:, : x.size(1)]
  77. return self.dropout(x)
  78. class ScaledPositionalEncoding(PositionalEncoding):
  79. """Scaled positional encoding module.
  80. See Sec. 3.2 https://arxiv.org/abs/1809.08895
  81. Args:
  82. d_model (int): Embedding dimension.
  83. dropout_rate (float): Dropout rate.
  84. max_len (int): Maximum input length.
  85. """
  86. def __init__(self, d_model, dropout_rate, max_len=5000):
  87. """Initialize class."""
  88. super().__init__(d_model=d_model, dropout_rate=dropout_rate, max_len=max_len)
  89. self.alpha = torch.nn.Parameter(torch.tensor(1.0))
  90. def reset_parameters(self):
  91. """Reset parameters."""
  92. self.alpha.data = torch.tensor(1.0)
  93. def forward(self, x):
  94. """Add positional encoding.
  95. Args:
  96. x (torch.Tensor): Input tensor (batch, time, `*`).
  97. Returns:
  98. torch.Tensor: Encoded tensor (batch, time, `*`).
  99. """
  100. self.extend_pe(x)
  101. x = x + self.alpha * self.pe[:, : x.size(1)]
  102. return self.dropout(x)
  103. class LearnableFourierPosEnc(torch.nn.Module):
  104. """Learnable Fourier Features for Positional Encoding.
  105. See https://arxiv.org/pdf/2106.02795.pdf
  106. Args:
  107. d_model (int): Embedding dimension.
  108. dropout_rate (float): Dropout rate.
  109. max_len (int): Maximum input length.
  110. gamma (float): init parameter for the positional kernel variance
  111. see https://arxiv.org/pdf/2106.02795.pdf.
  112. apply_scaling (bool): Whether to scale the input before adding the pos encoding.
  113. hidden_dim (int): if not None, we modulate the pos encodings with
  114. an MLP whose hidden layer has hidden_dim neurons.
  115. """
  116. def __init__(
  117. self,
  118. d_model,
  119. dropout_rate=0.0,
  120. max_len=5000,
  121. gamma=1.0,
  122. apply_scaling=False,
  123. hidden_dim=None,
  124. ):
  125. """Initialize class."""
  126. super(LearnableFourierPosEnc, self).__init__()
  127. self.d_model = d_model
  128. if apply_scaling:
  129. self.xscale = math.sqrt(self.d_model)
  130. else:
  131. self.xscale = 1.0
  132. self.dropout = torch.nn.Dropout(dropout_rate)
  133. self.max_len = max_len
  134. self.gamma = gamma
  135. if self.gamma is None:
  136. self.gamma = self.d_model // 2
  137. assert (
  138. d_model % 2 == 0
  139. ), "d_model should be divisible by two in order to use this layer."
  140. self.w_r = torch.nn.Parameter(torch.empty(1, d_model // 2))
  141. self._reset() # init the weights
  142. self.hidden_dim = hidden_dim
  143. if self.hidden_dim is not None:
  144. self.mlp = torch.nn.Sequential(
  145. torch.nn.Linear(d_model, hidden_dim),
  146. torch.nn.GELU(),
  147. torch.nn.Linear(hidden_dim, d_model),
  148. )
  149. def _reset(self):
  150. self.w_r.data = torch.normal(
  151. 0, (1 / math.sqrt(self.gamma)), (1, self.d_model // 2)
  152. )
  153. def extend_pe(self, x):
  154. """Reset the positional encodings."""
  155. position_v = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1).to(x)
  156. cosine = torch.cos(torch.matmul(position_v, self.w_r))
  157. sine = torch.sin(torch.matmul(position_v, self.w_r))
  158. pos_enc = torch.cat((cosine, sine), -1)
  159. pos_enc /= math.sqrt(self.d_model)
  160. if self.hidden_dim is None:
  161. return pos_enc.unsqueeze(0)
  162. else:
  163. return self.mlp(pos_enc.unsqueeze(0))
  164. def forward(self, x: torch.Tensor):
  165. """Add positional encoding.
  166. Args:
  167. x (torch.Tensor): Input tensor (batch, time, `*`).
  168. Returns:
  169. torch.Tensor: Encoded tensor (batch, time, `*`).
  170. """
  171. pe = self.extend_pe(x)
  172. x = x * self.xscale + pe
  173. return self.dropout(x)
  174. class LegacyRelPositionalEncoding(PositionalEncoding):
  175. """Relative positional encoding module (old version).
  176. Details can be found in https://github.com/espnet/espnet/pull/2816.
  177. See : Appendix B in https://arxiv.org/abs/1901.02860
  178. Args:
  179. d_model (int): Embedding dimension.
  180. dropout_rate (float): Dropout rate.
  181. max_len (int): Maximum input length.
  182. """
  183. def __init__(self, d_model, dropout_rate, max_len=5000):
  184. """Initialize class."""
  185. super().__init__(
  186. d_model=d_model,
  187. dropout_rate=dropout_rate,
  188. max_len=max_len,
  189. reverse=True,
  190. )
  191. def forward(self, x):
  192. """Compute positional encoding.
  193. Args:
  194. x (torch.Tensor): Input tensor (batch, time, `*`).
  195. Returns:
  196. torch.Tensor: Encoded tensor (batch, time, `*`).
  197. torch.Tensor: Positional embedding tensor (1, time, `*`).
  198. """
  199. self.extend_pe(x)
  200. x = x * self.xscale
  201. pos_emb = self.pe[:, : x.size(1)]
  202. return self.dropout(x), self.dropout(pos_emb)
  203. class RelPositionalEncoding(torch.nn.Module):
  204. """Relative positional encoding module (new implementation).
  205. Details can be found in https://github.com/espnet/espnet/pull/2816.
  206. See : Appendix B in https://arxiv.org/abs/1901.02860
  207. Args:
  208. d_model (int): Embedding dimension.
  209. dropout_rate (float): Dropout rate.
  210. max_len (int): Maximum input length.
  211. """
  212. def __init__(self, d_model, dropout_rate, max_len=5000):
  213. """Construct an PositionalEncoding object."""
  214. super(RelPositionalEncoding, self).__init__()
  215. self.d_model = d_model
  216. self.xscale = math.sqrt(self.d_model)
  217. self.dropout = torch.nn.Dropout(p=dropout_rate)
  218. self.pe = None
  219. self.extend_pe(torch.tensor(0.0).expand(1, max_len))
  220. def extend_pe(self, x):
  221. """Reset the positional encodings."""
  222. if self.pe is not None:
  223. # self.pe contains both positive and negative parts
  224. # the length of self.pe is 2 * input_len - 1
  225. if self.pe.size(1) >= x.size(1) * 2 - 1:
  226. if self.pe.dtype != x.dtype or self.pe.device != x.device:
  227. self.pe = self.pe.to(dtype=x.dtype, device=x.device)
  228. return
  229. # Suppose `i` means to the position of query vecotr and `j` means the
  230. # position of key vector. We use position relative positions when keys
  231. # are to the left (i>j) and negative relative positions otherwise (i<j).
  232. pe_positive = torch.zeros(x.size(1), self.d_model)
  233. pe_negative = torch.zeros(x.size(1), self.d_model)
  234. position = torch.arange(0, x.size(1), dtype=torch.float32).unsqueeze(1)
  235. div_term = torch.exp(
  236. torch.arange(0, self.d_model, 2, dtype=torch.float32)
  237. * -(math.log(10000.0) / self.d_model)
  238. )
  239. pe_positive[:, 0::2] = torch.sin(position * div_term)
  240. pe_positive[:, 1::2] = torch.cos(position * div_term)
  241. pe_negative[:, 0::2] = torch.sin(-1 * position * div_term)
  242. pe_negative[:, 1::2] = torch.cos(-1 * position * div_term)
  243. # Reserve the order of positive indices and concat both positive and
  244. # negative indices. This is used to support the shifting trick
  245. # as in https://arxiv.org/abs/1901.02860
  246. pe_positive = torch.flip(pe_positive, [0]).unsqueeze(0)
  247. pe_negative = pe_negative[1:].unsqueeze(0)
  248. pe = torch.cat([pe_positive, pe_negative], dim=1)
  249. self.pe = pe.to(device=x.device, dtype=x.dtype)
  250. def forward(self, x: torch.Tensor):
  251. """Add positional encoding.
  252. Args:
  253. x (torch.Tensor): Input tensor (batch, time, `*`).
  254. Returns:
  255. torch.Tensor: Encoded tensor (batch, time, `*`).
  256. """
  257. self.extend_pe(x)
  258. x = x * self.xscale
  259. pos_emb = self.pe[
  260. :,
  261. self.pe.size(1) // 2 - x.size(1) + 1 : self.pe.size(1) // 2 + x.size(1),
  262. ]
  263. return self.dropout(x), self.dropout(pos_emb)
  264. class StreamPositionalEncoding(torch.nn.Module):
  265. """Streaming Positional encoding.
  266. Args:
  267. d_model (int): Embedding dimension.
  268. dropout_rate (float): Dropout rate.
  269. max_len (int): Maximum input length.
  270. """
  271. def __init__(self, d_model, dropout_rate, max_len=5000):
  272. """Construct an PositionalEncoding object."""
  273. super(StreamPositionalEncoding, self).__init__()
  274. self.d_model = d_model
  275. self.xscale = math.sqrt(self.d_model)
  276. self.dropout = torch.nn.Dropout(p=dropout_rate)
  277. self.pe = None
  278. self.tmp = torch.tensor(0.0).expand(1, max_len)
  279. self.extend_pe(self.tmp.size(1), self.tmp.device, self.tmp.dtype)
  280. self._register_load_state_dict_pre_hook(_pre_hook)
  281. def extend_pe(self, length, device, dtype):
  282. """Reset the positional encodings."""
  283. if self.pe is not None:
  284. if self.pe.size(1) >= length:
  285. if self.pe.dtype != dtype or self.pe.device != device:
  286. self.pe = self.pe.to(dtype=dtype, device=device)
  287. return
  288. pe = torch.zeros(length, self.d_model)
  289. position = torch.arange(0, length, dtype=torch.float32).unsqueeze(1)
  290. div_term = torch.exp(
  291. torch.arange(0, self.d_model, 2, dtype=torch.float32)
  292. * -(math.log(10000.0) / self.d_model)
  293. )
  294. pe[:, 0::2] = torch.sin(position * div_term)
  295. pe[:, 1::2] = torch.cos(position * div_term)
  296. pe = pe.unsqueeze(0)
  297. self.pe = pe.to(device=device, dtype=dtype)
  298. def forward(self, x: torch.Tensor, start_idx: int = 0):
  299. """Add positional encoding.
  300. Args:
  301. x (torch.Tensor): Input tensor (batch, time, `*`).
  302. Returns:
  303. torch.Tensor: Encoded tensor (batch, time, `*`).
  304. """
  305. self.extend_pe(x.size(1) + start_idx, x.device, x.dtype)
  306. x = x * self.xscale + self.pe[:, start_idx : start_idx + x.size(1)]
  307. return self.dropout(x)
  308. class SinusoidalPositionEncoder(torch.nn.Module):
  309. '''
  310. '''
  311. def __int__(self, d_model=80, dropout_rate=0.1):
  312. pass
  313. def encode(self, positions: torch.Tensor = None, depth: int = None, dtype: torch.dtype = torch.float32):
  314. batch_size = positions.size(0)
  315. positions = positions.type(dtype)
  316. log_timescale_increment = torch.log(torch.tensor([10000], dtype=dtype)) / (depth / 2 - 1)
  317. inv_timescales = torch.exp(torch.arange(depth / 2).type(dtype) * (-log_timescale_increment))
  318. inv_timescales = torch.reshape(inv_timescales, [batch_size, -1])
  319. scaled_time = torch.reshape(positions, [1, -1, 1]) * torch.reshape(inv_timescales, [1, 1, -1])
  320. encoding = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=2)
  321. return encoding.type(dtype)
  322. def forward(self, x):
  323. batch_size, timesteps, input_dim = x.size()
  324. positions = torch.arange(1, timesteps+1)[None, :]
  325. position_encoding = self.encode(positions, input_dim, x.dtype).to(x.device)
  326. return x + position_encoding
  327. class StreamSinusoidalPositionEncoder(torch.nn.Module):
  328. '''
  329. '''
  330. def __int__(self, d_model=80, dropout_rate=0.1):
  331. pass
  332. def encode(self, positions: torch.Tensor = None, depth: int = None, dtype: torch.dtype = torch.float32):
  333. batch_size = positions.size(0)
  334. positions = positions.type(dtype)
  335. log_timescale_increment = torch.log(torch.tensor([10000], dtype=dtype)) / (depth / 2 - 1)
  336. inv_timescales = torch.exp(torch.arange(depth / 2).type(dtype) * (-log_timescale_increment))
  337. inv_timescales = torch.reshape(inv_timescales, [batch_size, -1])
  338. scaled_time = torch.reshape(positions, [1, -1, 1]) * torch.reshape(inv_timescales, [1, 1, -1])
  339. encoding = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=2)
  340. return encoding.type(dtype)
  341. def forward(self, x, cache=None):
  342. batch_size, timesteps, input_dim = x.size()
  343. start_idx = 0
  344. if cache is not None:
  345. start_idx = cache["start_idx"]
  346. cache["start_idx"] += timesteps
  347. positions = torch.arange(1, timesteps+start_idx+1)[None, :]
  348. position_encoding = self.encode(positions, input_dim, x.dtype).to(x.device)
  349. return x + position_encoding[:, start_idx: start_idx + timesteps]
  350. class StreamingRelPositionalEncoding(torch.nn.Module):
  351. """Relative positional encoding.
  352. Args:
  353. size: Module size.
  354. max_len: Maximum input length.
  355. dropout_rate: Dropout rate.
  356. """
  357. def __init__(
  358. self, size: int, dropout_rate: float = 0.0, max_len: int = 5000
  359. ) -> None:
  360. """Construct a RelativePositionalEncoding object."""
  361. super().__init__()
  362. self.size = size
  363. self.pe = None
  364. self.dropout = torch.nn.Dropout(p=dropout_rate)
  365. self.extend_pe(torch.tensor(0.0).expand(1, max_len))
  366. self._register_load_state_dict_pre_hook(_pre_hook)
  367. def extend_pe(self, x: torch.Tensor, left_context: int = 0) -> None:
  368. """Reset positional encoding.
  369. Args:
  370. x: Input sequences. (B, T, ?)
  371. left_context: Number of frames in left context.
  372. """
  373. time1 = x.size(1) + left_context
  374. if self.pe is not None:
  375. if self.pe.size(1) >= time1 * 2 - 1:
  376. if self.pe.dtype != x.dtype or self.pe.device != x.device:
  377. self.pe = self.pe.to(device=x.device, dtype=x.dtype)
  378. return
  379. pe_positive = torch.zeros(time1, self.size)
  380. pe_negative = torch.zeros(time1, self.size)
  381. position = torch.arange(0, time1, dtype=torch.float32).unsqueeze(1)
  382. div_term = torch.exp(
  383. torch.arange(0, self.size, 2, dtype=torch.float32)
  384. * -(math.log(10000.0) / self.size)
  385. )
  386. pe_positive[:, 0::2] = torch.sin(position * div_term)
  387. pe_positive[:, 1::2] = torch.cos(position * div_term)
  388. pe_positive = torch.flip(pe_positive, [0]).unsqueeze(0)
  389. pe_negative[:, 0::2] = torch.sin(-1 * position * div_term)
  390. pe_negative[:, 1::2] = torch.cos(-1 * position * div_term)
  391. pe_negative = pe_negative[1:].unsqueeze(0)
  392. self.pe = torch.cat([pe_positive, pe_negative], dim=1).to(
  393. dtype=x.dtype, device=x.device
  394. )
  395. def forward(self, x: torch.Tensor, left_context: int = 0) -> torch.Tensor:
  396. """Compute positional encoding.
  397. Args:
  398. x: Input sequences. (B, T, ?)
  399. left_context: Number of frames in left context.
  400. Returns:
  401. pos_enc: Positional embedding sequences. (B, 2 * (T - 1), ?)
  402. """
  403. self.extend_pe(x, left_context=left_context)
  404. time1 = x.size(1) + left_context
  405. pos_enc = self.pe[
  406. :, self.pe.size(1) // 2 - time1 + 1 : self.pe.size(1) // 2 + x.size(1)
  407. ]
  408. pos_enc = self.dropout(pos_enc)
  409. return pos_enc