rec_nrtr_head.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. # copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import math
  15. import paddle
  16. from paddle import nn
  17. import paddle.nn.functional as F
  18. from paddle.nn import Dropout, LayerNorm
  19. import numpy as np
  20. from ppocr.modeling.backbones.rec_svtrnet import Mlp, zeros_
  21. from paddle.nn.initializer import XavierNormal as xavier_normal_
  22. class Transformer(nn.Layer):
  23. """A transformer model. User is able to modify the attributes as needed. The architecture
  24. is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer,
  25. Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and
  26. Illia Polosukhin. 2017. Attention is all you need. In Advances in Neural Information
  27. Processing Systems, pages 6000-6010.
  28. Args:
  29. d_model: the number of expected features in the encoder/decoder inputs (default=512).
  30. nhead: the number of heads in the multiheadattention models (default=8).
  31. num_encoder_layers: the number of sub-encoder-layers in the encoder (default=6).
  32. num_decoder_layers: the number of sub-decoder-layers in the decoder (default=6).
  33. dim_feedforward: the dimension of the feedforward network model (default=2048).
  34. dropout: the dropout value (default=0.1).
  35. custom_encoder: custom encoder (default=None).
  36. custom_decoder: custom decoder (default=None).
  37. """
  38. def __init__(
  39. self,
  40. d_model=512,
  41. nhead=8,
  42. num_encoder_layers=6,
  43. beam_size=0,
  44. num_decoder_layers=6,
  45. max_len=25,
  46. dim_feedforward=1024,
  47. attention_dropout_rate=0.0,
  48. residual_dropout_rate=0.1,
  49. in_channels=0,
  50. out_channels=0,
  51. scale_embedding=True,
  52. ):
  53. super(Transformer, self).__init__()
  54. self.out_channels = out_channels + 1
  55. self.max_len = max_len
  56. self.embedding = Embeddings(
  57. d_model=d_model,
  58. vocab=self.out_channels,
  59. padding_idx=0,
  60. scale_embedding=scale_embedding,
  61. )
  62. self.positional_encoding = PositionalEncoding(
  63. dropout=residual_dropout_rate, dim=d_model
  64. )
  65. if num_encoder_layers > 0:
  66. self.encoder = nn.LayerList(
  67. [
  68. TransformerBlock(
  69. d_model,
  70. nhead,
  71. dim_feedforward,
  72. attention_dropout_rate,
  73. residual_dropout_rate,
  74. with_self_attn=True,
  75. with_cross_attn=False,
  76. )
  77. for i in range(num_encoder_layers)
  78. ]
  79. )
  80. else:
  81. self.encoder = None
  82. self.decoder = nn.LayerList(
  83. [
  84. TransformerBlock(
  85. d_model,
  86. nhead,
  87. dim_feedforward,
  88. attention_dropout_rate,
  89. residual_dropout_rate,
  90. with_self_attn=True,
  91. with_cross_attn=True,
  92. )
  93. for i in range(num_decoder_layers)
  94. ]
  95. )
  96. self.beam_size = beam_size
  97. self.d_model = d_model
  98. self.nhead = nhead
  99. self.tgt_word_prj = nn.Linear(d_model, self.out_channels, bias_attr=False)
  100. w0 = np.random.normal(
  101. 0.0, d_model**-0.5, (d_model, self.out_channels)
  102. ).astype(np.float32)
  103. self.tgt_word_prj.weight.set_value(w0)
  104. self.apply(self._init_weights)
  105. def _init_weights(self, m):
  106. if isinstance(m, nn.Linear):
  107. xavier_normal_(m.weight)
  108. if m.bias is not None:
  109. zeros_(m.bias)
  110. def forward_train(self, src, tgt):
  111. tgt = tgt[:, :-1]
  112. tgt = self.embedding(tgt)
  113. tgt = self.positional_encoding(tgt)
  114. tgt_mask = self.generate_square_subsequent_mask(tgt.shape[1])
  115. if self.encoder is not None:
  116. src = self.positional_encoding(src)
  117. for encoder_layer in self.encoder:
  118. src = encoder_layer(src)
  119. memory = src # B N C
  120. else:
  121. memory = src # B N C
  122. for decoder_layer in self.decoder:
  123. tgt = decoder_layer(tgt, memory, self_mask=tgt_mask)
  124. output = tgt
  125. logit = self.tgt_word_prj(output)
  126. return logit
  127. def forward(self, src, targets=None):
  128. """Take in and process masked source/target sequences.
  129. Args:
  130. src: the sequence to the encoder (required).
  131. tgt: the sequence to the decoder (required).
  132. Shape:
  133. - src: :math:`(B, sN, C)`.
  134. - tgt: :math:`(B, tN, C)`.
  135. Examples:
  136. >>> output = transformer_model(src, tgt)
  137. """
  138. if self.training:
  139. max_len = targets[1].max()
  140. tgt = targets[0][:, : 2 + max_len]
  141. return self.forward_train(src, tgt)
  142. else:
  143. if self.beam_size > 0:
  144. return self.forward_beam(src)
  145. else:
  146. return self.forward_test(src)
  147. def forward_test(self, src):
  148. bs = src.shape[0]
  149. if self.encoder is not None:
  150. src = self.positional_encoding(src)
  151. for encoder_layer in self.encoder:
  152. src = encoder_layer(src)
  153. memory = src # B N C
  154. else:
  155. memory = src
  156. dec_seq = paddle.full((bs, 1), 2, dtype=paddle.int64)
  157. dec_prob = paddle.full((bs, 1), 1.0, dtype=paddle.float32)
  158. for len_dec_seq in range(1, paddle.to_tensor(self.max_len)):
  159. dec_seq_embed = self.embedding(dec_seq)
  160. dec_seq_embed = self.positional_encoding(dec_seq_embed)
  161. tgt_mask = self.generate_square_subsequent_mask(dec_seq_embed.shape[1])
  162. tgt = dec_seq_embed
  163. for decoder_layer in self.decoder:
  164. tgt = decoder_layer(tgt, memory, self_mask=tgt_mask)
  165. dec_output = tgt
  166. dec_output = dec_output[:, -1, :]
  167. word_prob = F.softmax(self.tgt_word_prj(dec_output), axis=-1)
  168. preds_idx = paddle.argmax(word_prob, axis=-1)
  169. if paddle.equal_all(
  170. preds_idx, paddle.full(preds_idx.shape, 3, dtype="int64")
  171. ):
  172. break
  173. preds_prob = paddle.max(word_prob, axis=-1)
  174. dec_seq = paddle.concat(
  175. [dec_seq, paddle.reshape(preds_idx, [-1, 1])], axis=1
  176. )
  177. dec_prob = paddle.concat(
  178. [dec_prob, paddle.reshape(preds_prob, [-1, 1])], axis=1
  179. )
  180. return [dec_seq, dec_prob]
  181. def forward_beam(self, images):
  182. """Translation work in one batch"""
  183. def get_inst_idx_to_tensor_position_map(inst_idx_list):
  184. """Indicate the position of an instance in a tensor."""
  185. return {
  186. inst_idx: tensor_position
  187. for tensor_position, inst_idx in enumerate(inst_idx_list)
  188. }
  189. def collect_active_part(
  190. beamed_tensor, curr_active_inst_idx, n_prev_active_inst, n_bm
  191. ):
  192. """Collect tensor parts associated to active instances."""
  193. beamed_tensor_shape = beamed_tensor.shape
  194. n_curr_active_inst = len(curr_active_inst_idx)
  195. new_shape = (
  196. n_curr_active_inst * n_bm,
  197. beamed_tensor_shape[1],
  198. beamed_tensor_shape[2],
  199. )
  200. beamed_tensor = beamed_tensor.reshape([n_prev_active_inst, -1])
  201. beamed_tensor = beamed_tensor.index_select(curr_active_inst_idx, axis=0)
  202. beamed_tensor = beamed_tensor.reshape(new_shape)
  203. return beamed_tensor
  204. def collate_active_info(
  205. src_enc, inst_idx_to_position_map, active_inst_idx_list
  206. ):
  207. # Sentences which are still active are collected,
  208. # so the decoder will not run on completed sentences.
  209. n_prev_active_inst = len(inst_idx_to_position_map)
  210. active_inst_idx = [
  211. inst_idx_to_position_map[k] for k in active_inst_idx_list
  212. ]
  213. active_inst_idx = paddle.to_tensor(active_inst_idx, dtype="int64")
  214. active_src_enc = collect_active_part(
  215. src_enc.transpose([1, 0, 2]), active_inst_idx, n_prev_active_inst, n_bm
  216. ).transpose([1, 0, 2])
  217. active_inst_idx_to_position_map = get_inst_idx_to_tensor_position_map(
  218. active_inst_idx_list
  219. )
  220. return active_src_enc, active_inst_idx_to_position_map
  221. def beam_decode_step(
  222. inst_dec_beams, len_dec_seq, enc_output, inst_idx_to_position_map, n_bm
  223. ):
  224. """Decode and update beam status, and then return active beam idx"""
  225. def prepare_beam_dec_seq(inst_dec_beams, len_dec_seq):
  226. dec_partial_seq = [
  227. b.get_current_state() for b in inst_dec_beams if not b.done
  228. ]
  229. dec_partial_seq = paddle.stack(dec_partial_seq)
  230. dec_partial_seq = dec_partial_seq.reshape([-1, len_dec_seq])
  231. return dec_partial_seq
  232. def predict_word(dec_seq, enc_output, n_active_inst, n_bm):
  233. dec_seq = self.embedding(dec_seq)
  234. dec_seq = self.positional_encoding(dec_seq)
  235. tgt_mask = self.generate_square_subsequent_mask(dec_seq.shape[1])
  236. tgt = dec_seq
  237. for decoder_layer in self.decoder:
  238. tgt = decoder_layer(tgt, enc_output, self_mask=tgt_mask)
  239. dec_output = tgt
  240. dec_output = dec_output[:, -1, :] # Pick the last step: (bh * bm) * d_h
  241. word_prob = F.softmax(self.tgt_word_prj(dec_output), axis=1)
  242. word_prob = paddle.reshape(word_prob, [n_active_inst, n_bm, -1])
  243. return word_prob
  244. def collect_active_inst_idx_list(
  245. inst_beams, word_prob, inst_idx_to_position_map
  246. ):
  247. active_inst_idx_list = []
  248. for inst_idx, inst_position in inst_idx_to_position_map.items():
  249. is_inst_complete = inst_beams[inst_idx].advance(
  250. word_prob[inst_position]
  251. )
  252. if not is_inst_complete:
  253. active_inst_idx_list += [inst_idx]
  254. return active_inst_idx_list
  255. n_active_inst = len(inst_idx_to_position_map)
  256. dec_seq = prepare_beam_dec_seq(inst_dec_beams, len_dec_seq)
  257. word_prob = predict_word(dec_seq, enc_output, n_active_inst, n_bm)
  258. # Update the beam with predicted word prob information and collect incomplete instances
  259. active_inst_idx_list = collect_active_inst_idx_list(
  260. inst_dec_beams, word_prob, inst_idx_to_position_map
  261. )
  262. return active_inst_idx_list
  263. def collect_hypothesis_and_scores(inst_dec_beams, n_best):
  264. all_hyp, all_scores = [], []
  265. for inst_idx in range(len(inst_dec_beams)):
  266. scores, tail_idxs = inst_dec_beams[inst_idx].sort_scores()
  267. all_scores += [scores[:n_best]]
  268. hyps = [
  269. inst_dec_beams[inst_idx].get_hypothesis(i)
  270. for i in tail_idxs[:n_best]
  271. ]
  272. all_hyp += [hyps]
  273. return all_hyp, all_scores
  274. with paddle.no_grad():
  275. # -- Encode
  276. if self.encoder is not None:
  277. src = self.positional_encoding(images)
  278. src_enc = self.encoder(src)
  279. else:
  280. src_enc = images
  281. n_bm = self.beam_size
  282. src_shape = src_enc.shape
  283. inst_dec_beams = [Beam(n_bm) for _ in range(1)]
  284. active_inst_idx_list = list(range(1))
  285. # Repeat data for beam search
  286. src_enc = paddle.tile(src_enc, [1, n_bm, 1])
  287. inst_idx_to_position_map = get_inst_idx_to_tensor_position_map(
  288. active_inst_idx_list
  289. )
  290. # Decode
  291. for len_dec_seq in range(1, paddle.to_tensor(self.max_len)):
  292. src_enc_copy = src_enc.clone()
  293. active_inst_idx_list = beam_decode_step(
  294. inst_dec_beams,
  295. len_dec_seq,
  296. src_enc_copy,
  297. inst_idx_to_position_map,
  298. n_bm,
  299. )
  300. if not active_inst_idx_list:
  301. break # all instances have finished their path to <EOS>
  302. src_enc, inst_idx_to_position_map = collate_active_info(
  303. src_enc_copy, inst_idx_to_position_map, active_inst_idx_list
  304. )
  305. batch_hyp, batch_scores = collect_hypothesis_and_scores(inst_dec_beams, 1)
  306. result_hyp = []
  307. hyp_scores = []
  308. for bs_hyp, score in zip(batch_hyp, batch_scores):
  309. l = len(bs_hyp[0])
  310. bs_hyp_pad = bs_hyp[0] + [3] * (25 - l)
  311. result_hyp.append(bs_hyp_pad)
  312. score = float(score) / l
  313. hyp_score = [score for _ in range(25)]
  314. hyp_scores.append(hyp_score)
  315. return [
  316. paddle.to_tensor(np.array(result_hyp), dtype=paddle.int64),
  317. paddle.to_tensor(hyp_scores),
  318. ]
  319. def generate_square_subsequent_mask(self, sz):
  320. """Generate a square mask for the sequence. The masked positions are filled with float('-inf').
  321. Unmasked positions are filled with float(0.0).
  322. """
  323. mask = paddle.zeros([sz, sz], dtype="float32")
  324. mask_inf = paddle.triu(
  325. paddle.full(shape=[sz, sz], dtype="float32", fill_value=float("-inf")),
  326. diagonal=1,
  327. )
  328. mask = mask + mask_inf
  329. return mask.unsqueeze([0, 1])
  330. class MultiheadAttention(nn.Layer):
  331. """Allows the model to jointly attend to information
  332. from different representation subspaces.
  333. See reference: Attention Is All You Need
  334. .. math::
  335. \text{MultiHead}(Q, K, V) = \text{Concat}(head_1,\dots,head_h)W^O
  336. \text{where} head_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)
  337. Args:
  338. embed_dim: total dimension of the model
  339. num_heads: parallel attention layers, or heads
  340. """
  341. def __init__(self, embed_dim, num_heads, dropout=0.0, self_attn=False):
  342. super(MultiheadAttention, self).__init__()
  343. self.embed_dim = embed_dim
  344. self.num_heads = num_heads
  345. # self.dropout = dropout
  346. self.head_dim = embed_dim // num_heads
  347. assert (
  348. self.head_dim * num_heads == self.embed_dim
  349. ), "embed_dim must be divisible by num_heads"
  350. self.scale = self.head_dim**-0.5
  351. self.self_attn = self_attn
  352. if self_attn:
  353. self.qkv = nn.Linear(embed_dim, embed_dim * 3)
  354. else:
  355. self.q = nn.Linear(embed_dim, embed_dim)
  356. self.kv = nn.Linear(embed_dim, embed_dim * 2)
  357. self.attn_drop = nn.Dropout(dropout)
  358. self.out_proj = nn.Linear(embed_dim, embed_dim)
  359. def forward(self, query, key=None, attn_mask=None):
  360. qN = query.shape[1]
  361. if self.self_attn:
  362. qkv = (
  363. self.qkv(query)
  364. .reshape((0, qN, 3, self.num_heads, self.head_dim))
  365. .transpose((2, 0, 3, 1, 4))
  366. )
  367. q, k, v = qkv[0], qkv[1], qkv[2]
  368. else:
  369. kN = key.shape[1]
  370. q = (
  371. self.q(query)
  372. .reshape([0, qN, self.num_heads, self.head_dim])
  373. .transpose([0, 2, 1, 3])
  374. )
  375. kv = (
  376. self.kv(key)
  377. .reshape((0, kN, 2, self.num_heads, self.head_dim))
  378. .transpose((2, 0, 3, 1, 4))
  379. )
  380. k, v = kv[0], kv[1]
  381. attn = (q.matmul(k.transpose((0, 1, 3, 2)))) * self.scale
  382. if attn_mask is not None:
  383. attn += attn_mask
  384. attn = F.softmax(attn, axis=-1)
  385. attn = self.attn_drop(attn)
  386. x = (attn.matmul(v)).transpose((0, 2, 1, 3)).reshape((0, qN, self.embed_dim))
  387. x = self.out_proj(x)
  388. return x
  389. class TransformerBlock(nn.Layer):
  390. def __init__(
  391. self,
  392. d_model,
  393. nhead,
  394. dim_feedforward=2048,
  395. attention_dropout_rate=0.0,
  396. residual_dropout_rate=0.1,
  397. with_self_attn=True,
  398. with_cross_attn=False,
  399. epsilon=1e-5,
  400. ):
  401. super(TransformerBlock, self).__init__()
  402. self.with_self_attn = with_self_attn
  403. if with_self_attn:
  404. self.self_attn = MultiheadAttention(
  405. d_model, nhead, dropout=attention_dropout_rate, self_attn=with_self_attn
  406. )
  407. self.norm1 = LayerNorm(d_model, epsilon=epsilon)
  408. self.dropout1 = Dropout(residual_dropout_rate)
  409. self.with_cross_attn = with_cross_attn
  410. if with_cross_attn:
  411. self.cross_attn = (
  412. MultiheadAttention( # for self_attn of encoder or cross_attn of decoder
  413. d_model, nhead, dropout=attention_dropout_rate
  414. )
  415. )
  416. self.norm2 = LayerNorm(d_model, epsilon=epsilon)
  417. self.dropout2 = Dropout(residual_dropout_rate)
  418. self.mlp = Mlp(
  419. in_features=d_model,
  420. hidden_features=dim_feedforward,
  421. act_layer=nn.ReLU,
  422. drop=residual_dropout_rate,
  423. )
  424. self.norm3 = LayerNorm(d_model, epsilon=epsilon)
  425. self.dropout3 = Dropout(residual_dropout_rate)
  426. def forward(self, tgt, memory=None, self_mask=None, cross_mask=None):
  427. if self.with_self_attn:
  428. tgt1 = self.self_attn(tgt, attn_mask=self_mask)
  429. tgt = self.norm1(tgt + self.dropout1(tgt1))
  430. if self.with_cross_attn:
  431. tgt2 = self.cross_attn(tgt, key=memory, attn_mask=cross_mask)
  432. tgt = self.norm2(tgt + self.dropout2(tgt2))
  433. tgt = self.norm3(tgt + self.dropout3(self.mlp(tgt)))
  434. return tgt
  435. class PositionalEncoding(nn.Layer):
  436. """Inject some information about the relative or absolute position of the tokens
  437. in the sequence. The positional encodings have the same dimension as
  438. the embeddings, so that the two can be summed. Here, we use sine and cosine
  439. functions of different frequencies.
  440. .. math::
  441. \text{PosEncoder}(pos, 2i) = sin(pos/10000^(2i/d_model))
  442. \text{PosEncoder}(pos, 2i+1) = cos(pos/10000^(2i/d_model))
  443. \text{where pos is the word position and i is the embed idx)
  444. Args:
  445. d_model: the embed dim (required).
  446. dropout: the dropout value (default=0.1).
  447. max_len: the max. length of the incoming sequence (default=5000).
  448. Examples:
  449. >>> pos_encoder = PositionalEncoding(d_model)
  450. """
  451. def __init__(self, dropout, dim, max_len=5000):
  452. super(PositionalEncoding, self).__init__()
  453. self.dropout = nn.Dropout(p=dropout)
  454. pe = paddle.zeros([max_len, dim])
  455. position = paddle.arange(0, max_len, dtype=paddle.float32).unsqueeze(1)
  456. div_term = paddle.exp(
  457. paddle.arange(0, dim, 2).astype("float32") * (-math.log(10000.0) / dim)
  458. )
  459. pe[:, 0::2] = paddle.sin(position * div_term)
  460. pe[:, 1::2] = paddle.cos(position * div_term)
  461. pe = paddle.unsqueeze(pe, 0)
  462. pe = paddle.transpose(pe, [1, 0, 2])
  463. self.register_buffer("pe", pe)
  464. def forward(self, x):
  465. """Inputs of forward function
  466. Args:
  467. x: the sequence fed to the positional encoder model (required).
  468. Shape:
  469. x: [sequence length, batch size, embed dim]
  470. output: [sequence length, batch size, embed dim]
  471. Examples:
  472. >>> output = pos_encoder(x)
  473. """
  474. x = x.transpose([1, 0, 2])
  475. x = x + self.pe[: x.shape[0], :]
  476. return self.dropout(x).transpose([1, 0, 2])
  477. class PositionalEncoding_2d(nn.Layer):
  478. """Inject some information about the relative or absolute position of the tokens
  479. in the sequence. The positional encodings have the same dimension as
  480. the embeddings, so that the two can be summed. Here, we use sine and cosine
  481. functions of different frequencies.
  482. .. math::
  483. \text{PosEncoder}(pos, 2i) = sin(pos/10000^(2i/d_model))
  484. \text{PosEncoder}(pos, 2i+1) = cos(pos/10000^(2i/d_model))
  485. \text{where pos is the word position and i is the embed idx)
  486. Args:
  487. d_model: the embed dim (required).
  488. dropout: the dropout value (default=0.1).
  489. max_len: the max. length of the incoming sequence (default=5000).
  490. Examples:
  491. >>> pos_encoder = PositionalEncoding(d_model)
  492. """
  493. def __init__(self, dropout, dim, max_len=5000):
  494. super(PositionalEncoding_2d, self).__init__()
  495. self.dropout = nn.Dropout(p=dropout)
  496. pe = paddle.zeros([max_len, dim])
  497. position = paddle.arange(0, max_len, dtype=paddle.float32).unsqueeze(1)
  498. div_term = paddle.exp(
  499. paddle.arange(0, dim, 2).astype("float32") * (-math.log(10000.0) / dim)
  500. )
  501. pe[:, 0::2] = paddle.sin(position * div_term)
  502. pe[:, 1::2] = paddle.cos(position * div_term)
  503. pe = paddle.transpose(paddle.unsqueeze(pe, 0), [1, 0, 2])
  504. self.register_buffer("pe", pe)
  505. self.avg_pool_1 = nn.AdaptiveAvgPool2D((1, 1))
  506. self.linear1 = nn.Linear(dim, dim)
  507. self.linear1.weight.data.fill_(1.0)
  508. self.avg_pool_2 = nn.AdaptiveAvgPool2D((1, 1))
  509. self.linear2 = nn.Linear(dim, dim)
  510. self.linear2.weight.data.fill_(1.0)
  511. def forward(self, x):
  512. """Inputs of forward function
  513. Args:
  514. x: the sequence fed to the positional encoder model (required).
  515. Shape:
  516. x: [sequence length, batch size, embed dim]
  517. output: [sequence length, batch size, embed dim]
  518. Examples:
  519. >>> output = pos_encoder(x)
  520. """
  521. w_pe = self.pe[: x.shape[-1], :]
  522. w1 = self.linear1(self.avg_pool_1(x).squeeze()).unsqueeze(0)
  523. w_pe = w_pe * w1
  524. w_pe = paddle.transpose(w_pe, [1, 2, 0])
  525. w_pe = paddle.unsqueeze(w_pe, 2)
  526. h_pe = self.pe[: x.shape.shape[-2], :]
  527. w2 = self.linear2(self.avg_pool_2(x).squeeze()).unsqueeze(0)
  528. h_pe = h_pe * w2
  529. h_pe = paddle.transpose(h_pe, [1, 2, 0])
  530. h_pe = paddle.unsqueeze(h_pe, 3)
  531. x = x + w_pe + h_pe
  532. x = paddle.transpose(
  533. paddle.reshape(x, [x.shape[0], x.shape[1], x.shape[2] * x.shape[3]]),
  534. [2, 0, 1],
  535. )
  536. return self.dropout(x)
  537. class Embeddings(nn.Layer):
  538. def __init__(self, d_model, vocab, padding_idx=None, scale_embedding=True):
  539. super(Embeddings, self).__init__()
  540. self.embedding = nn.Embedding(vocab, d_model, padding_idx=padding_idx)
  541. w0 = np.random.normal(0.0, d_model**-0.5, (vocab, d_model)).astype(np.float32)
  542. self.embedding.weight.set_value(w0)
  543. self.d_model = d_model
  544. self.scale_embedding = scale_embedding
  545. def forward(self, x):
  546. if self.scale_embedding:
  547. x = self.embedding(x)
  548. return x * math.sqrt(self.d_model)
  549. return self.embedding(x)
  550. class Beam:
  551. """Beam search"""
  552. def __init__(self, size, device=False):
  553. self.size = size
  554. self._done = False
  555. # The score for each translation on the beam.
  556. self.scores = paddle.zeros((size,), dtype=paddle.float32)
  557. self.all_scores = []
  558. # The backpointers at each time-step.
  559. self.prev_ks = []
  560. # The outputs at each time-step.
  561. self.next_ys = [paddle.full((size,), 0, dtype=paddle.int64)]
  562. self.next_ys[0][0] = 2
  563. def get_current_state(self):
  564. "Get the outputs for the current timestep."
  565. return self.get_tentative_hypothesis()
  566. def get_current_origin(self):
  567. "Get the backpointers for the current timestep."
  568. return self.prev_ks[-1]
  569. @property
  570. def done(self):
  571. return self._done
  572. def advance(self, word_prob):
  573. "Update beam status and check if finished or not."
  574. num_words = word_prob.shape[1]
  575. # Sum the previous scores.
  576. if len(self.prev_ks) > 0:
  577. beam_lk = word_prob + self.scores.unsqueeze(1).expand_as(word_prob)
  578. else:
  579. beam_lk = word_prob[0]
  580. flat_beam_lk = beam_lk.reshape([-1])
  581. best_scores, best_scores_id = flat_beam_lk.topk(
  582. self.size, 0, True, True
  583. ) # 1st sort
  584. self.all_scores.append(self.scores)
  585. self.scores = best_scores
  586. # bestScoresId is flattened as a (beam x word) array,
  587. # so we need to calculate which word and beam each score came from
  588. prev_k = best_scores_id // num_words
  589. self.prev_ks.append(prev_k)
  590. self.next_ys.append(best_scores_id - prev_k * num_words)
  591. # End condition is when top-of-beam is EOS.
  592. if self.next_ys[-1][0] == 3:
  593. self._done = True
  594. self.all_scores.append(self.scores)
  595. return self._done
  596. def sort_scores(self):
  597. "Sort the scores."
  598. return self.scores, paddle.to_tensor(
  599. [i for i in range(int(self.scores.shape[0]))], dtype="int32"
  600. )
  601. def get_the_best_score_and_idx(self):
  602. "Get the score of the best in the beam."
  603. scores, ids = self.sort_scores()
  604. return scores[1], ids[1]
  605. def get_tentative_hypothesis(self):
  606. "Get the decoded sequence for the current timestep."
  607. if len(self.next_ys) == 1:
  608. dec_seq = self.next_ys[0].unsqueeze(1)
  609. else:
  610. _, keys = self.sort_scores()
  611. hyps = [self.get_hypothesis(k) for k in keys]
  612. hyps = [[2] + h for h in hyps]
  613. dec_seq = paddle.to_tensor(hyps, dtype="int64")
  614. return dec_seq
  615. def get_hypothesis(self, k):
  616. """Walk back to construct the full hypothesis."""
  617. hyp = []
  618. for j in range(len(self.prev_ks) - 1, -1, -1):
  619. hyp.append(self.next_ys[j + 1][k])
  620. k = self.prev_ks[j][k]
  621. return list(map(lambda x: x.item(), hyp[::-1]))