rnn_config_en.html 42.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26


<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>RNN Configuration &mdash; PaddlePaddle  documentation</title>
  

  
  

  

  
  
    

  

  
  
27
    <link rel="stylesheet" href="../../_static/css/theme.css" type="text/css" />
28 29 30 31 32
  

  
  
        <link rel="index" title="Index"
33 34 35
              href="../../genindex.html"/>
        <link rel="search" title="Search" href="../../search.html"/>
    <link rel="top" title="PaddlePaddle  documentation" href="../../index.html"/>
36
        <link rel="up" title="RNN Models" href="index_en.html"/>
37
        <link rel="next" title="Tune GPU Performance" href="../optimization/gpu_profiling_en.html"/>
38
        <link rel="prev" title="RNN Models" href="index_en.html"/> 
39 40

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/perfect-scrollbar/0.6.14/css/perfect-scrollbar.min.css" type="text/css" />
41
  <link rel="stylesheet" href="../../_static/css/override.css" type="text/css" />
42 43 44 45 46 47 48 49 50 51 52 53 54
  <script>
  var _hmt = _hmt || [];
  (function() {
    var hm = document.createElement("script");
    hm.src = "//hm.baidu.com/hm.js?b9a314ab40d04d805655aab1deee08ba";
    var s = document.getElementsByTagName("script")[0]; 
    s.parentNode.insertBefore(hm, s);
  })();
  </script>

  

  
55
  <script src="../../_static/js/modernizr.min.js"></script>
56 57 58 59 60 61 62 63

</head>

<body class="wy-body-for-nav" role="document">

  
  <header class="site-header">
    <div class="site-logo">
64
      <a href="/"><img src="../../_static/images/PP_w.png"></a>
65 66 67
    </div>
    <div class="site-nav-links">
      <div class="site-menu">
68
        <a class="fork-on-github" href="https://github.com/PaddlePaddle/Paddle" target="_blank"><i class="fa fa-github"></i>Fork me on Github</a>
69 70 71 72 73 74 75 76 77 78 79 80
        <div class="language-switcher dropdown">
          <a type="button" data-toggle="dropdown">
            <span>English</span>
            <i class="fa fa-angle-up"></i>
            <i class="fa fa-angle-down"></i>
          </a>
          <ul class="dropdown-menu">
            <li><a href="/doc_cn">中文</a></li>
            <li><a href="/doc">English</a></li>
          </ul>
        </div>
        <ul class="site-page-links">
81
          <li><a href="/">Home</a></li>
82 83 84 85
        </ul>
      </div>
      <div class="doc-module">
        
86
        <ul class="current">
87 88 89 90
<li class="toctree-l1"><a class="reference internal" href="../../getstarted/index_en.html">GET STARTED</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../build_and_install/index_en.html">Install and Build</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="../index_en.html">HOW TO</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../dev/index_en.html">Development</a></li>
91 92 93 94
</ul>

        
<div role="search">
95
  <form id="rtd-search-form" class="wy-form" action="../../search.html" method="get">
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>        
      </div>
    </div>
  </header>
  
  <div class="main-content-wrap">

    
    <nav class="doc-menu-vertical" role="navigation">
        
          
111
          <ul class="current">
112 113
<li class="toctree-l1"><a class="reference internal" href="../../getstarted/index_en.html">GET STARTED</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../../getstarted/quickstart_en.html">Quick Start</a></li>
114 115
</ul>
</li>
116 117 118 119 120
<li class="toctree-l1"><a class="reference internal" href="../../build_and_install/index_en.html">Install and Build</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../../build_and_install/pip_install_en.html">Install Using pip</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../build_and_install/docker_install_en.html">Run in Docker Containers</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../build_and_install/build_en.html">Build using Docker</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../build_and_install/build_from_source_en.html">Build from Sources</a></li>
121 122
</ul>
</li>
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
<li class="toctree-l1 current"><a class="reference internal" href="../index_en.html">HOW TO</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="../cmd_parameter/index_en.html">Set Command-line Parameters</a><ul>
<li class="toctree-l3"><a class="reference internal" href="../cmd_parameter/use_case_en.html">Use Case</a></li>
<li class="toctree-l3"><a class="reference internal" href="../cmd_parameter/arguments_en.html">Argument Outline</a></li>
<li class="toctree-l3"><a class="reference internal" href="../cmd_parameter/detail_introduction_en.html">Detail Description</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="../cluster/index_en.html">Distributed Training</a><ul>
<li class="toctree-l3"><a class="reference internal" href="../cluster/preparations_en.html">Preparations</a></li>
<li class="toctree-l3"><a class="reference internal" href="../cluster/cmd_argument_en.html">Command-line arguments</a></li>
<li class="toctree-l3"><a class="reference internal" href="../cluster/multi_cluster/index_en.html">Use different clusters</a><ul>
<li class="toctree-l4"><a class="reference internal" href="../cluster/multi_cluster/fabric_en.html">Cluster Training Using Fabric</a></li>
<li class="toctree-l4"><a class="reference internal" href="../cluster/multi_cluster/openmpi_en.html">Cluster Training Using OpenMPI</a></li>
<li class="toctree-l4"><a class="reference internal" href="../cluster/multi_cluster/k8s_en.html">PaddlePaddle On Kubernetes</a></li>
<li class="toctree-l4"><a class="reference internal" href="../cluster/multi_cluster/k8s_aws_en.html">Distributed PaddlePaddle Training on AWS with Kubernetes</a></li>
138 139
</ul>
</li>
140 141
</ul>
</li>
142 143 144 145
<li class="toctree-l2 current"><a class="reference internal" href="index_en.html">RNN Models</a><ul class="current">
<li class="toctree-l3 current"><a class="current reference internal" href="#">RNN Configuration</a></li>
</ul>
</li>
146 147 148 149 150 151 152
<li class="toctree-l2"><a class="reference internal" href="../optimization/gpu_profiling_en.html">Tune GPU Performance</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../dev/index_en.html">Development</a><ul>
<li class="toctree-l2"><a class="reference internal" href="../../dev/new_layer_en.html">Write New Layers</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../dev/contribute_to_paddle_en.html">Contribute Code</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../dev/write_docs_en.html">Contribute Documentation</a></li>
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
</ul>
</li>
</ul>

        
    </nav>
    
    <section class="doc-content-wrap">

      

 







<div role="navigation" aria-label="breadcrumbs navigation">
  <ul class="wy-breadcrumbs">
      
175
        <li><a href="../index_en.html">HOW TO</a> > </li>
176 177 178
      
        <li><a href="index_en.html">RNN Models</a> > </li>
      
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
    <li>RNN Configuration</li>
  </ul>
</div>
      
      <div class="wy-nav-content" id="doc-content">
        <div class="rst-content">
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <div class="section" id="rnn-configuration">
<h1>RNN Configuration<a class="headerlink" href="#rnn-configuration" title="Permalink to this headline"></a></h1>
<p>This tutorial will guide you how to configure recurrent neural network in PaddlePaddle. PaddlePaddle supports highly flexible and efficient recurrent neural network configuration. In this tutorial, you will learn how to:</p>
<ul class="simple">
<li>configure recurrent neural network architecture.</li>
<li>generate sequence with learned recurrent neural network models.</li>
</ul>
195 196
<p>We will use vanilla recurrent neural network, and sequence to sequence model to guide you through these steps. The code of sequence to sequence model can be found at <a class="reference external" href="https://github.com/PaddlePaddle/book/tree/develop/08.machine_translation">book/08.machine_translation</a> .
And the data preparation of this model can be found at <a class="reference external" href="https://github.com/PaddlePaddle/Paddle/blob/develop/python/paddle/v2/dataset/wmt14.py">python/paddle/v2/dataset/wmt14.py</a></p>
197 198 199 200 201
<div class="section" id="configure-recurrent-neural-network-architecture">
<h2>Configure Recurrent Neural Network Architecture<a class="headerlink" href="#configure-recurrent-neural-network-architecture" title="Permalink to this headline"></a></h2>
<div class="section" id="simple-gated-recurrent-neural-network">
<h3>Simple Gated Recurrent Neural Network<a class="headerlink" href="#simple-gated-recurrent-neural-network" title="Permalink to this headline"></a></h3>
<p>Recurrent neural network process a sequence at each time step sequentially. An example of the architecture of LSTM is listed below.</p>
202
<img alt="../../_images/bi_lstm.jpg" class="align-center" src="../../_images/bi_lstm.jpg" />
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
<p>Generally speaking, a recurrent network perform the following operations from <span class="math">\(t=1\)</span> to <span class="math">\(t=T\)</span>, or reversely from <span class="math">\(t=T\)</span> to <span class="math">\(t=1\)</span>.</p>
<div class="math">
\[x_{t+1} = f_x(x_t), y_t = f_y(x_t)\]</div>
<p>where <span class="math">\(f_x(.)\)</span> is called <strong>step function</strong>, and <span class="math">\(f_y(.)\)</span> is called <strong>output function</strong>. In vanilla recurrent neural network, both of the step function and output function are very simple. However, PaddlePaddle supports the configuration of very complex architectures by modifying these two functions. We will use the sequence to sequence model with attention as an example to demonstrate how you can configure complex recurrent neural network models. In this section, we will use a simple vanilla recurrent neural network as an example of configuring simple recurrent neural network using <code class="code docutils literal"><span class="pre">recurrent_group</span></code>. Notice that if you only need to use simple RNN, GRU, or LSTM, then <code class="code docutils literal"><span class="pre">grumemory</span></code> and <code class="code docutils literal"><span class="pre">lstmemory</span></code> is recommended because they are more computationally efficient than <code class="code docutils literal"><span class="pre">recurrent_group</span></code>.</p>
<p>For vanilla RNN, at each time step, the <strong>step function</strong> is:</p>
<div class="math">
\[x_{t+1} = W_x x_t + W_i I_t + b\]</div>
<p>where <span class="math">\(x_t\)</span> is the RNN state, and <span class="math">\(I_t\)</span> is the input, <span class="math">\(W_x\)</span> and <span class="math">\(W_i\)</span> are transformation matrices for RNN states and inputs, respectively. <span class="math">\(b\)</span> is the bias.
Its <strong>output function</strong> simply takes <span class="math">\(x_t\)</span> as the output.</p>
<p><code class="code docutils literal"><span class="pre">recurrent_group</span></code> is the most important tools for constructing recurrent neural networks. It defines the <strong>step function</strong>, <strong>output function</strong> and the inputs of the recurrent neural network. Notice that the <code class="code docutils literal"><span class="pre">step</span></code> argument of this function implements both the <code class="code docutils literal"><span class="pre">step</span> <span class="pre">function</span></code> and the <code class="code docutils literal"><span class="pre">output</span> <span class="pre">function</span></code>:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">simple_rnn</span><span class="p">(</span><span class="nb">input</span><span class="p">,</span>
               <span class="n">size</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span>
               <span class="n">name</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span>
               <span class="n">reverse</span><span class="o">=</span><span class="bp">False</span><span class="p">,</span>
               <span class="n">rnn_bias_attr</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span>
               <span class="n">act</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span>
               <span class="n">rnn_layer_attr</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__rnn_step__</span><span class="p">(</span><span class="n">ipt</span><span class="p">):</span>
221 222 223 224 225 226 227 228
       <span class="n">out_mem</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">memory</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="n">name</span><span class="p">,</span> <span class="n">size</span><span class="o">=</span><span class="n">size</span><span class="p">)</span>
       <span class="n">rnn_out</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">mixed</span><span class="p">(</span><span class="nb">input</span> <span class="o">=</span> <span class="p">[</span><span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">full_matrix_projection</span><span class="p">(</span><span class="nb">input</span><span class="o">=</span><span class="n">ipt</span><span class="p">),</span>
                                             <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">full_matrix_projection</span><span class="p">(</span><span class="nb">input</span><span class="o">=</span><span class="n">out_mem</span><span class="p">)],</span>
                                    <span class="n">name</span> <span class="o">=</span> <span class="n">name</span><span class="p">,</span>
                                    <span class="n">bias_attr</span> <span class="o">=</span> <span class="n">rnn_bias_attr</span><span class="p">,</span>
                                    <span class="n">act</span> <span class="o">=</span> <span class="n">act</span><span class="p">,</span>
                                    <span class="n">layer_attr</span> <span class="o">=</span> <span class="n">rnn_layer_attr</span><span class="p">,</span>
                                    <span class="n">size</span> <span class="o">=</span> <span class="n">size</span><span class="p">)</span>
229
       <span class="k">return</span> <span class="n">rnn_out</span>
230 231 232 233
    <span class="k">return</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">recurrent_group</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%s</span><span class="s1">_recurrent_group&#39;</span> <span class="o">%</span> <span class="n">name</span><span class="p">,</span>
                                        <span class="n">step</span><span class="o">=</span><span class="n">__rnn_step__</span><span class="p">,</span>
                                        <span class="n">reverse</span><span class="o">=</span><span class="n">reverse</span><span class="p">,</span>
                                        <span class="nb">input</span><span class="o">=</span><span class="nb">input</span><span class="p">)</span>
234 235 236 237 238 239 240 241 242
</pre></div>
</div>
<p>PaddlePaddle uses memory to construct step function. <strong>Memory</strong> is the most important concept when constructing recurrent neural networks in PaddlePaddle. A memory is a state that is used recurrently in step functions, such as <span class="math">\(x_{t+1} = f_x(x_t)\)</span>. One memory contains an <strong>output</strong> and a <strong>input</strong>. The output of memory at the current time step is utilized as the input of the memory at the next time step. A memory can also has a <strong>boot layer</strong>, whose output is utilized as the initial value of the memory. In our case, the output of the gated recurrent unit is employed as the output memory. Notice that the name of the layer <code class="code docutils literal"><span class="pre">rnn_out</span></code> is the same as the name of <code class="code docutils literal"><span class="pre">out_mem</span></code>. This means the output of the layer <code class="code docutils literal"><span class="pre">rnn_out</span></code> (<span class="math">\(x_{t+1}\)</span>) is utilized as the <strong>output</strong> of <code class="code docutils literal"><span class="pre">out_mem</span></code> memory.</p>
<p>A memory can also be a sequence. In this case, at each time step, we have a sequence as the state of the recurrent neural network. This can be useful when constructing very complex recurrent neural network. Other advanced functions include defining multiple memories, and defining hierarchical recurrent neural network architecture using sub-sequence.</p>
<p>We return <code class="code docutils literal"><span class="pre">rnn_out</span></code> at the end of the function. It means that the output of the layer <code class="code docutils literal"><span class="pre">rnn_out</span></code> is utilized as the <strong>output</strong> function of the gated recurrent neural network.</p>
</div>
<div class="section" id="sequence-to-sequence-model-with-attention">
<h3>Sequence to Sequence Model with Attention<a class="headerlink" href="#sequence-to-sequence-model-with-attention" title="Permalink to this headline"></a></h3>
<p>We will use the sequence to sequence model with attention as an example to demonstrate how you can configure complex recurrent neural network models. An illustration of the sequence to sequence model with attention is shown in the following figure.</p>
243
<img alt="../../_images/encoder-decoder-attention-model.png" class="align-center" src="../../_images/encoder-decoder-attention-model.png" />
244
<p>In this model, the source sequence <span class="math">\(S = \{s_1, \dots, s_T\}\)</span> is encoded with a bidirectional gated recurrent neural networks. The hidden states of the bidirectional gated recurrent neural network <span class="math">\(H_S = \{H_1, \dots, H_T\}\)</span> is called <em>encoder vector</em> The decoder is a gated recurrent neural network. When decoding each token <span class="math">\(y_t\)</span>, the gated recurrent neural network generates a set of weights <span class="math">\(W_S^t = \{W_1^t, \dots, W_T^t\}\)</span>, which are used to compute a weighted sum of the encoder vector. The weighted sum of the encoder vector is utilized to condition the generation of the token <span class="math">\(y_t\)</span>.</p>
245
<p>The encoder part of the model is listed below. It calls <code class="code docutils literal"><span class="pre">grumemory</span></code> to represent gated recurrent neural network. It is the recommended way of using recurrent neural network if the network architecture is simple, because it is faster than <code class="code docutils literal"><span class="pre">recurrent_group</span></code>. We have implemented most of the commonly used recurrent neural network architectures, you can refer to <span class="xref std std-ref">api_trainer_config_helpers_layers</span> for more details.</p>
246 247
<p>We also project the encoder vector to <code class="code docutils literal"><span class="pre">decoder_size</span></code> dimensional space, get the first instance of the backward recurrent network, and project it to <code class="code docutils literal"><span class="pre">decoder_size</span></code> dimensional space:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="c1"># Define the data layer of the source sentence.</span>
248 249 250
<span class="n">src_word_id</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">data</span><span class="p">(</span>
    <span class="n">name</span><span class="o">=</span><span class="s1">&#39;source_language_word&#39;</span><span class="p">,</span>
    <span class="nb">type</span><span class="o">=</span><span class="n">paddle</span><span class="o">.</span><span class="n">data_type</span><span class="o">.</span><span class="n">integer_value_sequence</span><span class="p">(</span><span class="n">source_dict_dim</span><span class="p">))</span>
251
<span class="c1"># Calculate the word embedding of each word.</span>
252
<span class="n">src_embedding</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">embedding</span><span class="p">(</span>
253 254
    <span class="nb">input</span><span class="o">=</span><span class="n">src_word_id</span><span class="p">,</span>
    <span class="n">size</span><span class="o">=</span><span class="n">word_vector_dim</span><span class="p">,</span>
255
    <span class="n">param_attr</span><span class="o">=</span><span class="n">paddle</span><span class="o">.</span><span class="n">attr</span><span class="o">.</span><span class="n">ParamAttr</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;_source_language_embedding&#39;</span><span class="p">))</span>
256
<span class="c1"># Apply forward recurrent neural network.</span>
257 258
<span class="n">src_forward</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">networks</span><span class="o">.</span><span class="n">simple_gru</span><span class="p">(</span>
    <span class="nb">input</span><span class="o">=</span><span class="n">src_embedding</span><span class="p">,</span> <span class="n">size</span><span class="o">=</span><span class="n">encoder_size</span><span class="p">)</span>
259
<span class="c1"># Apply backward recurrent neural network. reverse=True means backward recurrent neural network.</span>
260 261
<span class="n">src_backward</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">networks</span><span class="o">.</span><span class="n">simple_gru</span><span class="p">(</span>
    <span class="nb">input</span><span class="o">=</span><span class="n">src_embedding</span><span class="p">,</span> <span class="n">size</span><span class="o">=</span><span class="n">encoder_size</span><span class="p">,</span> <span class="n">reverse</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
262
<span class="c1"># Mix the forward and backward parts of the recurrent neural network together.</span>
263
<span class="n">encoded_vector</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">concat</span><span class="p">(</span><span class="nb">input</span><span class="o">=</span><span class="p">[</span><span class="n">src_forward</span><span class="p">,</span> <span class="n">src_backward</span><span class="p">])</span>
264 265

<span class="c1"># Project encoding vector to decoder_size.</span>
266 267 268
<span class="n">encoded_proj</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">mixed</span><span class="p">(</span>
    <span class="n">size</span><span class="o">=</span><span class="n">decoder_size</span><span class="p">,</span>
    <span class="nb">input</span><span class="o">=</span><span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">full_matrix_projection</span><span class="p">(</span><span class="n">encoded_vector</span><span class="p">))</span>
269 270

<span class="c1"># Compute the first instance of the backward RNN.</span>
271
<span class="n">backward_first</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">first_seq</span><span class="p">(</span><span class="nb">input</span><span class="o">=</span><span class="n">src_backward</span><span class="p">)</span>
272 273

<span class="c1"># Project the first instance of backward RNN to decoder size.</span>
274 275 276 277
<span class="n">decoder_boot</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">mixed</span><span class="p">(</span>
   <span class="n">size</span><span class="o">=</span><span class="n">decoder_size</span><span class="p">,</span>
   <span class="n">act</span><span class="o">=</span><span class="n">paddle</span><span class="o">.</span><span class="n">activation</span><span class="o">.</span><span class="n">Tanh</span><span class="p">(),</span>
   <span class="nb">input</span><span class="o">=</span><span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">full_matrix_projection</span><span class="p">(</span><span class="n">backward_first</span><span class="p">))</span>
278 279 280
</pre></div>
</div>
<p>The decoder uses <code class="code docutils literal"><span class="pre">recurrent_group</span></code> to define the recurrent neural network. The step and output functions are defined in <code class="code docutils literal"><span class="pre">gru_decoder_with_attention</span></code>:</p>
281 282 283 284 285 286 287 288 289 290
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="n">group_input1</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">StaticInput</span><span class="p">(</span><span class="nb">input</span><span class="o">=</span><span class="n">encoded_vector</span><span class="p">,</span> <span class="n">is_seq</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">group_input2</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">StaticInput</span><span class="p">(</span><span class="nb">input</span><span class="o">=</span><span class="n">encoded_proj</span><span class="p">,</span> <span class="n">is_seq</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">group_inputs</span> <span class="o">=</span> <span class="p">[</span><span class="n">group_input1</span><span class="p">,</span> <span class="n">group_input2</span><span class="p">]</span>
<span class="n">trg_embedding</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">embedding</span><span class="p">(</span>
        <span class="nb">input</span><span class="o">=</span><span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">data</span><span class="p">(</span>
            <span class="n">name</span><span class="o">=</span><span class="s1">&#39;target_language_word&#39;</span><span class="p">,</span>
            <span class="nb">type</span><span class="o">=</span><span class="n">paddle</span><span class="o">.</span><span class="n">data_type</span><span class="o">.</span><span class="n">integer_value_sequence</span><span class="p">(</span><span class="n">target_dict_dim</span><span class="p">)),</span>
        <span class="n">size</span><span class="o">=</span><span class="n">word_vector_dim</span><span class="p">,</span>
        <span class="n">param_attr</span><span class="o">=</span><span class="n">paddle</span><span class="o">.</span><span class="n">attr</span><span class="o">.</span><span class="n">ParamAttr</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;_target_language_embedding&#39;</span><span class="p">))</span>
    <span class="n">group_inputs</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">trg_embedding</span><span class="p">)</span>
291 292 293 294 295 296 297 298
<span class="n">group_inputs</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">trg_embedding</span><span class="p">)</span>

<span class="c1"># For decoder equipped with attention mechanism, in training,</span>
<span class="c1"># target embedding (the groudtruth) is the data input,</span>
<span class="c1"># while encoded source sequence is accessed to as an unbounded memory.</span>
<span class="c1"># StaticInput means the same value is utilized at different time steps.</span>
<span class="c1"># Otherwise, it is a sequence input. Inputs at different time steps are different.</span>
<span class="c1"># All sequence inputs should have the same length.</span>
299 300 301 302
<span class="n">decoder</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">recurrent_group</span><span class="p">(</span>
        <span class="n">name</span><span class="o">=</span><span class="n">decoder_group_name</span><span class="p">,</span>
        <span class="n">step</span><span class="o">=</span><span class="n">gru_decoder_with_attention</span><span class="p">,</span>
        <span class="nb">input</span><span class="o">=</span><span class="n">group_inputs</span><span class="p">)</span>
303 304 305 306 307 308 309
</pre></div>
</div>
<p>The implementation of the step function is listed as below. First, it defines the <strong>memory</strong> of the decoder network. Then it defines attention, gated recurrent unit step function, and the output function:</p>
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">gru_decoder_with_attention</span><span class="p">(</span><span class="n">enc_vec</span><span class="p">,</span> <span class="n">enc_proj</span><span class="p">,</span> <span class="n">current_word</span><span class="p">):</span>
    <span class="c1"># Defines the memory of the decoder.</span>
    <span class="c1"># The output of this memory is defined in gru_step.</span>
    <span class="c1"># Notice that the name of gru_step should be the same as the name of this memory.</span>
310 311
    <span class="n">decoder_mem</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">memory</span><span class="p">(</span>
        <span class="n">name</span><span class="o">=</span><span class="s1">&#39;gru_decoder&#39;</span><span class="p">,</span> <span class="n">size</span><span class="o">=</span><span class="n">decoder_size</span><span class="p">,</span> <span class="n">boot_layer</span><span class="o">=</span><span class="n">decoder_boot</span><span class="p">)</span>
312
    <span class="c1"># Compute attention weighted encoder vector.</span>
313 314 315 316
    <span class="n">context</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">networks</span><span class="o">.</span><span class="n">simple_attention</span><span class="p">(</span>
        <span class="n">encoded_sequence</span><span class="o">=</span><span class="n">enc_vec</span><span class="p">,</span>
        <span class="n">encoded_proj</span><span class="o">=</span><span class="n">enc_proj</span><span class="p">,</span>
        <span class="n">decoder_state</span><span class="o">=</span><span class="n">decoder_mem</span><span class="p">)</span>
317
    <span class="c1"># Mix the current word embedding and the attention weighted encoder vector.</span>
318 319 320 321 322 323
    <span class="n">decoder_inputs</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">mixed</span><span class="p">(</span>
        <span class="n">size</span><span class="o">=</span><span class="n">decoder_size</span> <span class="o">*</span> <span class="mi">3</span><span class="p">,</span>
        <span class="nb">input</span><span class="o">=</span><span class="p">[</span>
            <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">full_matrix_projection</span><span class="p">(</span><span class="nb">input</span><span class="o">=</span><span class="n">context</span><span class="p">),</span>
            <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">full_matrix_projection</span><span class="p">(</span><span class="nb">input</span><span class="o">=</span><span class="n">current_word</span><span class="p">)</span>
        <span class="p">])</span>
324
    <span class="c1"># Define Gated recurrent unit recurrent neural network step function.</span>
325 326 327 328 329
    <span class="n">gru_step</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">gru_step</span><span class="p">(</span>
        <span class="n">name</span><span class="o">=</span><span class="s1">&#39;gru_decoder&#39;</span><span class="p">,</span>
        <span class="nb">input</span><span class="o">=</span><span class="n">decoder_inputs</span><span class="p">,</span>
        <span class="n">output_mem</span><span class="o">=</span><span class="n">decoder_mem</span><span class="p">,</span>
        <span class="n">size</span><span class="o">=</span><span class="n">decoder_size</span><span class="p">)</span>
330
    <span class="c1"># Defines the output function.</span>
331 332 333 334 335
    <span class="n">out</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">mixed</span><span class="p">(</span>
        <span class="n">size</span><span class="o">=</span><span class="n">target_dict_dim</span><span class="p">,</span>
        <span class="n">bias_attr</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
        <span class="n">act</span><span class="o">=</span><span class="n">paddle</span><span class="o">.</span><span class="n">activation</span><span class="o">.</span><span class="n">Softmax</span><span class="p">(),</span>
        <span class="nb">input</span><span class="o">=</span><span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">full_matrix_projection</span><span class="p">(</span><span class="nb">input</span><span class="o">=</span><span class="n">gru_step</span><span class="p">))</span>
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
    <span class="k">return</span> <span class="n">out</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="generate-sequence">
<h2>Generate Sequence<a class="headerlink" href="#generate-sequence" title="Permalink to this headline"></a></h2>
<p>After training the model, we can use it to generate sequences. A common practice is to use <strong>beam search</strong> to generate sequences. The following code snippets defines a beam search algorithm. Notice that <code class="code docutils literal"><span class="pre">beam_search</span></code> function assumes the output function of the <code class="code docutils literal"><span class="pre">step</span></code> returns a softmax normalized probability vector of the next token. We made the following changes to the model.</p>
<ul class="simple">
<li>use <code class="code docutils literal"><span class="pre">GeneratedInput</span></code> for trg_embedding. <code class="code docutils literal"><span class="pre">GeneratedInput</span></code> computes the embedding of the generated token at the last time step for the input at the current time step.</li>
<li>use <code class="code docutils literal"><span class="pre">beam_search</span></code> function. This function needs to set:<ul>
<li><code class="code docutils literal"><span class="pre">bos_id</span></code>: the start token. Every sentence starts with the start token.</li>
<li><code class="code docutils literal"><span class="pre">eos_id</span></code>: the end token. Every sentence ends with the end token.</li>
<li><code class="code docutils literal"><span class="pre">beam_size</span></code>: the beam size used in beam search.</li>
<li><code class="code docutils literal"><span class="pre">max_length</span></code>: the maximum length of the generated sentences.</li>
</ul>
</li>
</ul>
<p>The code is listed below:</p>
355 356 357
<div class="highlight-python"><div class="highlight"><pre><span></span><span class="n">group_input1</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">StaticInput</span><span class="p">(</span><span class="nb">input</span><span class="o">=</span><span class="n">encoded_vector</span><span class="p">,</span> <span class="n">is_seq</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">group_input2</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">StaticInput</span><span class="p">(</span><span class="nb">input</span><span class="o">=</span><span class="n">encoded_proj</span><span class="p">,</span> <span class="n">is_seq</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">group_inputs</span> <span class="o">=</span> <span class="p">[</span><span class="n">group_input1</span><span class="p">,</span> <span class="n">group_input2</span><span class="p">]</span>
358 359 360 361 362 363
<span class="c1"># In generation, decoder predicts a next target word based on</span>
<span class="c1"># the encoded source sequence and the last generated target word.</span>
<span class="c1"># The encoded source sequence (encoder&#39;s output) must be specified by</span>
<span class="c1"># StaticInput which is a read-only memory.</span>
<span class="c1"># Here, GeneratedInputs automatically fetchs the last generated word,</span>
<span class="c1"># which is initialized by a start mark, such as &lt;s&gt;.</span>
364 365 366 367
<span class="n">trg_embedding</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">GeneratedInput</span><span class="p">(</span>
        <span class="n">size</span><span class="o">=</span><span class="n">target_dict_dim</span><span class="p">,</span>
        <span class="n">embedding_name</span><span class="o">=</span><span class="s1">&#39;_target_language_embedding&#39;</span><span class="p">,</span>
        <span class="n">embedding_size</span><span class="o">=</span><span class="n">word_vector_dim</span><span class="p">)</span>
368
<span class="n">group_inputs</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">trg_embedding</span><span class="p">)</span>
369 370 371 372 373 374 375 376 377 378
<span class="n">beam_gen</span> <span class="o">=</span> <span class="n">paddle</span><span class="o">.</span><span class="n">layer</span><span class="o">.</span><span class="n">beam_search</span><span class="p">(</span>
        <span class="n">name</span><span class="o">=</span><span class="n">decoder_group_name</span><span class="p">,</span>
        <span class="n">step</span><span class="o">=</span><span class="n">gru_decoder_with_attention</span><span class="p">,</span>
        <span class="nb">input</span><span class="o">=</span><span class="n">group_inputs</span><span class="p">,</span>
        <span class="n">bos_id</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="c1"># Beginnning token.</span>
        <span class="n">eos_id</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="c1"># End of sentence token.</span>
        <span class="n">beam_size</span><span class="o">=</span><span class="n">beam_size</span><span class="p">,</span>
        <span class="n">max_length</span><span class="o">=</span><span class="n">max_length</span><span class="p">)</span>

<span class="k">return</span> <span class="n">beam_gen</span>
379 380
</pre></div>
</div>
381 382
<p>Notice that this generation technique is only useful for decoder like generation process. If you are working on sequence tagging tasks, please refer to <a class="reference external" href="https://github.com/PaddlePaddle/book/tree/develop/06.understand_sentiment">book/06.understand_sentiment</a> for more details.</p>
<p>The full configuration file is located at <a class="reference external" href="https://github.com/PaddlePaddle/book/blob/develop/08.machine_translation/train.py">book/08.machine_translation/train.py</a> .</p>
383 384 385 386 387 388 389 390
</div>
</div>


           </div>
          </div>
          <footer>
  
391 392
    <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
      
393
        <a href="../optimization/gpu_profiling_en.html" class="btn btn-neutral float-right" title="Tune GPU Performance" accesskey="n">Next <span class="fa fa-arrow-circle-right"></span></a>
394 395 396 397 398 399
      
      
        <a href="index_en.html" class="btn btn-neutral" title="RNN Models" accesskey="p"><span class="fa fa-arrow-circle-left"></span> Previous</a>
      
    </div>
  
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425

  <hr/>

  <div role="contentinfo">
    <p>
        &copy; Copyright 2016, PaddlePaddle developers.

    </p>
  </div>
  Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. 

</footer>

        </div>
      </div>

    </section>

  </div>
  


  

    <script type="text/javascript">
        var DOCUMENTATION_OPTIONS = {
426
            URL_ROOT:'../../',
427 428 429
            VERSION:'',
            COLLAPSE_INDEX:false,
            FILE_SUFFIX:'.html',
430 431
            HAS_SOURCE:  true,
            SOURCELINK_SUFFIX: ".txt",
432 433
        };
    </script>
434 435 436
      <script type="text/javascript" src="../../_static/jquery.js"></script>
      <script type="text/javascript" src="../../_static/underscore.js"></script>
      <script type="text/javascript" src="../../_static/doctools.js"></script>
437
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
438 439 440 441 442
       
  

  
  
443
    <script type="text/javascript" src="../../_static/js/theme.js"></script>
444 445 446 447
  
  
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/perfect-scrollbar/0.6.14/js/perfect-scrollbar.jquery.min.js"></script>
448
  <script src="../../_static/js/paddle_doc_init.js"></script> 
449 450

</body>
451
</html>