decode.py 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  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 collections
  15. import warnings
  16. import numpy as np
  17. import paddle
  18. from paddle.common_ops_import import default_main_program
  19. from paddle.framework import in_dynamic_mode
  20. from ..base.data_feeder import convert_dtype
  21. __all__ = []
  22. class ArrayWrapper:
  23. def __init__(self, x):
  24. self.array = [x]
  25. def append(self, x):
  26. self.array.append(x)
  27. return self
  28. def __getitem__(self, item):
  29. return self.array.__getitem__(item)
  30. class Decoder:
  31. """
  32. Decoder is the base class for any decoder instance used in `dynamic_decode`.
  33. It provides interface for output generation for one time step, which can be
  34. used to generate sequences.
  35. The key abstraction provided by Decoder is:
  36. 1. :code:`(initial_input, initial_state, finished) = initialize(inits)` ,
  37. which generates the input and state for the first decoding step, and gives the
  38. initial status telling whether each sequence in the batch is finished.
  39. It would be called once before the decoding iterations.
  40. 2. :code:`(output, next_state, next_input, finished) = step(time, input, state)` ,
  41. which transforms the input and state to the output and new state, generates
  42. input for the next decoding step, and emits the flag indicating finished status.
  43. It is the main part for each decoding iteration.
  44. 3. :code:`(final_outputs, final_state) = finalize(outputs, final_state, sequence_lengths)` ,
  45. which revises the outputs(stack of all time steps' output) and final state(state from the
  46. last decoding step) to get the counterpart for special usage.
  47. Not necessary to be implemented if no need to revise the stacked outputs and
  48. state from the last decoding step. If implemented, it would be called after
  49. the decoding iterations.
  50. Decoder is more general compared to RNNCell, since the returned `next_input`
  51. and `finished` make it can determine the input and when to finish by itself
  52. when used in dynamic decoding. Decoder always wraps a RNNCell instance though
  53. not necessary.
  54. """
  55. def initialize(self, inits):
  56. r"""
  57. Called once before the decoding iterations.
  58. Parameters:
  59. inits: Argument provided by the caller.
  60. Returns:
  61. tuple: A tuple( :code:`(initial_inputs, initial_states, finished)` ). \
  62. `initial_inputs` and `initial_states` both are a (possibly nested \
  63. structure of) tensor variable[s], and `finished` is a tensor with \
  64. bool data type.
  65. """
  66. raise NotImplementedError
  67. def step(self, time, inputs, states, **kwargs):
  68. r"""
  69. Called per step of decoding.
  70. Parameters:
  71. time(Tensor): A Tensor with shape :math:`[1]` provided by the caller.
  72. The data type is int64.
  73. inputs(Tensor): A (possibly nested structure of) tensor variable[s].
  74. states(Tensor): A (possibly nested structure of) tensor variable[s].
  75. **kwargs: Additional keyword arguments, provided by the caller.
  76. Returns:
  77. tuple: A tuple( :code:(outputs, next_states, next_inputs, finished)` ). \
  78. `next_inputs` and `next_states` both are a (possibly nested \
  79. structure of) tensor variable[s], and the structure, shape and \
  80. data type must be same as the counterpart from input arguments. \
  81. `outputs` is a (possibly nested structure of) tensor variable[s]. \
  82. `finished` is a Tensor with bool data type.
  83. """
  84. raise NotImplementedError
  85. def finalize(self, outputs, final_states, sequence_lengths):
  86. r"""
  87. Called once after the decoding iterations if implemented.
  88. Parameters:
  89. outputs(Tensor): A (possibly nested structure of) tensor variable[s].
  90. The structure and data type is same as `output_dtype`.
  91. The tensor stacks all time steps' output thus has shape
  92. :math:`[time\_step, batch\_size, ...]` , which is done by the caller.
  93. final_states(Tensor): A (possibly nested structure of) tensor variable[s].
  94. It is the `next_states` returned by `decoder.step` at last decoding step,
  95. thus has the same structure, shape and data type with states at any time
  96. step.
  97. Returns:
  98. tuple: A tuple( :code:`(final_outputs, final_states)` ). \
  99. `final_outputs` and `final_states` both are a (possibly nested \
  100. structure of) tensor variable[s].
  101. """
  102. raise NotImplementedError
  103. @property
  104. def tracks_own_finished(self):
  105. """
  106. Describes whether the Decoder keeps track of finished states by itself.
  107. `decoder.step()` would emit a bool `finished` value at each decoding
  108. step. The emited `finished` can be used to determine whether every
  109. batch entries is finished directly, or it can be combined with the
  110. finished tracker keeped in `dynamic_decode` by performing a logical OR
  111. to take the already finished into account.
  112. If `False`, the latter would be took when performing `dynamic_decode`,
  113. which is the default. Otherwise, the former would be took, which uses
  114. the finished value emited by the decoder as all batch entry finished
  115. status directly, and it is the case when batch entries might be
  116. reordered such as beams in BeamSearchDecoder.
  117. Returns:
  118. bool: A python bool `False`.
  119. """
  120. return False
  121. class BeamSearchDecoder(Decoder):
  122. """
  123. Decoder with beam search decoding strategy. It wraps a cell to get probabilities,
  124. and follows a beam search step to calculate scores and select candidate
  125. token ids for each decoding step.
  126. Please refer to `Beam search <https://en.wikipedia.org/wiki/Beam_search>`_
  127. for more details.
  128. Note:
  129. When decoding with beam search, the `inputs` and `states` of cell
  130. would be tiled to `beam_size` (unsqueeze and tile), resulting to shapes like
  131. `[batch_size * beam_size, ...]` , which is built into `BeamSearchDecoder` and
  132. done automatically. Thus any other tensor with shape `[batch_size, ...]` used
  133. in `cell.call` needs to be tiled manually first, which can be completed by using
  134. :code:`BeamSearchDecoder.tile_beam_merge_with_batch` . The most common case
  135. for this is the encoder output in attention mechanism.
  136. Parameters:
  137. cell (RNNCellBase): An instance of `RNNCellBase` or object with the same interface.
  138. start_token (int): The start token id.
  139. end_token (int): The end token id.
  140. beam_size (int): The beam width used in beam search.
  141. embedding_fn (optional): A callable to apply to selected candidate ids.
  142. Mostly it is an embedding layer to transform ids to embeddings,
  143. and the returned value acts as the `input` argument for `cell.call`.
  144. If not provided, the id to embedding transformation must be built into
  145. `cell.call`. Default None.
  146. output_fn (optional): A callable to apply to the cell's output prior to
  147. calculate scores and select candidate token ids. Default None.
  148. Returns:
  149. BeamSearchDecoder: An instance of decoder which can be used in \
  150. `paddle.nn.dynamic_decode` to implement decoding.
  151. Examples:
  152. .. code-block:: python
  153. >>> import numpy as np
  154. >>> import paddle
  155. >>> from paddle.nn import BeamSearchDecoder, dynamic_decode
  156. >>> from paddle.nn import GRUCell, Linear, Embedding
  157. >>> trg_embeder = Embedding(100, 32)
  158. >>> output_layer = Linear(32, 32)
  159. >>> decoder_cell = GRUCell(input_size=32, hidden_size=32)
  160. >>> decoder = BeamSearchDecoder(decoder_cell,
  161. ... start_token=0,
  162. ... end_token=1,
  163. ... beam_size=4,
  164. ... embedding_fn=trg_embeder,
  165. ... output_fn=output_layer)
  166. ...
  167. """
  168. def __init__(
  169. self,
  170. cell,
  171. start_token,
  172. end_token,
  173. beam_size,
  174. embedding_fn=None,
  175. output_fn=None,
  176. ):
  177. """
  178. Constructor of BeamSearchDecoder.
  179. Parameters:
  180. cell(RNNCellBase): An instance of `RNNCellBase` or object with the same interface.
  181. start_token(int): The start token id.
  182. end_token(int): The end token id.
  183. beam_size(int): The beam width used in beam search.
  184. embedding_fn(optional): A callable to apply to selected candidate ids.
  185. Mostly it is an embedding layer to transform ids to embeddings,
  186. and the returned value acts as the `input` argument for `cell.call`.
  187. If not provided, the id to embedding transformation must be built into
  188. `cell.call`. Default None.
  189. output_fn(optional): A callable to apply to the cell's output prior to
  190. calculate scores and select candidate token ids. Default None.
  191. """
  192. self.cell = cell
  193. self.embedding_fn = embedding_fn
  194. self.output_fn = output_fn
  195. self.start_token = start_token
  196. self.end_token = end_token
  197. self.beam_size = beam_size
  198. @staticmethod
  199. def tile_beam_merge_with_batch(x, beam_size):
  200. r"""
  201. Tile the batch dimension of a tensor. Specifically, this function takes
  202. a tensor t shaped `[batch_size, s0, s1, ...]` composed of minibatch
  203. entries `t[0], ..., t[batch_size - 1]` and tiles it to have a shape
  204. `[batch_size * beam_size, s0, s1, ...]` composed of minibatch entries
  205. `t[0], t[0], ..., t[1], t[1], ...` where each minibatch entry is repeated
  206. `beam_size` times.
  207. Parameters:
  208. x(Tensor): A tensor with shape `[batch_size, ...]`. The data type
  209. should be float32, float64, int32, int64 or bool.
  210. beam_size(int): The beam width used in beam search.
  211. Returns:
  212. Tensor: A tensor with shape `[batch_size * beam_size, ...]`, whose \
  213. data type is same as `x`.
  214. """
  215. x = paddle.unsqueeze(x, [1]) # [batch_size, 1, ...]
  216. expand_times = [1] * len(x.shape)
  217. expand_times[1] = beam_size
  218. x = paddle.tile(x, expand_times) # [batch_size, beam_size, ...]
  219. x = paddle.transpose(
  220. x, list(range(2, len(x.shape))) + [0, 1]
  221. ) # [..., batch_size, beam_size]
  222. # use 0 to copy to avoid wrong shape
  223. x = paddle.reshape(
  224. x, shape=[0] * (len(x.shape) - 2) + [-1]
  225. ) # [..., batch_size * beam_size]
  226. x = paddle.transpose(
  227. x, [len(x.shape) - 1] + list(range(0, len(x.shape) - 1))
  228. ) # [batch_size * beam_size, ...]
  229. return x
  230. def _split_batch_beams(self, x):
  231. r"""
  232. Reshape a tensor with shape `[batch_size * beam_size, ...]` to a new
  233. tensor with shape `[batch_size, beam_size, ...]`.
  234. Parameters:
  235. x(Tensor): A tensor with shape `[batch_size * beam_size, ...]`. The
  236. data type should be float32, float64, int32, int64 or bool.
  237. Returns:
  238. Tensor: A tensor with shape `[batch_size, beam_size, ...]`, whose \
  239. data type is same as `x`.
  240. """
  241. # TODO: avoid fake shape in compile-time like tile_beam_merge_with_batch
  242. return paddle.reshape(x, shape=[-1, self.beam_size] + list(x.shape[1:]))
  243. def _merge_batch_beams(self, x):
  244. r"""
  245. Reshape a tensor with shape `[batch_size, beam_size, ...]` to a new
  246. tensor with shape `[batch_size * beam_size, ...]`.
  247. Parameters:
  248. x(Tensor): A tensor with shape `[batch_size, beam_size, ...]`. The
  249. data type should be float32, float64, int32, int64 or bool.
  250. Returns:
  251. Tensor: A tensor with shape `[batch_size * beam_size, ...]`, whose \
  252. data type is same as `x`.
  253. """
  254. # TODO: avoid fake shape in compile-time like tile_beam_merge_with_batch
  255. return paddle.reshape(x, shape=[-1] + list(x.shape[2:]))
  256. def _expand_to_beam_size(self, x):
  257. r"""
  258. This function takes a tensor t shaped `[batch_size, s0, s1, ...]` composed
  259. of minibatch entries `t[0], ..., t[batch_size - 1]` and tiles it to have a
  260. shape `[batch_size, beam_size, s0, s1, ...]` composed of minibatch entries
  261. `t[0], t[0], ..., t[1], t[1], ...` where each minibatch entry is repeated
  262. `beam_size` times.
  263. Parameters:
  264. x(Tensor): A tensor with shape `[batch_size, ...]`, The data type
  265. should be float32, float64, int32, int64 or bool.
  266. Returns:
  267. Tensor: A tensor with shape `[batch_size, beam_size, ...]`, whose \
  268. data type is same as `x`.
  269. """
  270. x = paddle.unsqueeze(x, [1])
  271. expand_times = [1] * len(x.shape)
  272. expand_times[1] = self.beam_size
  273. x = paddle.tile(x, expand_times)
  274. return x
  275. def _mask_probs(self, probs, finished):
  276. r"""
  277. Mask log probabilities. It forces finished beams to allocate all probability
  278. mass to eos and unfinished beams to remain unchanged.
  279. Parameters:
  280. probs(Tensor): A tensor with shape `[batch_size, beam_size, vocab_size]`,
  281. representing the log probabilities. Its data type should be float32 or float64.
  282. finished(Tensor): A tensor with shape `[batch_size, beam_size]`,
  283. representing the finished status for all beams. Its data type
  284. should be bool.
  285. Returns:
  286. Tensor: A tensor with the same shape and data type as `x`, \
  287. where unfinished beams stay unchanged and finished beams are \
  288. replaced with a tensor with all probability on the EOS token.
  289. """
  290. # TODO: use where_op
  291. finished = paddle.cast(finished, dtype=probs.dtype)
  292. probs = paddle.multiply(
  293. paddle.tile(
  294. paddle.unsqueeze(finished, [2]), [1, 1, self.vocab_size]
  295. ),
  296. self.noend_mask_tensor,
  297. ) - paddle.multiply(probs, (finished - 1).unsqueeze([2]))
  298. return probs
  299. def _gather(self, x, indices, batch_size):
  300. r"""
  301. Gather from the tensor `x` using `indices`.
  302. Parameters:
  303. x(Tensor): A tensor with shape `[batch_size, beam_size, ...]`.
  304. indices(Tensor): A `int64` tensor with shape `[batch_size, beam_size]`,
  305. representing the indices that we use to gather.
  306. batch_size(Tensor): A tensor with shape `[1]`. Its data type should
  307. be int32 or int64.
  308. Returns:
  309. Tensor: A tensor with the same shape and data type as `x`, \
  310. representing the gathered tensor.
  311. """
  312. # TODO: compatibility of int32 and int64
  313. batch_size = (
  314. paddle.cast(batch_size, indices.dtype)
  315. if batch_size.dtype != indices.dtype
  316. else batch_size
  317. )
  318. batch_size.stop_gradient = True # TODO: remove this
  319. batch_pos = paddle.tile(
  320. paddle.unsqueeze(
  321. paddle.arange(0, batch_size, 1, dtype=indices.dtype), [1]
  322. ),
  323. [1, self.beam_size],
  324. )
  325. topk_coordinates = paddle.stack([batch_pos, indices], axis=2)
  326. topk_coordinates.stop_gradient = True
  327. return paddle.gather_nd(x, topk_coordinates)
  328. class OutputWrapper(
  329. collections.namedtuple(
  330. "OutputWrapper", ("scores", "predicted_ids", "parent_ids")
  331. )
  332. ):
  333. """
  334. The structure for the returned value `outputs` of `decoder.step`.
  335. A namedtuple includes scores, predicted_ids, parent_ids as fields.
  336. """
  337. pass
  338. class StateWrapper(
  339. collections.namedtuple(
  340. "StateWrapper", ("cell_states", "log_probs", "finished", "lengths")
  341. )
  342. ):
  343. """
  344. The structure for the argument `states` of `decoder.step`.
  345. A namedtuple includes cell_states, log_probs, finished, lengths as fields.
  346. """
  347. pass
  348. def initialize(self, initial_cell_states):
  349. r"""
  350. Initialize the BeamSearchDecoder.
  351. Parameters:
  352. initial_cell_states(Tensor): A (possibly nested structure of)
  353. tensor variable[s]. An argument provided by the caller.
  354. Returns:
  355. tuple: A tuple( :code:`(initial_inputs, initial_states, finished)` ). \
  356. `initial_inputs` is a tensor t filled by `start_token` with shape \
  357. `[batch_size, beam_size]` when `embedding_fn` is None, or the \
  358. returned value of `embedding_fn(t)` when `embedding_fn` is provided. \
  359. `initial_states` is a nested structure(namedtuple including cell_states, \
  360. log_probs, finished, lengths as fields) of tensor variables, where \
  361. `log_probs, finished, lengths` all has a tensor value shaped \
  362. `[batch_size, beam_size]` with data type `float32, bool, int64`. \
  363. cell_states has a value with the same structure as the input \
  364. argument `initial_cell_states` but with tiled shape `[batch_size, beam_size, ...]`. \
  365. `finished` is a `bool` tensor filled by False with shape `[batch_size, beam_size]`.
  366. """
  367. self.kinf = 1e9
  368. state = paddle.utils.flatten(initial_cell_states)[0]
  369. self.batch_size = paddle.shape(state)[0]
  370. self.start_token_tensor = paddle.full(
  371. shape=[1], dtype="int64", fill_value=self.start_token
  372. )
  373. self.end_token_tensor = paddle.full(
  374. shape=[1], dtype="int64", fill_value=self.end_token
  375. )
  376. init_cell_states = paddle.utils.map_structure(
  377. self._expand_to_beam_size, initial_cell_states
  378. )
  379. init_inputs = paddle.full(
  380. shape=[self.batch_size, self.beam_size],
  381. fill_value=self.start_token_tensor,
  382. dtype=self.start_token_tensor.dtype,
  383. )
  384. log_probs = paddle.tile(
  385. paddle.assign(
  386. np.array(
  387. [[0.0] + [-self.kinf] * (self.beam_size - 1)],
  388. dtype="float32",
  389. )
  390. ),
  391. [self.batch_size, 1],
  392. )
  393. if paddle.get_default_dtype() == "float64":
  394. log_probs = paddle.cast(log_probs, "float64")
  395. init_finished = paddle.full(
  396. shape=[paddle.shape(state)[0], self.beam_size],
  397. fill_value=False,
  398. dtype="bool",
  399. )
  400. init_lengths = paddle.zeros_like(init_inputs)
  401. init_inputs = (
  402. self.embedding_fn(init_inputs) if self.embedding_fn else init_inputs
  403. )
  404. return (
  405. init_inputs,
  406. self.StateWrapper(
  407. init_cell_states, log_probs, init_finished, init_lengths
  408. ),
  409. init_finished,
  410. )
  411. def _beam_search_step(self, time, logits, next_cell_states, beam_state):
  412. r"""
  413. Calculate scores and select candidate token ids.
  414. Parameters:
  415. time(Tensor): An `int64` tensor with shape `[1]` provided by the caller,
  416. representing the current time step number of decoding.
  417. logits(Tensor): A tensor with shape `[batch_size, beam_size, vocab_size]`,
  418. representing the logits at the current time step. Its data type is float32.
  419. next_cell_states(Tensor): A (possibly nested structure of) tensor variable[s].
  420. It has the same structure, shape and data type as the `cell_states` of
  421. `initial_states` returned by `initialize()`. It represents the next state
  422. from the cell.
  423. beam_state(Tensor): A structure of tensor variables.
  424. It is same as the `initial_states` returned by `initialize()` for
  425. the first decoding step and `beam_search_state` returned by
  426. `step()` for the others.
  427. Returns:
  428. tuple: A tuple( :code:`(beam_search_output, beam_search_state)` ). \
  429. `beam_search_output` is a namedtuple(including scores, predicted_ids, \
  430. parent_ids as fields) of tensor variables, where \
  431. `scores, predicted_ids, parent_ids` all has a tensor value shaped \
  432. `[batch_size, beam_size]` with data type `float32, int64, int64`.
  433. `beam_search_state` has the same structure, shape and data type \
  434. as the input argument `beam_state`.
  435. """
  436. self.vocab_size = logits.shape[-1]
  437. self.vocab_size_tensor = paddle.full(
  438. shape=[1], dtype="int64", fill_value=self.vocab_size
  439. )
  440. noend_array = [-self.kinf] * self.vocab_size
  441. noend_array[self.end_token] = 0
  442. self.noend_mask_tensor = paddle.assign(np.array(noend_array, "float32"))
  443. if paddle.get_default_dtype() == "float64":
  444. self.noend_mask_tensor = paddle.cast(
  445. self.noend_mask_tensor, "float64"
  446. )
  447. step_log_probs = paddle.log(paddle.nn.functional.softmax(logits))
  448. step_log_probs = self._mask_probs(step_log_probs, beam_state.finished)
  449. log_probs = paddle.add(
  450. step_log_probs, beam_state.log_probs.unsqueeze([2])
  451. )
  452. # TODO: length penalty
  453. scores = log_probs
  454. scores = paddle.reshape(scores, [-1, self.beam_size * self.vocab_size])
  455. # TODO: add grad for topk then this beam search can be used to train
  456. topk_scores, topk_indices = paddle.topk(x=scores, k=self.beam_size)
  457. beam_indices = paddle.floor_divide(topk_indices, self.vocab_size_tensor)
  458. token_indices = paddle.remainder(topk_indices, self.vocab_size_tensor)
  459. next_log_probs = self._gather(
  460. paddle.reshape(log_probs, [-1, self.beam_size * self.vocab_size]),
  461. topk_indices,
  462. self.batch_size,
  463. )
  464. next_cell_states = paddle.utils.map_structure(
  465. lambda x: self._gather(x, beam_indices, self.batch_size),
  466. next_cell_states,
  467. )
  468. next_finished = self._gather(
  469. beam_state.finished, beam_indices, self.batch_size
  470. )
  471. next_lengths = self._gather(
  472. beam_state.lengths, beam_indices, self.batch_size
  473. )
  474. next_lengths = next_lengths + paddle.cast(
  475. paddle.logical_not(next_finished), beam_state.lengths.dtype
  476. )
  477. next_finished = paddle.logical_or(
  478. next_finished,
  479. paddle.equal(token_indices, self.end_token_tensor),
  480. )
  481. beam_search_output = self.OutputWrapper(
  482. topk_scores, token_indices, beam_indices
  483. )
  484. beam_search_state = self.StateWrapper(
  485. next_cell_states, next_log_probs, next_finished, next_lengths
  486. )
  487. return beam_search_output, beam_search_state
  488. def step(self, time, inputs, states, **kwargs):
  489. r"""
  490. Perform a beam search decoding step, which uses `cell` to get probabilities,
  491. and follows a beam search step to calculate scores and select candidate
  492. token ids.
  493. Parameters:
  494. time(Tensor): An `int64` tensor with shape `[1]` provided by the caller,
  495. representing the current time step number of decoding.
  496. inputs(Tensor): A tensor variable. It is same as `initial_inputs`
  497. returned by `initialize()` for the first decoding step and
  498. `next_inputs` returned by `step()` for the others.
  499. states(Tensor): A structure of tensor variables.
  500. It is same as the `initial_states` returned by `initialize()` for
  501. the first decoding step and `beam_search_state` returned by
  502. `step()` for the others.
  503. **kwargs: Additional keyword arguments, provided by the caller.
  504. Returns:
  505. tuple: A tuple( :code:`(beam_search_output, beam_search_state, next_inputs, finished)` ). \
  506. `beam_search_state` and `next_inputs` have the same structure, \
  507. shape and data type as the input arguments `states` and `inputs` separately. \
  508. `beam_search_output` is a namedtuple(including scores, predicted_ids, \
  509. parent_ids as fields) of tensor variables, where \
  510. `scores, predicted_ids, parent_ids` all has a tensor value shaped \
  511. `[batch_size, beam_size]` with data type `float32, int64, int64`. \
  512. `finished` is a `bool` tensor with shape `[batch_size, beam_size]`.
  513. """
  514. inputs = paddle.utils.map_structure(self._merge_batch_beams, inputs)
  515. cell_states = paddle.utils.map_structure(
  516. self._merge_batch_beams, states.cell_states
  517. )
  518. cell_outputs, next_cell_states = self.cell(
  519. inputs, cell_states, **kwargs
  520. )
  521. cell_outputs = paddle.utils.map_structure(
  522. self._split_batch_beams, cell_outputs
  523. )
  524. next_cell_states = paddle.utils.map_structure(
  525. self._split_batch_beams, next_cell_states
  526. )
  527. if self.output_fn is not None:
  528. cell_outputs = self.output_fn(cell_outputs)
  529. beam_search_output, beam_search_state = self._beam_search_step(
  530. time=time,
  531. logits=cell_outputs,
  532. next_cell_states=next_cell_states,
  533. beam_state=states,
  534. )
  535. finished = beam_search_state.finished
  536. sample_ids = beam_search_output.predicted_ids
  537. sample_ids.stop_gradient = True
  538. next_inputs = (
  539. self.embedding_fn(sample_ids) if self.embedding_fn else sample_ids
  540. )
  541. return (beam_search_output, beam_search_state, next_inputs, finished)
  542. def finalize(self, outputs, final_states, sequence_lengths):
  543. r"""
  544. Use `gather_tree` to backtrace along the beam search tree and construct
  545. the full predicted sequences.
  546. Parameters:
  547. outputs(Tensor): A structure(namedtuple) of tensor variables,
  548. The structure and data type is same as `output_dtype`.
  549. The tensor stacks all time steps' output thus has shape
  550. `[time_step, batch_size, ...]`, which is done by the caller.
  551. final_states(Tensor): A structure(namedtuple) of tensor variables.
  552. It is the `next_states` returned by `decoder.step` at last
  553. decoding step, thus has the same structure, shape and data type
  554. with states at any time step.
  555. sequence_lengths(Tensor): An `int64` tensor shaped `[batch_size, beam_size]`.
  556. It contains sequence lengths for each beam determined during
  557. decoding.
  558. Returns:
  559. tuple: A tuple( :code:`(predicted_ids, final_states)` ). \
  560. `predicted_ids` is an `int64` tensor shaped \
  561. `[time_step, batch_size, beam_size]`. `final_states` is the same \
  562. as the input argument `final_states`.
  563. """
  564. predicted_ids = paddle.nn.functional.gather_tree(
  565. outputs.predicted_ids, outputs.parent_ids
  566. )
  567. # TODO: use FinalBeamSearchDecoderOutput as output
  568. return predicted_ids, final_states
  569. @property
  570. def tracks_own_finished(self):
  571. """
  572. BeamSearchDecoder reorders its beams and their finished state. Thus it
  573. conflicts with `dynamic_decode` function's tracking of finished states.
  574. Setting this property to true to avoid early stopping of decoding due
  575. to mismanagement of the finished state.
  576. Returns:
  577. bool: A python bool `True`.
  578. """
  579. return True
  580. def _dynamic_decode_imperative(
  581. decoder,
  582. inits=None,
  583. max_step_num=None,
  584. output_time_major=False,
  585. impute_finished=False,
  586. is_test=False,
  587. return_length=False,
  588. **kwargs
  589. ):
  590. def _maybe_copy(state, new_state, step_mask):
  591. # TODO: use where_op
  592. state_dtype = state.dtype
  593. if convert_dtype(state_dtype) in ["bool"]:
  594. state = paddle.cast(state, dtype="float32")
  595. new_state = paddle.cast(new_state, dtype="float32")
  596. if step_mask.dtype != state.dtype:
  597. step_mask = paddle.cast(step_mask, dtype=state.dtype)
  598. # otherwise, renamed bool gradients of would be summed up leading
  599. # to sum(bool) error.
  600. step_mask = step_mask.unsqueeze([1])
  601. step_mask.stop_gradient = True
  602. new_state = paddle.multiply(state, step_mask) - paddle.multiply(
  603. new_state, (step_mask - 1)
  604. )
  605. if convert_dtype(state_dtype) in ["bool"]:
  606. new_state = paddle.cast(new_state, dtype=state_dtype)
  607. return new_state
  608. initial_inputs, initial_states, initial_finished = decoder.initialize(inits)
  609. inputs, states, finished = (
  610. initial_inputs,
  611. initial_states,
  612. initial_finished,
  613. )
  614. cond = paddle.logical_not(paddle.all(initial_finished))
  615. sequence_lengths = paddle.cast(paddle.zeros_like(initial_finished), "int64")
  616. outputs = None
  617. step_idx = 0
  618. step_idx_tensor = paddle.full(shape=[1], fill_value=step_idx, dtype="int64")
  619. while np.array(cond).item():
  620. (step_outputs, next_states, next_inputs, next_finished) = decoder.step(
  621. step_idx_tensor, inputs, states, **kwargs
  622. )
  623. if not decoder.tracks_own_finished:
  624. # BeamSearchDecoder would track it own finished, since
  625. # beams would be reordered and the finished status of each
  626. # entry might change. Otherwise, perform logical OR which
  627. # would not change the already finished.
  628. next_finished = paddle.logical_or(next_finished, finished)
  629. # To confirm states.finished/finished be consistent with
  630. # next_finished.
  631. paddle.assign(next_finished, finished)
  632. next_sequence_lengths = paddle.add(
  633. sequence_lengths,
  634. paddle.cast(
  635. paddle.logical_not(finished), sequence_lengths.dtype
  636. ),
  637. )
  638. if impute_finished: # rectify the states for the finished.
  639. next_states = paddle.utils.map_structure(
  640. lambda x, y: _maybe_copy(x, y, finished),
  641. states,
  642. next_states,
  643. )
  644. else:
  645. warnings.warn(
  646. "`next_states` has no `lengths` attribute, the returned `sequence_lengths` would be all zeros."
  647. ) if not hasattr(next_states, "lengths") else None
  648. next_sequence_lengths = getattr(
  649. next_states, "lengths", sequence_lengths
  650. )
  651. outputs = (
  652. paddle.utils.map_structure(lambda x: ArrayWrapper(x), step_outputs)
  653. if step_idx == 0
  654. else paddle.utils.map_structure(
  655. lambda x, x_array: x_array.append(x), step_outputs, outputs
  656. )
  657. )
  658. inputs, states, finished, sequence_lengths = (
  659. next_inputs,
  660. next_states,
  661. next_finished,
  662. next_sequence_lengths,
  663. )
  664. step_idx_tensor = paddle.increment(x=step_idx_tensor, value=1.0)
  665. step_idx += 1
  666. cond = paddle.logical_not(paddle.all(finished))
  667. if max_step_num is not None and step_idx > max_step_num:
  668. break
  669. final_outputs = paddle.utils.map_structure(
  670. lambda x: paddle.stack(x.array, axis=0), outputs
  671. )
  672. final_states = states
  673. try:
  674. final_outputs, final_states = decoder.finalize(
  675. final_outputs, final_states, sequence_lengths
  676. )
  677. except NotImplementedError:
  678. pass
  679. if not output_time_major:
  680. final_outputs = paddle.utils.map_structure(
  681. lambda x: paddle.transpose(
  682. x, [1, 0] + list(range(2, len(x.shape)))
  683. ),
  684. final_outputs,
  685. )
  686. return (
  687. (final_outputs, final_states, sequence_lengths)
  688. if return_length
  689. else (final_outputs, final_states)
  690. )
  691. def _dynamic_decode_declarative(
  692. decoder,
  693. inits=None,
  694. max_step_num=None,
  695. output_time_major=False,
  696. impute_finished=False,
  697. is_test=False,
  698. return_length=False,
  699. **kwargs
  700. ):
  701. initial_inputs, initial_states, initial_finished = decoder.initialize(inits)
  702. global_inputs, global_states, global_finished = (
  703. initial_inputs,
  704. initial_states,
  705. initial_finished,
  706. )
  707. global_finished.stop_gradient = True
  708. step_idx = paddle.full(shape=[1], fill_value=0, dtype="int64")
  709. cond = paddle.logical_not(paddle.all(initial_finished))
  710. if max_step_num is not None:
  711. max_step_num = paddle.full(
  712. shape=[1], fill_value=max_step_num, dtype="int64"
  713. )
  714. while_op = paddle.static.nn.control_flow.While(cond, is_test=is_test)
  715. sequence_lengths = paddle.cast(paddle.zeros_like(initial_finished), "int64")
  716. sequence_lengths.stop_gradient = True
  717. if is_test:
  718. # for test, reuse inputs and states variables to save memory
  719. inputs = paddle.utils.map_structure(lambda x: x, initial_inputs)
  720. states = paddle.utils.map_structure(lambda x: x, initial_states)
  721. else:
  722. # inputs and states of all steps must be saved for backward and training
  723. inputs_arrays = paddle.utils.map_structure(
  724. lambda x: paddle.tensor.array.array_write(x, step_idx),
  725. initial_inputs,
  726. )
  727. states_arrays = paddle.utils.map_structure(
  728. lambda x: paddle.tensor.array.array_write(x, step_idx),
  729. initial_states,
  730. )
  731. def _maybe_copy(state, new_state, step_mask):
  732. # TODO: use where_op
  733. state_dtype = state.dtype
  734. if convert_dtype(state_dtype) in ["bool"]:
  735. state = paddle.cast(state, dtype="float32")
  736. new_state = paddle.cast(new_state, dtype="float32")
  737. if step_mask.dtype != state.dtype:
  738. step_mask = paddle.cast(step_mask, dtype=state.dtype)
  739. # otherwise, renamed bool gradients of would be summed up leading
  740. # to sum(bool) error.
  741. step_mask = step_mask.unsqueeze([1])
  742. step_mask.stop_gradient = True
  743. new_state = paddle.multiply(state, step_mask) - paddle.multiply(
  744. new_state, (step_mask - 1)
  745. )
  746. if convert_dtype(state_dtype) in ["bool"]:
  747. new_state = paddle.cast(new_state, dtype=state_dtype)
  748. return new_state
  749. def _transpose_batch_time(x):
  750. return paddle.transpose(x, [1, 0] + list(range(2, len(x.shape))))
  751. def _create_array_out_of_while(dtype):
  752. current_block_idx = default_main_program().current_block_idx
  753. default_main_program().current_block_idx = (
  754. default_main_program().current_block().parent_idx
  755. )
  756. tensor_array = paddle.tensor.array.create_array(dtype)
  757. default_main_program().current_block_idx = current_block_idx
  758. return tensor_array
  759. # While
  760. with while_op.block():
  761. if not is_test:
  762. inputs = paddle.utils.map_structure(
  763. lambda array: paddle.tensor.array.array_read(array, step_idx),
  764. inputs_arrays,
  765. )
  766. states = paddle.utils.map_structure(
  767. lambda array: paddle.tensor.array.array_read(array, step_idx),
  768. states_arrays,
  769. )
  770. (outputs, next_states, next_inputs, next_finished) = decoder.step(
  771. step_idx, inputs, states, **kwargs
  772. )
  773. if not decoder.tracks_own_finished:
  774. # BeamSearchDecoder would track it own finished, since beams would
  775. # be reordered and the finished status of each entry might change.
  776. # Otherwise, perform logical OR which would not change the already
  777. # finished.
  778. next_finished = paddle.logical_or(next_finished, global_finished)
  779. next_sequence_lengths = paddle.add(
  780. sequence_lengths,
  781. paddle.cast(
  782. paddle.logical_not(global_finished),
  783. sequence_lengths.dtype,
  784. ),
  785. )
  786. if impute_finished: # rectify the states for the finished.
  787. next_states = paddle.utils.map_structure(
  788. lambda x, y: _maybe_copy(x, y, global_finished),
  789. states,
  790. next_states,
  791. )
  792. else:
  793. warnings.warn(
  794. "`next_states` has no `lengths` attribute, the returned `sequence_lengths` would be all zeros."
  795. ) if not hasattr(next_states, "lengths") else None
  796. next_sequence_lengths = getattr(
  797. next_states, "lengths", sequence_lengths
  798. )
  799. # create tensor array in global block after dtype[s] of outputs can be got
  800. outputs_arrays = paddle.utils.map_structure(
  801. lambda x: _create_array_out_of_while(x.dtype), outputs
  802. )
  803. paddle.utils.map_structure(
  804. lambda x, x_array: paddle.tensor.array.array_write(
  805. x, i=step_idx, array=x_array
  806. ),
  807. outputs,
  808. outputs_arrays,
  809. )
  810. step_idx = paddle.increment(x=step_idx, value=1.0)
  811. # update the global_finished first, since it might be also in states of
  812. # decoder, which otherwise would write a stale finished status to array
  813. paddle.assign(next_finished, global_finished)
  814. paddle.assign(next_sequence_lengths, sequence_lengths)
  815. if is_test:
  816. paddle.utils.map_structure(
  817. paddle.assign, next_inputs, global_inputs
  818. )
  819. paddle.utils.map_structure(
  820. paddle.assign, next_states, global_states
  821. )
  822. else:
  823. paddle.utils.map_structure(
  824. lambda x, x_array: paddle.tensor.array.array_write(
  825. x, i=step_idx, array=x_array
  826. ),
  827. next_inputs,
  828. inputs_arrays,
  829. )
  830. paddle.utils.map_structure(
  831. lambda x, x_array: paddle.tensor.array.array_write(
  832. x, i=step_idx, array=x_array
  833. ),
  834. next_states,
  835. states_arrays,
  836. )
  837. if max_step_num is not None:
  838. paddle.logical_and(
  839. paddle.logical_not(paddle.all(global_finished)),
  840. paddle.less_equal(step_idx, max_step_num),
  841. cond,
  842. )
  843. else:
  844. paddle.logical_not(paddle.all(global_finished), cond)
  845. final_outputs = paddle.utils.map_structure(
  846. lambda array: paddle.tensor.manipulation.tensor_array_to_tensor(
  847. array, axis=0, use_stack=True
  848. )[0],
  849. outputs_arrays,
  850. )
  851. if is_test:
  852. final_states = global_states
  853. else:
  854. final_states = paddle.utils.map_structure(
  855. lambda array: paddle.tensor.array.array_read(array, step_idx),
  856. states_arrays,
  857. )
  858. try:
  859. final_outputs, final_states = decoder.finalize(
  860. final_outputs, final_states, sequence_lengths
  861. )
  862. except NotImplementedError:
  863. pass
  864. if not output_time_major:
  865. final_outputs = paddle.utils.map_structure(
  866. _transpose_batch_time, final_outputs
  867. )
  868. return (
  869. (final_outputs, final_states, sequence_lengths)
  870. if return_length
  871. else (final_outputs, final_states)
  872. )
  873. def dynamic_decode(
  874. decoder,
  875. inits=None,
  876. max_step_num=None,
  877. output_time_major=False,
  878. impute_finished=False,
  879. is_test=False,
  880. return_length=False,
  881. **kwargs
  882. ):
  883. r"""
  884. Dynamic decoding performs :code:`decoder.step()` repeatedly until the returned
  885. Tensor indicating finished status contains all True values or the number of
  886. decoding step reaches to :attr:`max_step_num`.
  887. :code:`decoder.initialize()` would be called once before the decoding loop.
  888. If the `decoder` has implemented `finalize` method, :code:`decoder.finalize()`
  889. would be called once after the decoding loop.
  890. Parameters:
  891. decoder(Decoder): An instance of `Decoder`.
  892. inits(object, optional): Argument passed to `decoder.initialize`.
  893. Default `None`.
  894. max_step_num(int, optional): The maximum number of steps. If not provided,
  895. decode until the decoder is fully done, or in other words, the returned
  896. Tensor by :code:`decoder.step()` indicating finished status contains
  897. all True. Default `None`.
  898. output_time_major(bool, optional): Indicate the data layout of Tensor included
  899. in the final outputs(the first returned value of this method). If
  900. attr:`False`, the data layout would be batch major with shape
  901. `[batch_size, seq_len, ...]`. If attr:`True`, the data layout would
  902. be time major with shape `[seq_len, batch_size, ...]`. Default: `False`.
  903. impute_finished(bool, optional): If `True` and `decoder.tracks_own_finished`
  904. is False, then states get copied through for batch entries which are
  905. marked as finished, which differs with the unfinished using the new states
  906. returned by :code:`decoder.step()` and ensures that the final states have
  907. the correct values. Otherwise, states wouldn't be copied through when
  908. finished. If the returned `final_states` is needed, it should be set as
  909. True, which causes some slowdown. Default `False`.
  910. is_test(bool, optional): A flag indicating whether to use test mode. In
  911. test mode, it is more memory saving. Default `False`.
  912. return_length(bool, optional): A flag indicating whether to return an
  913. extra Tensor variable in the output tuple, which stores the actual
  914. lengths of all decoded sequences. Default `False`.
  915. **kwargs: Additional keyword arguments. Arguments passed to `decoder.step`.
  916. Returns:
  917. - final_outputs (Tensor, nested structure of Tensor), each Tensor in :code:`final_outputs` is the stacked of all decoding steps' outputs, which might be revised
  918. by :code:`decoder.finalize()` if the decoder has implemented finalize.
  919. And :code:`final_outputs` has the same structure and data types as the :code:`outputs`
  920. returned by :code:`decoder.step()`
  921. - final_states (Tensor, nested structure of Tensor), :code:`final_states` is the counterpart at last time step of initial states \
  922. returned by :code:`decoder.initialize()` , thus has the same structure
  923. with it and has tensors with same shapes and data types.
  924. - sequence_lengths (Tensor), stores the actual lengths of all decoded sequences.
  925. sequence_lengths is provided only if :code:`return_length` is True.
  926. Examples:
  927. .. code-block:: python
  928. >>> import paddle
  929. >>> from paddle.nn import BeamSearchDecoder, dynamic_decode
  930. >>> from paddle.nn import GRUCell, Linear, Embedding
  931. >>> trg_embeder = Embedding(100, 32)
  932. >>> output_layer = Linear(32, 32)
  933. >>> decoder_cell = GRUCell(input_size=32, hidden_size=32)
  934. >>> decoder = BeamSearchDecoder(decoder_cell,
  935. ... start_token=0,
  936. ... end_token=1,
  937. ... beam_size=4,
  938. ... embedding_fn=trg_embeder,
  939. ... output_fn=output_layer)
  940. >>> encoder_output = paddle.ones((4, 8, 32), dtype=paddle.get_default_dtype())
  941. >>> outputs = dynamic_decode(decoder=decoder,
  942. ... inits=decoder_cell.get_initial_states(encoder_output),
  943. ... max_step_num=10)
  944. >>> print(outputs[0].shape)
  945. [4, 11, 4]
  946. """
  947. if in_dynamic_mode():
  948. return _dynamic_decode_imperative(
  949. decoder,
  950. inits,
  951. max_step_num,
  952. output_time_major,
  953. impute_finished,
  954. is_test,
  955. return_length,
  956. **kwargs
  957. )
  958. else:
  959. return _dynamic_decode_declarative(
  960. decoder,
  961. inits,
  962. max_step_num,
  963. output_time_major,
  964. impute_finished,
  965. is_test,
  966. return_length,
  967. **kwargs
  968. )