Metadata-Version: 1.0
Name: tangent
Version: 0.1.7
Summary: Automatic differentiation using source code transformation for Python
Home-page: https://github.com/google/tangent
Author: Google Inc.
Author-email: alexbw@google.com
License: 
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright 2017 Google Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

Description-Content-Type: UNKNOWN
Description: # Tangent 
        
        [![Build Status](https://travis-ci.org/google/tangent.svg?branch=master)](https://travis-ci.org/google/tangent)
        [![Join the chat at https://gitter.im/google/tangent](https://badges.gitter.im/google/tangent.svg)](https://gitter.im/google/tangent?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
        
        Tangent is a new, free, and open-source Python library for automatic differentiation.  
        
        
        Existing libraries implement automatic differentiation by tracing a program’s execution (at runtime, like PyTorch) or by staging out a dynamic data-flow graph and then differentiating the graph (ahead-of-time, like TensorFlow). In contrast, Tangent performs ahead-of-time autodiff on the Python source code itself, and produces Python source code as its output. Tangent fills a unique location in the space of machine learning tools.
        
        ![Autodiff Tool Space](docs/toolspace.png "Autodiff Tool Space")
        
        
        As a result, you can finally read your automatic derivative code just like the rest of your program. Tangent is useful to researchers and students who not only want to write their models in Python, but also read and debug automatically-generated derivative code without sacrificing speed and flexibility.
        
        Tangent works on a large and growing subset of Python, provides extra autodiff features other Python ML libraries don’t have, has reasonable performance, and is compatible with TensorFlow and NumPy.
        
        This project is an experimental release, and is under active development. As we continue to build Tangent, and respond to feedback from the community, there might be API changes.
        
        ## Usage
        
        Note: An interactive notebook with all the code in this page can be found [here](https://colab.research.google.com/notebook#fileId=1TDe5g25mhgtmPKbxOdwXlQ1pHm-VYFXB).
        
        Tangent has a one-function API:
        ```python
        import tangent
        df = tangent.grad(f)
        ```
        
        If you want to print out derivatives at the time Tangent generates the derivative function:
        
        ```python
        import tangent
        df = tangent.grad(f, verbose=1)
        ```
        
        Here's Tangent in action in the IPython console.
        
        ![Live Derivatives with Tangent](docs/sct-ad-live.gif "Live Derivatives with Tangent")
        
        ## Installing and running
        
        ### Installation
        
        The easiest way to install Tangent is to use `pip`.
        
            pip install tangent
        
        We'll have a conda package soon.
        
        ## Automatic Differentiation
        
        Under the hood, `tangent.grad` grabs the source code of the Python function you pass it (using `inspect.getsource`, which is available in the Python standard library), converts the source code into an abstract syntax tree (AST) using `ast.parse` (also built into the Python standard library), and walks the syntax tree in reverse order.
        
        Tangent has a library of recipes for the derivatives of basic arithmetic (`+`,`-`,`/`,`**`,`*`), pieces of syntax (`ast.For`, `ast.If`, `ast.While`) and TensorFlow Eager functions (`tf.reduce_sum`, `tf.exp`, `tf.matmul`, ... ). For each piece of syntax it encounters (for example, `c = a + b` is a single AST node `ast.Assign`), `tangent.grad` looks up the matching backward-pass recipe, and adds it to the end of the derivative function.
        This reverse-order processing gives the technique its name: reverse-mode automatic differentiation.
        
        ### TF Eager
        
        Tangent supports differentiating functions that use TensorFlow Eager functions that are composed together.
        
        ```python
        def f(W,x):
          h1 = tf.matmul(x,W)
          h2 = tf.tanh(h1)
          out = tf.reduce_sum(h2)
          return out
        
        dfdW = tangent.grad(f)
        ```
        
        ![SCT on TF Eager](docs/sct-ad-tf.gif "SCT on TF Eager")
        
        
        ### Subroutines
        
        When model code becomes long, using subroutines makes code more readable and reusable. Tangent handles taking derivatives of models that have user-defined functions.
        
        ![SCT on Subroutines](docs/sct-ad-subroutine.gif "SCT on Subroutines")
        
        ### Control Flow
        
        Tangent has recipes for auto-generating derivatives for code that contains if statements and loops:
        
        ![SCT on Conditionals](docs/sct-ad-conditional.gif "SCT on Conditionals")
        
        You’ll notice above that we have to modify the user’s code to keep track of information that we will need in the backward pass. For instance, we need to save which branch of an if-statement was followed in the forward pass, so that we run the correct branch in the backward pass. We save this information from the forward pass by pushing it onto a stack, which we then pop off in the backward pass. This is an important data structure in ahead-of-time autodiff.
        
        For loops require a little more bookkeeping. Tangent has to save the number of iterations of the loop on the stack. Also, loops usually overwrite the values of variables inside the loop body. In order to generate a correct derivative, Tangent has to keep track of all of the overwritten values, and restore them in the backward pass in the correct order.
        
        ![SCT on Loops](docs/sct-ad-loop.gif "SCT on Loops")
        
        ## Custom Gradients
        
        Tangent uses Python's built-in machinery to introspect and transform the _abstract syntax tree_ (AST) of parsed source code at runtime. For each piece of supported Python syntax, we have implemented a rule indicating how to rewrite an AST node into its backward pass equivalent, or "adjoint". We have defined adjoints for function calls to NumPy and TF Eager methods, as well as larger pieces of syntax, such as if-statements and for-loops. The adjoints are stored in function definitions that serve as "templates", or code macros. Another alternative, which we found too cumbersome, would be to use a templating engine like [Mustache](https://mustache.github.io/) and store adjoints as plain strings. Our templates also use a special syntax `d[x]` to refer to the derivative of a variable `x`.
        
        While differentiating a function, if Tangent encounters a function call, it first checks if it has a gradient registered for that function. If not, it tries to get the function source, and generate a derivative ahead-of-time. But, it's easy to register your own gradients. Here's a toy example of defining the gradient of `x^3`.
        
        ```python
        import tangent
        from tangent.grads import adjoint
        
        def cube(x):
          return x * x * x
          
        # Register the gradient of cube with Tangent
        # NOTE! This is not a runnable function, but instead is a code template.
        # Tangent will replace the names of the variables `result` and `x` with whatever
        # is used in your containing function.
        @adjoint(cube)
        def dcube(result, x):
          d[x] = d[result] * 3 * x * x
          
        def f(val):
            cubed_val = cube(val)
            return cubed_val
        
        print(tangent.grad(f,verbose=1))
        ```
        Should output something like:
        ```python
        def dfdval(val, bcubed_val=1.0):
            # Grad of: cubed_val = cube(val)
            bval = bcubed_val * 3 * (val * val) # <<<< this is our inlined gradient
            return bval
        ```
        
        The signature for the custom gradient of some function
        
        ```python
        result = orig_function(arg1,arg2)
        ```
        is
        ```python
        @adjoint(orig_function)
        def grad_orig_function(result, arg1, arg2):
          d[arg1] = d[result]*...
          d[arg2] = d[result]*...
        ```
        The first argument to the template is always the result of the function call, followed by the function arguments, in order.
        Tangent captures the variable names of the result and arguments, and then will use them to unquote the gradient template at the appropriate place in the backward pass.
        
        Check out an [example gradient definition of a NumPy function](https://github.com/google/tangent/blob/6ee7fe31e876c7a68273aeb28ecf03aae42d970d/tangent/grads.py#L261-L263) and [of a TF eager function](https://github.com/google/tangent/blob/6ee7fe31e876c7a68273aeb28ecf03aae42d970d/tangent/tf_extensions.py#L244-L247). Also, [see the docstring in `grads.py` for more info](https://github.com/google/tangent/blob/6ee7fe31e876c7a68273aeb28ecf03aae42d970d/tangent/grads.py#L14-L36).
        
        ## Debugging
        
        Because Tangent auto-generates derivative code you can read, you can also easily debug your backward pass. For instance, your NN might be outputting NaNs during training, and you want to find out where the NaNs are being generated in your model. Just insert a breakpoint (e.g., pdb.set_trace()) at the end of your forward pass.
        
        ![SCT for Debugging](docs/sct-ad-debugging.png "SCT for Debugging")
        
        For large models, setting a breakpoint at the beginning of the backward pass and stepping through dozens of lines might be cumbersome. Instead, you might want the breakpoint to be placed later in the derivative calculation. Tangent lets you insert code directly into any location in the backward pass. First, run `from tangent import insert_grad_of`, then add a with `insert_grad_of` block containing the code you’d like to insert into the backward pass.
        
        ```python
        
        from tangent import insert_grad_of
        def f(x):
          ...
          with insert_grad_of(x) as dx:
            print("dc/dx = %2.2f" % dx)
            pdb.set_trace()
          ...
        ```
        
        ![Ad Hoc Gradient Code](docs/sct-ad-insert_grad_of.gif "Ad Hoc Gradient Code")
        
        ## Derivative Surgery
        
        You can use the `insert_grad_of` feature to do more than debugging and logging. Some NN architectures benefit from tricks that directly manipulate the backward pass. For example, recurrent neural networks (RNNs) suffer from the "exploding gradient" problem, where gradients grow exponentially. This prevents the model from training properly. A typical solution is to force the derivatives inside of an RNN to not exceed a certain value by directly clipping them. We can implement this with `insert_grad_of`.
        
        ```python
        
        def f(params, x):
          h = x
          for i in range(5):
          with insert_grad_of(h) as g:
            g = tf.clip_by_value(g, -1, 1)
          h = rnn(params, h)
          return h
        
        dfdparams = tangent.grad(f)
        ```
        
        You can perform other backward-pass tricks with `insert_grad_of`, such as stop gradients (use a `break` in the inlined code to stop a for loop), or synthetic gradients (replace a derivative with a prediction from a neural network). This feature lets Tangent users easily debug their models, or quickly try out derivative tweaks in the backward pass.
        
        ## Forward Mode
        
        Reverse-mode autodiff, or backpropagation, generates efficient derivatives for the types of functions we use in machine learning, where there are usually many (perhaps millions) of input variables and only a single output (our loss). When the inverse is true, where there are many more outputs than inputs, reverse mode is not an efficient algorithm, as it has to be run as many times as there are output variables. However, a less famous algorithm, forward-mode autodiff, only has to be run as many times as there are _input_ variables.). Tangent supports forward-mode autodiff.
        
        ```python
        
        def f(x):
          a = x * x
          b = x * a
          c = a + b
          return c
        
        forward_df = tangent.grad(f, mode='forward')
        ```
        
        ![SCT Forward Mode](docs/sct-ad-forward.gif "SCT Forward Mode")
        
        ## Hessian-Vector Products
        
        Although we won’t dig into the technical details, forward-mode is very useful when combined with reverse-mode to calculate efficient higher-order derivatives, particularly for Hessian-vector products (HVP) of NNs. This is useful in research applications, and usually very painful and slow to calculate. Autograd has native forward-mode support, while TensorFlow has 3rd-party support.
        
        To take higher-order derivatives, you can use any combination of forward- and reverse-mode autodiff in Tangent. This works because the code Tangent produces can also be fed back in as input. The autodiff literature recommends calculating HVPs in a "Forward-over-Reverse" style. This means first apply reverse mode autodiff to the function, and then apply forward mode to that.
        
        ```python
        
        def f(x):
            a = x * x * x
            b = a * x ** 2.0
            return tf.reduce_sum(b)
        
        hvp = tangent.grad(tangent.grad(f,mode='reverse'),mode='forward')
        ```
        
        ## Performance
        
        Although we did not build Tangent for performance, it is competitive with major ML libraries. Because we are generating derivatives ahead-of-time, there is no interpretive overhead like there is with runtime autodiff libraries. We implemented a few compiler optimizations (dead code elimination, and constant folding), but we are still working on extra optimization passes to further increase performance.
        
        ![Small Benchmark](docs/small-benchmark.png "Small Benchmark")
        
        
        ## Optimization
        
        We are often interested in the gradients of only some of the arguments. In this
        case, many of the adjoint calculation might be dead code. In the optimization
        pass this is removed. We also perform limited constant folding and assignment propagation.
        
        ## Known Limitations
        
        Tangent is still an experiment, so expect some bugs. If you report them to us on GitHub, we will do our best to fix them quickly.
        
        We are working to add support in Tangent for more aspects of the Python language (e.g., closures, inline function definitions, classes, more NumPy and TensorFlow functions). We also hope to add more advanced automatic differentiation and compiler functionality in the future, such as automatic trade-off between memory and compute (Griewank and Walther 2000; Gruslys et al., 2016), more aggressive optimizations, and lambda lifting.
        
        Many of Python's advanced features are difficult to statically analyze or to
        define sensible gradients of, so we restrict Python to a functional subset
        (i.e. no mutable objects).
        
        ### Closures
        
        Closures are currently not supported for the following reasons:
        
        * AD relies on being able to resolve function names. If function names are
          resolved using the enclosing function namespace, we cannot be sure that they
          will resolve to the same function at each call.
        * Although we can access functions from the enclosing function namespace, we
          cannot write to this namespace, which is required for the gradients.
        
        ### Classes
        
        Classes are not _currently_ supported, but are on our near-term roadmap.
        This will enable PyTorch/Chainer/TFEager-style class definitions of neural networks, and parameterized functions, like in TF Slim.
        
        ## Team
        
        Tangent is developed by Alex Wiltschko, Bart van Merriënboer and Dan Moldovan.
        
Keywords: autodiff,automatic-differentiation,machine-learning,deep-learning
Platform: UNKNOWN
