rnn_config_en.html 43.3 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 27 28 29 30 31 32 33 34


<!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>
  

  
  

  

  
  
    

  

  
  
    <link rel="stylesheet" href="../../../_static/css/theme.css" type="text/css" />
  

  
  
        <link rel="index" title="Index"
              href="../../../genindex.html"/>
        <link rel="search" title="Search" href="../../../search.html"/>
35 36 37 38
    <link rel="top" title="PaddlePaddle  documentation" href="../../../index.html"/>
        <link rel="up" title="RNN Models" href="index_en.html"/>
        <link rel="next" title="Tune GPU Performance" href="../../optimization/gpu_profiling_en.html"/>
        <link rel="prev" title="RNN Models" href="index_en.html"/> 
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/perfect-scrollbar/0.6.14/css/perfect-scrollbar.min.css" type="text/css" />
  <link rel="stylesheet" href="../../../_static/css/override.css" type="text/css" />
  <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>

  

  
  <script src="../../../_static/js/modernizr.min.js"></script>

</head>

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

  
  <header class="site-header">
    <div class="site-logo">
      <a href="/"><img src="../../../_static/images/PP_w.png"></a>
    </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
<li class="toctree-l1"><a class="reference internal" href="../../../getstarted/index_en.html">GET STARTED</a></li>
88
<li class="toctree-l1 current"><a class="reference internal" href="../../index_en.html">HOW TO</a></li>
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
<li class="toctree-l1"><a class="reference internal" href="../../../api/index_en.html">API</a></li>
</ul>

        
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../../../search.html" method="get">
    <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">
        
          
110
          <ul class="current">
111 112 113 114 115 116 117 118
<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/build_and_install/index_en.html">Install and Build</a><ul>
<li class="toctree-l3"><a class="reference internal" href="../../../getstarted/build_and_install/docker_install_en.html">PaddlePaddle in Docker Containers</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../../getstarted/build_and_install/build_from_source_en.html">Installing from Sources</a></li>
</ul>
</li>
</ul>
</li>
119
<li class="toctree-l1 current"><a class="reference internal" href="../../index_en.html">HOW TO</a><ul class="current">
120 121 122 123 124 125
<li class="toctree-l2"><a class="reference internal" href="../../usage/cmd_parameter/index_en.html">Set Command-line Parameters</a><ul>
<li class="toctree-l3"><a class="reference internal" href="../../usage/cmd_parameter/use_case_en.html">Use Case</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../usage/cmd_parameter/arguments_en.html">Argument Outline</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../usage/cmd_parameter/detail_introduction_en.html">Detail Description</a></li>
</ul>
</li>
126 127 128 129 130
<li class="toctree-l2"><a class="reference internal" href="../../usage/cluster/cluster_train_en.html">PaddlePaddle Distributed Training</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../usage/cluster/cluster_train_en.html#introduction">Introduction</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../usage/cluster/cluster_train_en.html#preparations">Preparations</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../usage/cluster/cluster_train_en.html#command-line-arguments">Command-line arguments</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../usage/cluster/cluster_train_en.html#use-cluster-platforms-or-cluster-management-tools">Use cluster platforms or cluster management tools</a></li>
131 132
<li class="toctree-l2"><a class="reference internal" href="../../usage/k8s/k8s_en.html">Paddle On Kubernetes</a></li>
<li class="toctree-l2"><a class="reference internal" href="../../usage/k8s/k8s_aws_en.html">Distributed PaddlePaddle Training on AWS with Kubernetes</a></li>
133
<li class="toctree-l2"><a class="reference internal" href="../../dev/build_en.html">Build PaddlePaddle from Source Code and Run Unit Test</a></li>
134
<li class="toctree-l2"><a class="reference internal" href="../../dev/new_layer_en.html">Write New Layers</a></li>
135
<li class="toctree-l2"><a class="reference internal" href="../../dev/contribute_to_paddle_en.html">Contribute Code</a></li>
136 137 138 139
<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>
140 141 142 143
<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="../../../api/index_en.html">API</a><ul>
144 145 146
<li class="toctree-l2"><a class="reference internal" href="../../../api/v2/model_configs.html">Model Configuration</a><ul>
<li class="toctree-l3"><a class="reference internal" href="../../../api/v2/config/activation.html">Activation</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../../api/v2/config/layer.html">Layers</a></li>
147
<li class="toctree-l3"><a class="reference internal" href="../../../api/v2/config/evaluators.html">Evaluators</a></li>
148 149 150 151 152 153
<li class="toctree-l3"><a class="reference internal" href="../../../api/v2/config/optimizer.html">Optimizer</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../../api/v2/config/pooling.html">Pooling</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../../api/v2/config/networks.html">Networks</a></li>
<li class="toctree-l3"><a class="reference internal" href="../../../api/v2/config/attr.html">Parameter Attribute</a></li>
</ul>
</li>
154
<li class="toctree-l2"><a class="reference internal" href="../../../api/v2/data.html">Data Reader Interface and DataSets</a></li>
155
<li class="toctree-l2"><a class="reference internal" href="../../../api/v2/run_logic.html">Training and Inference</a></li>
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
</ul>
</li>
</ul>

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

      

 







<div role="navigation" aria-label="breadcrumbs navigation">
  <ul class="wy-breadcrumbs">
      
178 179 180 181
        <li><a href="../../index_en.html">HOW TO</a> > </li>
      
        <li><a href="index_en.html">RNN Models</a> > </li>
      
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    <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>
198 199
<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>
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
<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>
<img alt="../../../_images/bi_lstm.jpg" class="align-center" src="../../../_images/bi_lstm.jpg" />
<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>
224 225 226 227 228 229 230 231
       <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>
232
       <span class="k">return</span> <span class="n">rnn_out</span>
233 234 235 236
    <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>
237 238 239 240 241 242 243 244 245 246 247
</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>
<img alt="../../../_images/encoder-decoder-attention-model.png" class="align-center" src="../../../_images/encoder-decoder-attention-model.png" />
<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>
248
<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>
249 250
<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>
251 252 253
<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>
254
<span class="c1"># Calculate the word embedding of each word.</span>
255
<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>
256 257
    <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>
258
    <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>
259
<span class="c1"># Apply forward recurrent neural network.</span>
260 261
<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>
262
<span class="c1"># Apply backward recurrent neural network. reverse=True means backward recurrent neural network.</span>
263 264
<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>
265
<span class="c1"># Mix the forward and backward parts of the recurrent neural network together.</span>
266
<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>
267 268

<span class="c1"># Project encoding vector to decoder_size.</span>
269 270 271
<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>
272 273

<span class="c1"># Compute the first instance of the backward RNN.</span>
274
<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>
275 276

<span class="c1"># Project the first instance of backward RNN to decoder size.</span>
277 278 279 280
<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>
281 282 283
</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>
284 285 286 287 288 289 290 291 292 293
<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>
294 295 296 297 298 299 300 301
<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>
302 303 304 305
<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>
306 307 308 309 310 311 312
</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>
313 314
    <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>
315
    <span class="c1"># Compute attention weighted encoder vector.</span>
316 317 318 319
    <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>
320
    <span class="c1"># Mix the current word embedding and the attention weighted encoder vector.</span>
321 322 323 324 325 326
    <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>
327
    <span class="c1"># Define Gated recurrent unit recurrent neural network step function.</span>
328 329 330 331 332
    <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>
333
    <span class="c1"># Defines the output function.</span>
334 335 336 337 338
    <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>
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
    <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>
358 359 360
<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>
361 362 363 364 365 366
<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>
367 368 369 370
<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>
371
<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>
372 373 374 375 376 377 378 379 380 381
<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>
382 383
</pre></div>
</div>
384 385
<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>
386 387 388 389 390 391 392 393
</div>
</div>


           </div>
          </div>
          <footer>
  
394 395 396 397 398 399 400 401 402
    <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
      
        <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>
      
      
        <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>
  
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432

  <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 = {
            URL_ROOT:'../../../',
            VERSION:'',
            COLLAPSE_INDEX:false,
            FILE_SUFFIX:'.html',
433 434
            HAS_SOURCE:  true,
            SOURCELINK_SUFFIX: ".txt",
435 436 437 438 439
        };
    </script>
      <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>
440
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
441 442 443 444 445 446 447 448 449 450 451 452 453
       
  

  
  
    <script type="text/javascript" src="../../../_static/js/theme.js"></script>
  
  
  <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>
  <script src="../../../_static/js/paddle_doc_init.js"></script> 

</body>
454
</html>