In tasks such as machine translation and image to text,
a [sequence decoder](https://github.com/PaddlePaddle/book/blob/develop/08.machine_translation/README.md) is necessary to generate sequences.
This documentation describes how to implement the sequence decoder as an operator.
## Beam Search based Decoder
The [beam search algorithm](https://en.wikipedia.org/wiki/Beam_search) is necessary when generating sequences,
it is a heuristic search algorithm that explores the paths by expanding the most promising node in a limited set.
In the old version of PaddlePaddle, a C++ class `RecurrentGradientMachine` implements the general sequence decoder based on beam search,
due to the complexity, the implementation relays on a lot of special data structures,
quite trivial and hard to be customized by users.
There are a lot of heuristic tricks in the sequence generation tasks,
so the flexibility of sequence decoder is very important to users.
During PaddlePaddle's refactoring work,
some new concept is proposed such as [LoDTensor](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/framework/lod_tensor.md) and [TensorArray](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/design/tensor_array.md) that can better support sequence usage,
and they can help to make the implementation of beam search based sequence decoder **more transparent and modular** .
For example, the RNN sates, candidates IDs and probabilities of beam search can be represented as `LoDTensors`;
the selected candidate's IDs in each time step can be stored in a `TensorArray`, and `Packed` to the sentences translated.
## Changing LoD's absolute offset to relative offsets
The current `LoDTensor` is designed to store levels of variable-length sequences,
it stores several arrays of integers each represents a level.
The integers in each level represents the begin and end (not inclusive) offset of a sequence **in the underlying tensor**,
let's call this format the **absolute-offset LoD** for clear.
The relative-offset LoD can fast retrieve any sequence but fails to represent empty sequences, for example, a two-level LoD is as follows
```python
[[0, 3, 9]
[0, 2, 3, 3, 3, 9]]
```
The first level tells that there are two sequences:
- the first's offset is `[0, 3)`
- the second's offset is `[3, 9)`
while on the second level, there are several empty sequences that both begin and end at `3`.
It is impossible to tell how many empty second-level sequences exist in the first-level sequences.
There are many scenarios that relay on empty sequence representation,
such as machine translation or image to text, one instance has no translations or the empty candidate set for a prefix.
So let's introduce another format of LoD,
it stores **the offsets of the lower level sequences** and is called **relative-offset** LoD.
For example, to represent the same sequences of the above data
```python
[[0, 3, 6]
[0, 2, 3, 3, 3, 9]]
```
the first level represents that there are two sequences,
their offsets in the second-level LoD is `[0, 3)` and `[3, 5)`.
The second level is the same with the relative offset example because the lower level is a tensor.
It is easy to find out the second sequence in the first-level LoD has two empty sequences.
The following demos are based on relative-offset LoD.
## Usage in a simple machine translation model
Let's start from a simple machine translation model that is simplified from [machine translation chapter](https://github.com/PaddlePaddle/book/tree/develop/08.machine_translation) to draw a simple blueprint of what a sequence decoder can do and how to use it.
The model has an encoder that learns the semantic vector from a sequence,
and a decoder which uses the sequence decoder to generate new sentences.
The `decoder.beam_search` is a operator that given the candidates and the scores of translations including the candidates,
return the result of the beam search algorithm.
In this way, users can customize anything on the inputs or outputs of beam search, for example, two ways to prune some translation prefixes
1. meke the correspondind elements in `topk_generated_scores` zero or some small values, beam_search will discard this candidate.
2. remove some specific candidate in `selected_ids`
3. get the final `translation_ids`, remove the translation sequence in it.
The implementation of sequence decoder can reuse the C++ class [RNNAlgorithm](https://github.com/Superjom/Paddle/blob/68cac3c0f8451fe62a4cdf156747d6dc0ee000b3/paddle/operators/dynamic_recurrent_op.h#L30),
so the python syntax is quite similar to a [RNN](https://github.com/Superjom/Paddle/blob/68cac3c0f8451fe62a4cdf156747d6dc0ee000b3/doc/design/block.md#blocks-with-for-and-rnnop).
Both of them are two-level `LoDTensors`
- the first level represents `batch_size` of (source) sentences;
- the second level represents the candidate ID sets for translation prefix.
for example, 3 source sentences to translate, and has 2, 3, 1 candidates.
Unlike an RNN, in sequence decoder, the previous state and the current state have different LoD and shape,
a `lod_expand` operator is used to expand the LoD of the previous state to fit the current state.
For example, the previous state
* LoD is `[0, 1, 3][0, 2, 5, 6]`
* content of tensor is `a1 a2 b1 b2 b3 c1`
the current state stored in `encoder_ctx_expanded`
* LoD is `[0, 2, 7][0 3 5 8 9 11 11]`
* the content is
- a1 a1 a1 (a1 has 3 candidates, so the state should be copied 3 times for each candidates)
- a2 a2
- b1 b1 b1
- b2
- b3 b3
- None (c1 has 0 candidates, so c1 is dropped)
Benefit from the relative offset LoD, empty candidate set can be represented naturally.
the status in each time step can be stored in `TensorArray`, and `Pack`ed to a final LoDTensor, the corresponding syntax is
```python
decoder.output(selected_ids)
decoder.output(selected_generation_scores)
```
the `selected_ids` is the candidate ids for the prefixes,
it will be `Packed` by `TensorArray` to a two-level `LoDTensor`,
the first level represents the source sequences,
the second level represents generated sequences.
Pack the `selected_scores` will get a `LoDTensor` that stores scores of each candidate of translations.
Pack the `selected_generation_scores` will get a `LoDTensor`, and each tail is the probability of the translation.
<liclass="toctree-l2"><aclass="reference internal"href="../../getstarted/build_and_install/index_en.html">Install and Build</a><ul>
<liclass="toctree-l3"><aclass="reference internal"href="../../getstarted/build_and_install/docker_install_en.html">PaddlePaddle in Docker Containers</a></li>
<liclass="toctree-l3"><aclass="reference internal"href="../../getstarted/build_and_install/build_from_source_en.html">Installing from Sources</a></li>
<liclass="toctree-l2"><aclass="reference internal"href="../../howto/usage/k8s/k8s_en.html">Paddle On Kubernetes</a></li>
<liclass="toctree-l2"><aclass="reference internal"href="../../howto/usage/k8s/k8s_aws_en.html">Distributed PaddlePaddle Training on AWS with Kubernetes</a></li>
<liclass="toctree-l2"><aclass="reference internal"href="../../howto/dev/build_en.html">Build PaddlePaddle from Source Code and Run Unit Test</a></li>
<liclass="toctree-l2"><aclass="reference internal"href="../../howto/dev/new_layer_en.html">Write New Layers</a></li>
<spanid="design-sequence-decoder-generating-lodtensors"></span><h1>Design: Sequence Decoder Generating LoDTensors<aclass="headerlink"href="#design-sequence-decoder-generating-lodtensors"title="Permalink to this headline">¶</a></h1>
<p>In tasks such as machine translation and image to text,
a <aclass="reference external"href="https://github.com/PaddlePaddle/book/blob/develop/08.machine_translation/README.md">sequence decoder</a> is necessary to generate sequences.</p>
<p>This documentation describes how to implement the sequence decoder as an operator.</p>
<spanid="beam-search-based-decoder"></span><h2>Beam Search based Decoder<aclass="headerlink"href="#beam-search-based-decoder"title="Permalink to this headline">¶</a></h2>
<p>The <aclass="reference external"href="https://en.wikipedia.org/wiki/Beam_search">beam search algorithm</a> is necessary when generating sequences,
it is a heuristic search algorithm that explores the paths by expanding the most promising node in a limited set.</p>
<p>In the old version of PaddlePaddle, a C++ class <codeclass="docutils literal"><spanclass="pre">RecurrentGradientMachine</span></code> implements the general sequence decoder based on beam search,
due to the complexity, the implementation relays on a lot of special data structures,
quite trivial and hard to be customized by users.</p>
<p>There are a lot of heuristic tricks in the sequence generation tasks,
so the flexibility of sequence decoder is very important to users.</p>
<p>During PaddlePaddle’s refactoring work,
some new concept is proposed such as <aclass="reference external"href="https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/framework/lod_tensor.md">LoDTensor</a> and <aclass="reference external"href="https://github.com/PaddlePaddle/Paddle/blob/develop/doc/design/tensor_array.md">TensorArray</a> that can better support sequence usage,
and they can help to make the implementation of beam search based sequence decoder <strong>more transparent and modular</strong> .</p>
<p>For example, the RNN sates, candidates IDs and probabilities of beam search can be represented as <codeclass="docutils literal"><spanclass="pre">LoDTensors</span></code>;
the selected candidate’s IDs in each time step can be stored in a <codeclass="docutils literal"><spanclass="pre">TensorArray</span></code>, and <codeclass="docutils literal"><spanclass="pre">Packed</span></code> to the sentences translated.</p>
<spanid="changing-lod-s-absolute-offset-to-relative-offsets"></span><h2>Changing LoD’s absolute offset to relative offsets<aclass="headerlink"href="#changing-lod-s-absolute-offset-to-relative-offsets"title="Permalink to this headline">¶</a></h2>
<p>The current <codeclass="docutils literal"><spanclass="pre">LoDTensor</span></code> is designed to store levels of variable-length sequences,
it stores several arrays of integers each represents a level.</p>
<p>The integers in each level represents the begin and end (not inclusive) offset of a sequence <strong>in the underlying tensor</strong>,
let’s call this format the <strong>absolute-offset LoD</strong> for clear.</p>
<p>The relative-offset LoD can fast retrieve any sequence but fails to represent empty sequences, for example, a two-level LoD is as follows</p>
<p>The first level tells that there are two sequences:</p>
<ulclass="simple">
<li>the first’s offset is <codeclass="docutils literal"><spanclass="pre">[0,</span><spanclass="pre">3)</span></code></li>
<li>the second’s offset is <codeclass="docutils literal"><spanclass="pre">[3,</span><spanclass="pre">9)</span></code></li>
</ul>
<p>while on the second level, there are several empty sequences that both begin and end at <codeclass="docutils literal"><spanclass="pre">3</span></code>.
It is impossible to tell how many empty second-level sequences exist in the first-level sequences.</p>
<p>There are many scenarios that relay on empty sequence representation,
such as machine translation or image to text, one instance has no translations or the empty candidate set for a prefix.</p>
<p>So let’s introduce another format of LoD,
it stores <strong>the offsets of the lower level sequences</strong> and is called <strong>relative-offset</strong> LoD.</p>
<p>For example, to represent the same sequences of the above data</p>
<p>the first level represents that there are two sequences,
their offsets in the second-level LoD is <codeclass="docutils literal"><spanclass="pre">[0,</span><spanclass="pre">3)</span></code> and <codeclass="docutils literal"><spanclass="pre">[3,</span><spanclass="pre">5)</span></code>.</p>
<p>The second level is the same with the relative offset example because the lower level is a tensor.
It is easy to find out the second sequence in the first-level LoD has two empty sequences.</p>
<p>The following demos are based on relative-offset LoD.</p>
<spanid="usage-in-a-simple-machine-translation-model"></span><h2>Usage in a simple machine translation model<aclass="headerlink"href="#usage-in-a-simple-machine-translation-model"title="Permalink to this headline">¶</a></h2>
<p>Let’s start from a simple machine translation model that is simplified from <aclass="reference external"href="https://github.com/PaddlePaddle/book/tree/develop/08.machine_translation">machine translation chapter</a> to draw a simple blueprint of what a sequence decoder can do and how to use it.</p>
<p>The model has an encoder that learns the semantic vector from a sequence,
and a decoder which uses the sequence decoder to generate new sentences.</p>
<spanclass="n">decoder_mem</span><spanclass="o">=</span><spanclass="n">decoder</span><spanclass="o">.</span><spanclass="n">memory</span><spanclass="p">(</span><spanclass="n">init</span><spanclass="o">=</span><spanclass="n">encoder_ctx</span><spanclass="p">)</span><spanclass="c1"># mark the memory</span>
<spanclass="n">generated_ids</span><spanclass="o">=</span><spanclass="n">decoder</span><spanclass="o">.</span><spanclass="n">memory</span><spanclass="p">()</span><spanclass="c1"># TODO init to batch_size <s>s</span>
<spanclass="n">generated_scores</span><spanclass="o">=</span><spanclass="n">decoder</span><spanclass="o">.</span><spanclass="n">memory</span><spanclass="p">()</span><spanclass="c1"># TODO init to batch_size 1s or 0s</span>
<spanclass="n">decoder_mem</span><spanclass="o">.</span><spanclass="n">update</span><spanclass="p">(</span><spanclass="n">cur_mem</span><spanclass="p">)</span><spanclass="c1"># tells how to update state</span>
<p>The <codeclass="docutils literal"><spanclass="pre">decoder.beam_search</span></code> is a operator that given the candidates and the scores of translations including the candidates,
return the result of the beam search algorithm.</p>
<p>In this way, users can customize anything on the inputs or outputs of beam search, for example, two ways to prune some translation prefixes</p>
<olclass="simple">
<li>meke the correspondind elements in <codeclass="docutils literal"><spanclass="pre">topk_generated_scores</span></code> zero or some small values, beam_search will discard this candidate.</li>
<li>remove some specific candidate in <codeclass="docutils literal"><spanclass="pre">selected_ids</span></code></li>
<li>get the final <codeclass="docutils literal"><spanclass="pre">translation_ids</span></code>, remove the translation sequence in it.</li>
</ol>
<p>The implementation of sequence decoder can reuse the C++ class <aclass="reference external"href="https://github.com/Superjom/Paddle/blob/68cac3c0f8451fe62a4cdf156747d6dc0ee000b3/paddle/operators/dynamic_recurrent_op.h#L30">RNNAlgorithm</a>,
so the python syntax is quite similar to a <aclass="reference external"href="https://github.com/Superjom/Paddle/blob/68cac3c0f8451fe62a4cdf156747d6dc0ee000b3/doc/design/block.md#blocks-with-for-and-rnnop">RNN</a>.</p>
<p>Both of them are two-level <codeclass="docutils literal"><spanclass="pre">LoDTensors</span></code></p>
<ulclass="simple">
<li>the first level represents <codeclass="docutils literal"><spanclass="pre">batch_size</span></code> of (source) sentences;</li>
<li>the second level represents the candidate ID sets for translation prefix.</li>
</ul>
<p>for example, 3 source sentences to translate, and has 2, 3, 1 candidates.</p>
<p>Unlike an RNN, in sequence decoder, the previous state and the current state have different LoD and shape,
a <codeclass="docutils literal"><spanclass="pre">lod_expand</span></code> operator is used to expand the LoD of the previous state to fit the current state.</p>
<p>For example, the previous state</p>
<ulclass="simple">
<li>LoD is <codeclass="docutils literal"><spanclass="pre">[0,</span><spanclass="pre">1,</span><spanclass="pre">3][0,</span><spanclass="pre">2,</span><spanclass="pre">5,</span><spanclass="pre">6]</span></code></li>
<li>content of tensor is <codeclass="docutils literal"><spanclass="pre">a1</span><spanclass="pre">a2</span><spanclass="pre">b1</span><spanclass="pre">b2</span><spanclass="pre">b3</span><spanclass="pre">c1</span></code></li>
</ul>
<p>the current state stored in <codeclass="docutils literal"><spanclass="pre">encoder_ctx_expanded</span></code></p>
<ulclass="simple">
<li>LoD is <codeclass="docutils literal"><spanclass="pre">[0,</span><spanclass="pre">2,</span><spanclass="pre">7][0</span><spanclass="pre">3</span><spanclass="pre">5</span><spanclass="pre">8</span><spanclass="pre">9</span><spanclass="pre">11</span><spanclass="pre">11]</span></code></li>
<li>the content is<ul>
<li>a1 a1 a1 (a1 has 3 candidates, so the state should be copied 3 times for each candidates)</li>
<li>a2 a2</li>
<li>b1 b1 b1</li>
<li>b2</li>
<li>b3 b3</li>
<li>None (c1 has 0 candidates, so c1 is dropped)</li>
</ul>
</li>
</ul>
<p>Benefit from the relative offset LoD, empty candidate set can be represented naturally.</p>
<p>the status in each time step can be stored in <codeclass="docutils literal"><spanclass="pre">TensorArray</span></code>, and <codeclass="docutils literal"><spanclass="pre">Pack</span></code>ed to a final LoDTensor, the corresponding syntax is</p>
<p>the <codeclass="docutils literal"><spanclass="pre">selected_ids</span></code> is the candidate ids for the prefixes,
it will be <codeclass="docutils literal"><spanclass="pre">Packed</span></code> by <codeclass="docutils literal"><spanclass="pre">TensorArray</span></code> to a two-level <codeclass="docutils literal"><spanclass="pre">LoDTensor</span></code>,
the first level represents the source sequences,
the second level represents generated sequences.</p>
<p>Pack the <codeclass="docutils literal"><spanclass="pre">selected_scores</span></code> will get a <codeclass="docutils literal"><spanclass="pre">LoDTensor</span></code> that stores scores of each candidate of translations.</p>
<p>Pack the <codeclass="docutils literal"><spanclass="pre">selected_generation_scores</span></code> will get a <codeclass="docutils literal"><spanclass="pre">LoDTensor</span></code>, and each tail is the probability of the translation.</p>
<spanid="lod-and-shape-changes-during-decoding"></span><h2>LoD and shape changes during decoding<aclass="headerlink"href="#lod-and-shape-changes-during-decoding"title="Permalink to this headline">¶</a></h2>
</p><p>According the image above, the only phrase to change LoD is beam search.</p>
</div>
<divclass="section"id="beam-search-design">
<spanid="beam-search-design"></span><h2>Beam search design<aclass="headerlink"href="#beam-search-design"title="Permalink to this headline">¶</a></h2>
<p>The beam search algorthm will be implemented as one method of the sequence decoder, it has 3 inputs</p>
<olclass="simple">
<li><codeclass="docutils literal"><spanclass="pre">topk_ids</span></code>, top K candidate ids for each prefix.</li>
<li><codeclass="docutils literal"><spanclass="pre">topk_scores</span></code>, the corresponding scores for <codeclass="docutils literal"><spanclass="pre">topk_ids</span></code></li>
<li><codeclass="docutils literal"><spanclass="pre">generated_scores</span></code>, the score of the prefixes.</li>
</ol>
<p>All of the are LoDTensors, so that the sequence affilication is clear.
Beam search will keep a beam for each prefix and select a smaller candidate set for each prefix.</p>
<p>It will return three variables</p>
<olclass="simple">
<li><codeclass="docutils literal"><spanclass="pre">selected_ids</span></code>, the final candidate beam search function selected for the next step.</li>
<li><codeclass="docutils literal"><spanclass="pre">selected_scores</span></code>, the scores for the candidates.</li>
<li><codeclass="docutils literal"><spanclass="pre">generated_scores</span></code>, the updated scores for each prefixes (with the new candidates appended).</li>
<spanid="introducing-the-lod-based-pack-and-unpack-methods-in-tensorarray"></span><h2>Introducing the LoD-based <codeclass="docutils literal"><spanclass="pre">Pack</span></code> and <codeclass="docutils literal"><spanclass="pre">Unpack</span></code> methods in <codeclass="docutils literal"><spanclass="pre">TensorArray</span></code><aclass="headerlink"href="#introducing-the-lod-based-pack-and-unpack-methods-in-tensorarray"title="Permalink to this headline">¶</a></h2>
<p>The <codeclass="docutils literal"><spanclass="pre">selected_ids</span></code>, <codeclass="docutils literal"><spanclass="pre">selected_scores</span></code> and <codeclass="docutils literal"><spanclass="pre">generated_scores</span></code> are LoDTensors,
and they exist in each time step,
so it is natural to store them in arrays.</p>
<p>Currently, PaddlePaddle has a module called <codeclass="docutils literal"><spanclass="pre">TensorArray</span></code> which can store an array of tensors,
the results of beam search are better to store in a <codeclass="docutils literal"><spanclass="pre">TensorArray</span></code>.</p>
<p>The <codeclass="docutils literal"><spanclass="pre">Pack</span></code> and <codeclass="docutils literal"><spanclass="pre">UnPack</span></code> in <codeclass="docutils literal"><spanclass="pre">TensorArray</span></code> are used to package tensors in the array to a <codeclass="docutils literal"><spanclass="pre">LoDTensor</span></code> or split the <codeclass="docutils literal"><spanclass="pre">LoDTensor</span></code> to an array of tensors.
It needs some extensions to support pack or unpack an array of <codeclass="docutils literal"><spanclass="pre">LoDTensors</span></code>.</p>
Built with <ahref="http://sphinx-doc.org/">Sphinx</a> using a <ahref="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <ahref="https://readthedocs.org">Read the Docs</a>.
In tasks such as machine translation and image to text,
a [sequence decoder](https://github.com/PaddlePaddle/book/blob/develop/08.machine_translation/README.md) is necessary to generate sequences.
This documentation describes how to implement the sequence decoder as an operator.
## Beam Search based Decoder
The [beam search algorithm](https://en.wikipedia.org/wiki/Beam_search) is necessary when generating sequences,
it is a heuristic search algorithm that explores the paths by expanding the most promising node in a limited set.
In the old version of PaddlePaddle, a C++ class `RecurrentGradientMachine` implements the general sequence decoder based on beam search,
due to the complexity, the implementation relays on a lot of special data structures,
quite trivial and hard to be customized by users.
There are a lot of heuristic tricks in the sequence generation tasks,
so the flexibility of sequence decoder is very important to users.
During PaddlePaddle's refactoring work,
some new concept is proposed such as [LoDTensor](https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/framework/lod_tensor.md) and [TensorArray](https://github.com/PaddlePaddle/Paddle/blob/develop/doc/design/tensor_array.md) that can better support sequence usage,
and they can help to make the implementation of beam search based sequence decoder **more transparent and modular** .
For example, the RNN sates, candidates IDs and probabilities of beam search can be represented as `LoDTensors`;
the selected candidate's IDs in each time step can be stored in a `TensorArray`, and `Packed` to the sentences translated.
## Changing LoD's absolute offset to relative offsets
The current `LoDTensor` is designed to store levels of variable-length sequences,
it stores several arrays of integers each represents a level.
The integers in each level represents the begin and end (not inclusive) offset of a sequence **in the underlying tensor**,
let's call this format the **absolute-offset LoD** for clear.
The relative-offset LoD can fast retrieve any sequence but fails to represent empty sequences, for example, a two-level LoD is as follows
```python
[[0, 3, 9]
[0, 2, 3, 3, 3, 9]]
```
The first level tells that there are two sequences:
- the first's offset is `[0, 3)`
- the second's offset is `[3, 9)`
while on the second level, there are several empty sequences that both begin and end at `3`.
It is impossible to tell how many empty second-level sequences exist in the first-level sequences.
There are many scenarios that relay on empty sequence representation,
such as machine translation or image to text, one instance has no translations or the empty candidate set for a prefix.
So let's introduce another format of LoD,
it stores **the offsets of the lower level sequences** and is called **relative-offset** LoD.
For example, to represent the same sequences of the above data
```python
[[0, 3, 6]
[0, 2, 3, 3, 3, 9]]
```
the first level represents that there are two sequences,
their offsets in the second-level LoD is `[0, 3)` and `[3, 5)`.
The second level is the same with the relative offset example because the lower level is a tensor.
It is easy to find out the second sequence in the first-level LoD has two empty sequences.
The following demos are based on relative-offset LoD.
## Usage in a simple machine translation model
Let's start from a simple machine translation model that is simplified from [machine translation chapter](https://github.com/PaddlePaddle/book/tree/develop/08.machine_translation) to draw a simple blueprint of what a sequence decoder can do and how to use it.
The model has an encoder that learns the semantic vector from a sequence,
and a decoder which uses the sequence decoder to generate new sentences.
The `decoder.beam_search` is a operator that given the candidates and the scores of translations including the candidates,
return the result of the beam search algorithm.
In this way, users can customize anything on the inputs or outputs of beam search, for example, two ways to prune some translation prefixes
1. meke the correspondind elements in `topk_generated_scores` zero or some small values, beam_search will discard this candidate.
2. remove some specific candidate in `selected_ids`
3. get the final `translation_ids`, remove the translation sequence in it.
The implementation of sequence decoder can reuse the C++ class [RNNAlgorithm](https://github.com/Superjom/Paddle/blob/68cac3c0f8451fe62a4cdf156747d6dc0ee000b3/paddle/operators/dynamic_recurrent_op.h#L30),
so the python syntax is quite similar to a [RNN](https://github.com/Superjom/Paddle/blob/68cac3c0f8451fe62a4cdf156747d6dc0ee000b3/doc/design/block.md#blocks-with-for-and-rnnop).
Both of them are two-level `LoDTensors`
- the first level represents `batch_size` of (source) sentences;
- the second level represents the candidate ID sets for translation prefix.
for example, 3 source sentences to translate, and has 2, 3, 1 candidates.
Unlike an RNN, in sequence decoder, the previous state and the current state have different LoD and shape,
a `lod_expand` operator is used to expand the LoD of the previous state to fit the current state.
For example, the previous state
* LoD is `[0, 1, 3][0, 2, 5, 6]`
* content of tensor is `a1 a2 b1 b2 b3 c1`
the current state stored in `encoder_ctx_expanded`
* LoD is `[0, 2, 7][0 3 5 8 9 11 11]`
* the content is
- a1 a1 a1 (a1 has 3 candidates, so the state should be copied 3 times for each candidates)
- a2 a2
- b1 b1 b1
- b2
- b3 b3
- None (c1 has 0 candidates, so c1 is dropped)
Benefit from the relative offset LoD, empty candidate set can be represented naturally.
the status in each time step can be stored in `TensorArray`, and `Pack`ed to a final LoDTensor, the corresponding syntax is
```python
decoder.output(selected_ids)
decoder.output(selected_generation_scores)
```
the `selected_ids` is the candidate ids for the prefixes,
it will be `Packed` by `TensorArray` to a two-level `LoDTensor`,
the first level represents the source sequences,
the second level represents generated sequences.
Pack the `selected_scores` will get a `LoDTensor` that stores scores of each candidate of translations.
Pack the `selected_generation_scores` will get a `LoDTensor`, and each tail is the probability of the translation.
<p>In tasks such as machine translation and image to text,
a <aclass="reference external"href="https://github.com/PaddlePaddle/book/blob/develop/08.machine_translation/README.md">sequence decoder</a> is necessary to generate sequences.</p>
<p>This documentation describes how to implement the sequence decoder as an operator.</p>
<spanid="beam-search-based-decoder"></span><h2>Beam Search based Decoder<aclass="headerlink"href="#beam-search-based-decoder"title="永久链接至标题">¶</a></h2>
<p>The <aclass="reference external"href="https://en.wikipedia.org/wiki/Beam_search">beam search algorithm</a> is necessary when generating sequences,
it is a heuristic search algorithm that explores the paths by expanding the most promising node in a limited set.</p>
<p>In the old version of PaddlePaddle, a C++ class <codeclass="docutils literal"><spanclass="pre">RecurrentGradientMachine</span></code> implements the general sequence decoder based on beam search,
due to the complexity, the implementation relays on a lot of special data structures,
quite trivial and hard to be customized by users.</p>
<p>There are a lot of heuristic tricks in the sequence generation tasks,
so the flexibility of sequence decoder is very important to users.</p>
<p>During PaddlePaddle’s refactoring work,
some new concept is proposed such as <aclass="reference external"href="https://github.com/PaddlePaddle/Paddle/blob/develop/paddle/framework/lod_tensor.md">LoDTensor</a> and <aclass="reference external"href="https://github.com/PaddlePaddle/Paddle/blob/develop/doc/design/tensor_array.md">TensorArray</a> that can better support sequence usage,
and they can help to make the implementation of beam search based sequence decoder <strong>more transparent and modular</strong> .</p>
<p>For example, the RNN sates, candidates IDs and probabilities of beam search can be represented as <codeclass="docutils literal"><spanclass="pre">LoDTensors</span></code>;
the selected candidate’s IDs in each time step can be stored in a <codeclass="docutils literal"><spanclass="pre">TensorArray</span></code>, and <codeclass="docutils literal"><spanclass="pre">Packed</span></code> to the sentences translated.</p>
<p>The first level tells that there are two sequences:</p>
<ulclass="simple">
<li>the first’s offset is <codeclass="docutils literal"><spanclass="pre">[0,</span><spanclass="pre">3)</span></code></li>
<li>the second’s offset is <codeclass="docutils literal"><spanclass="pre">[3,</span><spanclass="pre">9)</span></code></li>
</ul>
<p>while on the second level, there are several empty sequences that both begin and end at <codeclass="docutils literal"><spanclass="pre">3</span></code>.
It is impossible to tell how many empty second-level sequences exist in the first-level sequences.</p>
<p>There are many scenarios that relay on empty sequence representation,
such as machine translation or image to text, one instance has no translations or the empty candidate set for a prefix.</p>
<p>So let’s introduce another format of LoD,
it stores <strong>the offsets of the lower level sequences</strong> and is called <strong>relative-offset</strong> LoD.</p>
<p>For example, to represent the same sequences of the above data</p>
<p>the first level represents that there are two sequences,
their offsets in the second-level LoD is <codeclass="docutils literal"><spanclass="pre">[0,</span><spanclass="pre">3)</span></code> and <codeclass="docutils literal"><spanclass="pre">[3,</span><spanclass="pre">5)</span></code>.</p>
<p>The second level is the same with the relative offset example because the lower level is a tensor.
It is easy to find out the second sequence in the first-level LoD has two empty sequences.</p>
<p>The following demos are based on relative-offset LoD.</p>
<spanid="usage-in-a-simple-machine-translation-model"></span><h2>Usage in a simple machine translation model<aclass="headerlink"href="#usage-in-a-simple-machine-translation-model"title="永久链接至标题">¶</a></h2>
<p>Let’s start from a simple machine translation model that is simplified from <aclass="reference external"href="https://github.com/PaddlePaddle/book/tree/develop/08.machine_translation">machine translation chapter</a> to draw a simple blueprint of what a sequence decoder can do and how to use it.</p>
<p>The model has an encoder that learns the semantic vector from a sequence,
and a decoder which uses the sequence decoder to generate new sentences.</p>
<spanclass="n">decoder_mem</span><spanclass="o">=</span><spanclass="n">decoder</span><spanclass="o">.</span><spanclass="n">memory</span><spanclass="p">(</span><spanclass="n">init</span><spanclass="o">=</span><spanclass="n">encoder_ctx</span><spanclass="p">)</span><spanclass="c1"># mark the memory</span>
<spanclass="n">generated_ids</span><spanclass="o">=</span><spanclass="n">decoder</span><spanclass="o">.</span><spanclass="n">memory</span><spanclass="p">()</span><spanclass="c1"># TODO init to batch_size <s>s</span>
<spanclass="n">generated_scores</span><spanclass="o">=</span><spanclass="n">decoder</span><spanclass="o">.</span><spanclass="n">memory</span><spanclass="p">()</span><spanclass="c1"># TODO init to batch_size 1s or 0s</span>
<spanclass="n">decoder_mem</span><spanclass="o">.</span><spanclass="n">update</span><spanclass="p">(</span><spanclass="n">cur_mem</span><spanclass="p">)</span><spanclass="c1"># tells how to update state</span>
<p>The <codeclass="docutils literal"><spanclass="pre">decoder.beam_search</span></code> is a operator that given the candidates and the scores of translations including the candidates,
return the result of the beam search algorithm.</p>
<p>In this way, users can customize anything on the inputs or outputs of beam search, for example, two ways to prune some translation prefixes</p>
<olclass="simple">
<li>meke the correspondind elements in <codeclass="docutils literal"><spanclass="pre">topk_generated_scores</span></code> zero or some small values, beam_search will discard this candidate.</li>
<li>remove some specific candidate in <codeclass="docutils literal"><spanclass="pre">selected_ids</span></code></li>
<li>get the final <codeclass="docutils literal"><spanclass="pre">translation_ids</span></code>, remove the translation sequence in it.</li>
</ol>
<p>The implementation of sequence decoder can reuse the C++ class <aclass="reference external"href="https://github.com/Superjom/Paddle/blob/68cac3c0f8451fe62a4cdf156747d6dc0ee000b3/paddle/operators/dynamic_recurrent_op.h#L30">RNNAlgorithm</a>,
so the python syntax is quite similar to a <aclass="reference external"href="https://github.com/Superjom/Paddle/blob/68cac3c0f8451fe62a4cdf156747d6dc0ee000b3/doc/design/block.md#blocks-with-for-and-rnnop">RNN</a>.</p>
<p>Both of them are two-level <codeclass="docutils literal"><spanclass="pre">LoDTensors</span></code></p>
<ulclass="simple">
<li>the first level represents <codeclass="docutils literal"><spanclass="pre">batch_size</span></code> of (source) sentences;</li>
<li>the second level represents the candidate ID sets for translation prefix.</li>
</ul>
<p>for example, 3 source sentences to translate, and has 2, 3, 1 candidates.</p>
<p>Unlike an RNN, in sequence decoder, the previous state and the current state have different LoD and shape,
a <codeclass="docutils literal"><spanclass="pre">lod_expand</span></code> operator is used to expand the LoD of the previous state to fit the current state.</p>
<p>For example, the previous state</p>
<ulclass="simple">
<li>LoD is <codeclass="docutils literal"><spanclass="pre">[0,</span><spanclass="pre">1,</span><spanclass="pre">3][0,</span><spanclass="pre">2,</span><spanclass="pre">5,</span><spanclass="pre">6]</span></code></li>
<li>content of tensor is <codeclass="docutils literal"><spanclass="pre">a1</span><spanclass="pre">a2</span><spanclass="pre">b1</span><spanclass="pre">b2</span><spanclass="pre">b3</span><spanclass="pre">c1</span></code></li>
</ul>
<p>the current state stored in <codeclass="docutils literal"><spanclass="pre">encoder_ctx_expanded</span></code></p>
<ulclass="simple">
<li>LoD is <codeclass="docutils literal"><spanclass="pre">[0,</span><spanclass="pre">2,</span><spanclass="pre">7][0</span><spanclass="pre">3</span><spanclass="pre">5</span><spanclass="pre">8</span><spanclass="pre">9</span><spanclass="pre">11</span><spanclass="pre">11]</span></code></li>
<li>the content is<ul>
<li>a1 a1 a1 (a1 has 3 candidates, so the state should be copied 3 times for each candidates)</li>
<li>a2 a2</li>
<li>b1 b1 b1</li>
<li>b2</li>
<li>b3 b3</li>
<li>None (c1 has 0 candidates, so c1 is dropped)</li>
</ul>
</li>
</ul>
<p>Benefit from the relative offset LoD, empty candidate set can be represented naturally.</p>
<p>the status in each time step can be stored in <codeclass="docutils literal"><spanclass="pre">TensorArray</span></code>, and <codeclass="docutils literal"><spanclass="pre">Pack</span></code>ed to a final LoDTensor, the corresponding syntax is</p>
<p>the <codeclass="docutils literal"><spanclass="pre">selected_ids</span></code> is the candidate ids for the prefixes,
it will be <codeclass="docutils literal"><spanclass="pre">Packed</span></code> by <codeclass="docutils literal"><spanclass="pre">TensorArray</span></code> to a two-level <codeclass="docutils literal"><spanclass="pre">LoDTensor</span></code>,
the first level represents the source sequences,
the second level represents generated sequences.</p>
<p>Pack the <codeclass="docutils literal"><spanclass="pre">selected_scores</span></code> will get a <codeclass="docutils literal"><spanclass="pre">LoDTensor</span></code> that stores scores of each candidate of translations.</p>
<p>Pack the <codeclass="docutils literal"><spanclass="pre">selected_generation_scores</span></code> will get a <codeclass="docutils literal"><spanclass="pre">LoDTensor</span></code>, and each tail is the probability of the translation.</p>
<spanid="lod-and-shape-changes-during-decoding"></span><h2>LoD and shape changes during decoding<aclass="headerlink"href="#lod-and-shape-changes-during-decoding"title="永久链接至标题">¶</a></h2>
<p>The beam search algorthm will be implemented as one method of the sequence decoder, it has 3 inputs</p>
<olclass="simple">
<li><codeclass="docutils literal"><spanclass="pre">topk_ids</span></code>, top K candidate ids for each prefix.</li>
<li><codeclass="docutils literal"><spanclass="pre">topk_scores</span></code>, the corresponding scores for <codeclass="docutils literal"><spanclass="pre">topk_ids</span></code></li>
<li><codeclass="docutils literal"><spanclass="pre">generated_scores</span></code>, the score of the prefixes.</li>
</ol>
<p>All of the are LoDTensors, so that the sequence affilication is clear.
Beam search will keep a beam for each prefix and select a smaller candidate set for each prefix.</p>
<p>It will return three variables</p>
<olclass="simple">
<li><codeclass="docutils literal"><spanclass="pre">selected_ids</span></code>, the final candidate beam search function selected for the next step.</li>
<li><codeclass="docutils literal"><spanclass="pre">selected_scores</span></code>, the scores for the candidates.</li>
<li><codeclass="docutils literal"><spanclass="pre">generated_scores</span></code>, the updated scores for each prefixes (with the new candidates appended).</li>
<spanid="introducing-the-lod-based-pack-and-unpack-methods-in-tensorarray"></span><h2>Introducing the LoD-based <codeclass="docutils literal"><spanclass="pre">Pack</span></code> and <codeclass="docutils literal"><spanclass="pre">Unpack</span></code> methods in <codeclass="docutils literal"><spanclass="pre">TensorArray</span></code><aclass="headerlink"href="#introducing-the-lod-based-pack-and-unpack-methods-in-tensorarray"title="永久链接至标题">¶</a></h2>
<p>The <codeclass="docutils literal"><spanclass="pre">selected_ids</span></code>, <codeclass="docutils literal"><spanclass="pre">selected_scores</span></code> and <codeclass="docutils literal"><spanclass="pre">generated_scores</span></code> are LoDTensors,
and they exist in each time step,
so it is natural to store them in arrays.</p>
<p>Currently, PaddlePaddle has a module called <codeclass="docutils literal"><spanclass="pre">TensorArray</span></code> which can store an array of tensors,
the results of beam search are better to store in a <codeclass="docutils literal"><spanclass="pre">TensorArray</span></code>.</p>
<p>The <codeclass="docutils literal"><spanclass="pre">Pack</span></code> and <codeclass="docutils literal"><spanclass="pre">UnPack</span></code> in <codeclass="docutils literal"><spanclass="pre">TensorArray</span></code> are used to package tensors in the array to a <codeclass="docutils literal"><spanclass="pre">LoDTensor</span></code> or split the <codeclass="docutils literal"><spanclass="pre">LoDTensor</span></code> to an array of tensors.
It needs some extensions to support pack or unpack an array of <codeclass="docutils literal"><spanclass="pre">LoDTensors</span></code>.</p>
Built with <ahref="http://sphinx-doc.org/">Sphinx</a> using a <ahref="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <ahref="https://readthedocs.org">Read the Docs</a>.