embedding.py 18 KB

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