
.. _crei2013_advanced_theano:

***************
Advanced Theano
***************


Profiling
---------

- To replace the default mode with this mode, use the Theano flags ``profile=True``

- To enable the memory profiling use the flags ``profile_memory=True``

Theano output:

.. literalinclude:: logreg_profile.prof

Compilation pipeline
--------------------

.. image:: ../hpcs2011_tutorial/pics/pipeline.png
   :width: 400 px


Inplace optimization
--------------------

- 2 type of inplace operations:

  - An op that return a view on its inputs (e.g. reshape, inplace transpose)
  - An op that write the output on the inputs memory space

- This allows some memory optimization
- The Op must tell Theano if they work inplace
- Inplace Op add constraints to the order of execution


Conditions
----------
**IfElse**

- Build condition over symbolic variables.
- IfElse Op takes a boolean condition and two variables to compute as input.
- While Switch Op evaluates both 'output' variables, IfElse Op is lazy and only
  evaluates one variable respect to the condition.

**IfElse Example: Comparison with Switch**

.. literalinclude:: ifelse_switch.py

IfElse Op spend less time (about an half) than Switch since it computes only
one variable instead of both.

>>> python ifelse_switch.py # doctest: +SKIP
time spent evaluating both values 0.230000 sec
time spent evaluating one value 0.120000 sec

Note that IfElse condition is a boolean while Switch condition is a tensor, so
Switch is more general.

It is actually important to use  ``linker='vm'`` or ``linker='cvm'``,
otherwise IfElse will compute both variables and take the same computation
time as the Switch Op. The linker is not currently set by default to 'cvm' but
it will be in a near future.

Loops
-----

**Scan**

- General form of **recurrence**, which can be used for looping.
- **Reduction** and **map** (loop over the leading dimensions) are special cases of Scan
- You 'scan' a function along some input sequence, producing an output at each time-step
- The function can see the **previous K time-steps** of your function
- ``sum()`` could be computed by scanning the z + x(i) function over a list, given an initial state of ``z=0``.
- Often a for-loop can be expressed as a ``scan()`` operation, and ``scan`` is the closest that Theano comes to looping.
- The advantage of using ``scan`` over for loops
  
  - The number of iterations to be part of the symbolic graph
  - Minimizes GPU transfers if GPU is involved
  - Compute gradients through sequential steps
  - Slightly faster then using a for loop in Python with a compiled Theano function
  - Can lower the overall memory usage by detecting the actual amount of memory needed

**Scan Example: Computing pow(A,k)**

.. literalinclude:: scan_pow.py


**Scan Example: Calculating a Polynomial**

.. literalinclude:: scan_poly.py

Exercise 4
-----------

- Run both examples 
- Modify and execute the polynomial example to have the reduction done by scan


Exercise 5
-----------

- In the last exercises, do you see a speed up with the GPU?
- Where does it come from? (Use profile=True)
- Is there something we can do to speed up the GPU version?



Printing/Drawing Theano graphs
------------------------------

Consider the following logistic regression model:

>>> import numpy
>>> import theano
>>> import theano.tensor as T
>>> rng = numpy.random
>>> # Training data
>>> N = 400
>>> feats = 784
>>> D = (rng.randn(N, feats).astype(theano.config.floatX), rng.randint(size=N,low=0, high=2).astype(theano.config.floatX))
>>> training_steps = 10000
>>> # Declare Theano symbolic variables
>>> x = T.matrix("x")
>>> y = T.vector("y")
>>> w = theano.shared(rng.randn(feats).astype(theano.config.floatX), name="w")
>>> b = theano.shared(numpy.asarray(0., dtype=theano.config.floatX), name="b")
>>> x.tag.test_value = D[0]
>>> y.tag.test_value = D[1]
>>> # Construct Theano expression graph
>>> p_1 = 1 / (1 + T.exp(-T.dot(x, w)-b)) # Probability of having a one
>>> prediction = p_1 > 0.5 # The prediction that is done: 0 or 1
>>> # Compute gradients
>>> xent = -y*T.log(p_1) - (1-y)*T.log(1-p_1) # Cross-entropy
>>> cost = xent.mean() + 0.01*(w**2).sum() # The cost to optimize
>>> gw,gb = T.grad(cost, [w,b])
>>> # Training and prediction function
>>> train = theano.function(inputs=[x,y], outputs=[prediction, xent], updates=[[w, w-0.01*gw], [b, b-0.01*gb]], name = "train")
>>> predict = theano.function(inputs=[x], outputs=prediction, name = "predict")

We will now make use of Theano's printing features to compare the unoptimized
graph (``prediction``) to the optimized graph (``predict``).

Pretty Printing
~~~~~~~~~~~~~~~

>>> theano.printing.pprint(prediction) # doctest: +NORMALIZE_WHITESPACE
'gt((TensorConstant{1} / (TensorConstant{1} + exp(((-(x \\dot w)) - b)))), TensorConstant{0.5})'


Debug Print
~~~~~~~~~~~

The graph before optimization:

.. doctest::
   :options: +SKIP

   >>> theano.printing.debugprint(prediction) # doctest: +NORMALIZE_WHITESPACE
   Elemwise{gt,no_inplace} [@A] ''
    |Elemwise{true_div,no_inplace} [@B] ''
    | |DimShuffle{x} [@C] ''
    | | |TensorConstant{1} [@D]
    | |Elemwise{add,no_inplace} [@E] ''
    |   |DimShuffle{x} [@F] ''
    |   | |TensorConstant{1} [@D]
    |   |Elemwise{exp,no_inplace} [@G] ''
    |     |Elemwise{sub,no_inplace} [@H] ''
    |       |Elemwise{neg,no_inplace} [@I] ''
    |       | |dot [@J] ''
    |       |   |x [@K]
    |       |   |w [@L]
    |       |DimShuffle{x} [@M] ''
    |         |b [@N]
    |DimShuffle{x} [@O] ''
      |TensorConstant{0.5} [@P]

The graph after optimization:

.. doctest::
   :options: +SKIP

   >>> theano.printing.debugprint(predict) # doctest: +NORMALIZE_WHITESPACE
   Elemwise{Composite{GT(scalar_sigmoid((-((-i0) - i1))), i2)}} [@A] ''   4
    |CGemv{inplace} [@B] ''   3
    | |Alloc [@C] ''   2
    | | |TensorConstant{0.0} [@D]
    | | |Shape_i{0} [@E] ''   1
    | |   |x [@F]
    | |TensorConstant{1.0} [@G]
    | |x [@F]
    | |w [@H]
    | |TensorConstant{0.0} [@D]
    |InplaceDimShuffle{x} [@I] ''   0
    | |b [@J]
    |TensorConstant{(1,) of 0.5} [@K]


Picture Printing of Graphs
~~~~~~~~~~~~~~~~~~~~~~~~~~

``pydotprint`` requires graphviz and either pydot or pydot-ng.

The graph before optimization:

.. doctest::
   :options: +SKIP

   >>> theano.printing.pydotprint(prediction, outfile="pics/logreg_pydotprint_prediction.png", var_with_name_simple=True)
   The output file is available at pics/logreg_pydotprint_prediction.png

.. image:: ./pics/logreg_pydotprint_prediction.png
   :width: 800 px

The graph after optimization:

.. doctest::
   :options: +SKIP

   >>> theano.printing.pydotprint(predict, outfile="pics/logreg_pydotprint_predict.png", var_with_name_simple=True)
   The output file is available at pics/logreg_pydotprint_predict.png

.. image:: ./pics/logreg_pydotprint_predict.png
   :width: 800 px

The optimized training graph:

.. doctest::
   :options: +SKIP

   >>> theano.printing.pydotprint(train, outfile="pics/logreg_pydotprint_train.png", var_with_name_simple=True)
   The output file is available at pics/logreg_pydotprint_train.png

.. image:: ./pics/logreg_pydotprint_train.png
   :width: 1500 px



Debugging
---------

- Run with the Theano flag ``compute_test_value = {``off'',``ignore'', ``warn'', ``raise''}``

  - Run the code as we create the graph
  - Allows you to find the bug earlier (ex: shape mismatch)
  - Makes it easier to identify where the problem is in *your* code
  - Use the value of constants and shared variables directly
  - For pure symbolic variables uses ``x.tag.test_value = numpy.random.rand(5,10)``

- Run with the flag ``mode=FAST_COMPILE``
  
  - Few optimizations
  - Run Python code (better error messages and can be debugged interactively in the Python debugger)

- Run with the flag ``mode=DebugMode``

  - 100-1000x slower
  - Test all optimization steps from the original graph to the final graph
  - Checks many things that Op should/shouldn't do
  - Executes both the Python and C code versions

Known limitations
-----------------

- Compilation phase distinct from execution phase

  - Use ``a_tensor_variable.eval()`` to make this less visible

- Compilation time can be significant

  - Amortize it with functions over big input or reuse functions

- Execution overhead

  - We have worked on this, but more work needed
  - So needs a certain number of operations to be useful

- Compilation time superlinear in the size of the graph.

  - Hundreds of nodes is fine
  - Disabling a few optimizations can speed up compilation
  - Usually too many nodes indicates a problem with the graph
