Metadata-Version: 2.4
Name: tangent-ad
Version: 0.3.0
Summary: Automatic differentiation using source code transformation for Python
Author-email: "Google Inc." <alexbw@google.com>
Maintainer-email: "Pedro N. Rodriguez" <pnrodriguezh@gmail.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.
        
Project-URL: Homepage, https://github.com/pedronahum/tangent
Project-URL: Documentation, https://pedronahum.github.io/tangent/
Project-URL: Changelog, https://github.com/pedronahum/tangent/blob/master/CHANGELOG.md
Project-URL: Repository, https://github.com/pedronahum/tangent
Project-URL: Issues, https://github.com/pedronahum/tangent/issues
Project-URL: Upstream, https://github.com/google/tangent
Keywords: autodiff,automatic-differentiation,machine-learning,deep-learning
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: gast<0.8.0,>=0.6.0
Requires-Dist: numpy
Provides-Extra: test
Requires-Dist: pytest>=6.0; extra == "test"
Requires-Dist: autograd>=1.2; extra == "test"
Requires-Dist: pytest-cov>=4.0; extra == "test"
Requires-Dist: hypothesis>=6.0; extra == "test"
Provides-Extra: tf
Requires-Dist: tensorflow>=2.16; extra == "tf"
Provides-Extra: jax
Requires-Dist: jax>=0.4.30; extra == "jax"
Provides-Extra: torch
Requires-Dist: torch>=2.0; extra == "torch"
Provides-Extra: keras
Requires-Dist: keras>=3.0; extra == "keras"
Provides-Extra: tinygrad
Requires-Dist: tinygrad>=0.14; extra == "tinygrad"
Provides-Extra: symbolic
Requires-Dist: sympy>=1.12; extra == "symbolic"
Provides-Extra: viz
Requires-Dist: matplotlib>=3.7; extra == "viz"
Requires-Dist: networkx>=3.0; extra == "viz"
Provides-Extra: docs
Requires-Dist: mkdocs-material>=9.5; extra == "docs"
Requires-Dist: mkdocstrings[python]>=0.24; extra == "docs"
Requires-Dist: pymdown-extensions>=10.0; extra == "docs"
Provides-Extra: all
Requires-Dist: autograd>=1.2; extra == "all"
Requires-Dist: hypothesis>=6.0; extra == "all"
Requires-Dist: jax>=0.4.30; extra == "all"
Requires-Dist: keras>=3.0; extra == "all"
Requires-Dist: matplotlib>=3.7; extra == "all"
Requires-Dist: networkx>=3.0; extra == "all"
Requires-Dist: pytest>=6.0; extra == "all"
Requires-Dist: pytest-cov>=4.0; extra == "all"
Requires-Dist: sympy>=1.12; extra == "all"
Requires-Dist: tensorflow>=2.16; extra == "all"
Requires-Dist: tinygrad>=0.14; extra == "all"
Requires-Dist: torch>=2.0; extra == "all"
Dynamic: license-file

# Tangent - Source-to-Source Automatic Differentiation

[![Python 3.9–3.13](https://img.shields.io/badge/python-3.9%20--%203.13-blue.svg)](https://www.python.org/downloads/)
[![CI](https://github.com/pedronahum/tangent/actions/workflows/ci.yml/badge.svg)](https://github.com/pedronahum/tangent/actions/workflows/ci.yml)
[![Tests](https://img.shields.io/badge/tests-79%2C000%2B%20passing-brightgreen.svg)](tests/)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![Docs](https://img.shields.io/badge/docs-pedronahum.github.io%2Ftangent-teal.svg)](https://pedronahum.github.io/tangent/)
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pedronahum/tangent/blob/master/notebooks/tangent_tutorial.ipynb)

**A Python library for automatic differentiation that generates readable, inspectable gradient code — with NumPy, JAX, TensorFlow, PyTorch, Keras 3, and tinygrad support.**

Originally developed by Google Research, now maintained and enhanced by [@pedronahum](https://github.com/pedronahum).

<p align="center">
  <img src="assets/gradient_flow.png" alt="Gradient Flow Visualization" width="70%">
  <br>
  <em>Visualize how gradients flow through your computations</em>
</p>

---

## 🌟 What Makes Tangent Unique?

Tangent performs **source-to-source** automatic differentiation: it transforms your Python code directly into gradient code that you can read, debug, and understand. Unlike black-box autodiff libraries:

- **📖 Readable**: Generated gradient code is pure Python you can inspect
- **🔍 Debuggable**: Step through gradient computation line by line
- **🎨 Visual**: Interactive computation graphs and gradient flow diagrams
- **🔧 Flexible**: One API across NumPy, JAX, TensorFlow, PyTorch, Keras 3, and tinygrad
- **🐍 Pythonic**: Control flow (`break`/`continue`/early `return`), closures, classes, list building, comprehensions, and second and third derivatives
- **⚡ Compilable**: `grad(f, compile='jax')` runs the readable adjoint at `jax.grad`+`jit` speed; a persistent disk cache amortizes compilation across processes
- **🧩 Extensible**: `@tangent.custom_vjp`, `stop_gradient`, `with tangent.checkpoint():`, and `tangent.explain()` for gradient forensics
- **🔬 Differentiable simulators**: `tangent.odeint` differentiates ODE solutions via the adjoint method (constant memory in step count)
- **🛡️ Shape-checked**: `tangent.check_shapes(f, x)` catches rank/broadcast/matmul bugs at compile time, pointing at the offending line
- **📓 Works anywhere**: `@tangent.function` captures source so gradients work in notebooks, the REPL, and `exec`-defined code; `python -m tangent doctor` diagnoses setup

![Autodiff Tool Space](docs/toolspace.png "Autodiff Tool Space")

```python
import tangent

def f(x):
    return x ** 3 - 2 * x ** 2 + 3 * x - 1

df = tangent.grad(f, verbose=1)   # prints the generated gradient code
print(df(2.0))                    # f'(2) = 7.0
```

---

## 🚀 Quick Start

### Installation

This fork is distributed on PyPI as **`tangent-ad`** (the *import* name stays
`import tangent`, like Pillow's `pillow`/`PIL`). PyPI's `tangent` package is
Google's unmaintained 2017 release — if you have it installed, run
`pip uninstall tangent` first, since both provide the `tangent` module.

```bash
# Core (NumPy gradients)
pip install tangent-ad

# Optional backends are installed as extras:
pip install "tangent-ad[jax]"       # JAX support
pip install "tangent-ad[tf]"        # TensorFlow support
pip install "tangent-ad[torch]"     # PyTorch support
pip install "tangent-ad[keras]"     # Keras 3 (backend-agnostic keras.ops)
pip install "tangent-ad[tinygrad]"  # tinygrad (method-based tensor API)
pip install "tangent-ad[viz]"       # matplotlib + networkx visualization
pip install "tangent-ad[symbolic]"  # SymPy-based algebraic optimizations
pip install "tangent-ad[all]"       # everything above, plus the test tooling

# Or straight from the repository:
pip install "tangent-ad @ git+https://github.com/pedronahum/tangent.git"
```

Python 3.9–3.13 are supported and tested in CI. Note the platform caveats in
[Backend Support](#-backend-support) (e.g. TensorFlow has no CUDA build for
aarch64).

### Basic Usage

```python
import tangent
import numpy as np

def f(x):
    return x ** 3 - 2 * x ** 2 + 3 * x - 1

df = tangent.grad(f)
print(df(2.0))   # 7.0
```

### Multi-Backend Usage

The same `tangent.grad` API differentiates code written against any supported
array library:

```python
# NumPy
def f_np(x):
    return np.sum(x ** 2)

# JAX
def f_jax(x):
    return jnp.sum(jnp.tanh(x))

# TensorFlow
def f_tf(x):
    return tf.reduce_sum(tf.tanh(x))

# PyTorch
def f_torch(x):
    return torch.sum(torch.tanh(x))

# Keras 3 — works with whichever Keras backend is active
def f_keras(x):
    return kops.sum(kops.tanh(x))

# tinygrad — method-based tensor API
def f_tinygrad(x):
    return x.tanh().sum()

for f in (f_np, f_jax, f_tf, f_torch, f_keras, f_tinygrad):
    df = tangent.grad(f)
```

Each backend extension registers adjoints (reverse mode) and, for most ops,
forward-mode tangents; see the per-extension lists in
[Backend Support](#-backend-support).

---

## 🖥️ Backend Support

| Backend | Module | Reverse-mode adjoints | Forward-mode tangents | Notes |
|---|---|---|---|---|
| NumPy | `tangent/grads.py` + `numpy_extended.py` | 90+ | 55+ | Core gradients plus extended ops (matmul, einsum, sort, reductions, statistics, shape ops, cholesky/eigvalsh) |
| JAX | `tangent/jax_extensions.py` | 50+ | 45+ | `jax.numpy` ops and `jax.nn` activations; JAX is the reference for second-order tests |
| TensorFlow 2.x | `tangent/tf_extensions.py` + `tf_extended.py` | 45+ | 20+ | Eager-mode TF; includes conv/pooling, linalg, and reductions |
| PyTorch | `tangent/torch_extensions.py` | 45+ | 30+ | Functional `torch.*` API, verified against `torch.autograd` |
| Keras 3 | `tangent/keras_extensions.py` | 35+ | ~20 | Backend-agnostic `keras.ops`; runs on the TF, JAX, or torch backend |
| tinygrad | `tangent/tinygrad_extensions.py` | 65+ | ~20 | Method-based `Tensor.*` API incl. conv2d/max_pool2d/avg_pool2d/layernorm/batchnorm; generated gradient code is a tinygrad graph that tinygrad's own compiler fuses. Verified against tinygrad's autodiff |

Backend notes worth knowing:

- **Optional by design** — extensions load when the backend is importable and
  warn (not fail) otherwise. Core NumPy autodiff always works.
- **Keras backend choice** — `keras.ops` gradients run on whichever backend
  Keras is configured with (`KERAS_BACKEND=tensorflow|jax|torch`). Verified
  with the TensorFlow and JAX backends; the torch backend works in
  torch-only environments, but importing TensorFlow and torch in one process
  can crash on some platforms (e.g. aarch64/GB10) — a platform issue, not a
  Tangent one.
- **TensorFlow seeds** — pass an explicit seed matching your tensor dtype
  (e.g. `df(x, tf.constant(1.0, dtype=x.dtype))`); TF does not implicitly mix
  float64 Python-float seeds with float32 tensors.
- **Aliases** — torch aliases (`torch.negative`/`subtract`/`multiply`/`divide`)
  are registered alongside the short names.
- **tinygrad's method API** — tinygrad exposes ops as methods (`x.relu()`,
  `x.sum()`). Tangent resolves calls against a function's globals, so a method
  on a computed tensor isn't statically resolvable; the tinygrad extension
  registers a method resolver that rewrites such calls to unbound form
  (`Tensor.sum(x)`). This is scoped to functions whose module actually imports
  tinygrad, so plain NumPy `.sum()` elsewhere is unaffected. The generated
  gradient code is itself a tinygrad graph, which tinygrad's compiler schedules
  and fuses.
- **tinygrad conv/pool limitations** — `conv2d` gradients require `groups=1`
  (the input gradient supports any stride/dilation/padding; the weight gradient
  any stride/dilation); `max_pool2d` gradients require `dilation=1`, no
  `ceil_mode`, no `return_indices`, 3-D/4-D inputs, and symmetric padding;
  `avg_pool2d` gradients require the defaults (`count_include_pad`, no
  `ceil_mode`). Unsupported configurations raise `NotImplementedError`.
- **The `@` operator** — `x @ y` differentiates for NumPy, JAX, TensorFlow,
  PyTorch and tinygrad (backend-dispatched via
  `tangent.utils.register_matmul_grad`).

A shared cross-backend test suite (`tests/test_backend_coverage.py`) runs one
op catalog — arithmetic, exp/log, trig, activations, reductions, matmul,
reshape, transpose — through every installed backend and checks the results
against analytic gradients, keeping all six extensions at the same coverage
bar.

---

## 🎨 Gallery of Gradients: See the Magic

**The killer feature: readable gradient code.** [![Docs](https://img.shields.io/badge/docs-pedronahum.github.io%2Ftangent-teal.svg)](https://pedronahum.github.io/tangent/)
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pedronahum/tangent/blob/master/examples/Gallery_of_Gradients.ipynb)

Unlike black-box autodiff libraries, Tangent shows you **exactly** how gradients are computed. The gallery walks through 8 examples:

- 🔢 Polynomial derivatives (chain rule basics)
- 🔄 For loops that run **in reverse** during backprop
- 🌀 While loops with stack-based tape recording
- 🔀 Conditional branching (if/else and ternaries)
- 📊 NumPy array operations and broadcasting
- 📦 Nested function inlining
- 🔢 Matrix operations with colon slicing
- ⚡ Optimization comparison (before/after)

Each example shows: **original function → generated gradient code → why it looks that way → verification**.

**[→ Explore the Gallery](https://colab.research.google.com/github/pedronahum/tangent/blob/master/examples/Gallery_of_Gradients.ipynb)** | [📖 Documentation](examples/README_GALLERY.md)

---

## 🚀 Real-World Example: Building Energy Optimization

[![Docs](https://img.shields.io/badge/docs-pedronahum.github.io%2Ftangent-teal.svg)](https://pedronahum.github.io/tangent/)
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pedronahum/tangent/blob/master/examples/Building_Energy_Optimization_with_Tangent.ipynb)

Optimize building heating to minimize energy costs — a real-world differentiable simulation.

> **Based on**: PassiveLogic's [Breaking the AI Speed Barrier](https://passivelogic.com/blog/?post=breaking-ai-speed-barrier-blog) and their [Differentiable Swift Examples](https://github.com/PassiveLogic/differentiable-swift-examples/tree/main/Benchmarks/BuildingSimulation). This example demonstrates how Tangent achieves similar performance in Python.

```python
import tangent

# Physical simulation: building temperature dynamics
def simulate_building(heating_schedule, outdoor_temp, electricity_price, params):
    T = params['T_initial']
    total_cost = 0.0
    for t in range(len(heating_schedule)):
        dT_dt = (outdoor_temp[t] - T) / (params['R'] * params['C']) + \
                heating_schedule[t] / params['C']
        T = T + params['dt'] * dT_dt
        total_cost += electricity_price[t] * heating_schedule[t] + \
                     params['lambda_comfort'] * (T - params['T_target']) ** 2
    return total_cost

# 🎯 Automatic differentiation — one line
grad_simulate = tangent.grad(simulate_building, optimized=True)
gradient = grad_simulate(heating_schedule, outdoor_temp, electricity_price, params)
```

**[→ Open Interactive Notebook](https://colab.research.google.com/github/pedronahum/tangent/blob/master/examples/Building_Energy_Optimization_with_Tangent.ipynb)**

---

## 🐍 Python Feature Support

Tangent supports a broad subset of Python for numerical computing:

- **Control flow**: `if`/`elif`/`else`, `for` loops (with `range`/`enumerate`/`zip`), `while` loops, ternary expressions
- **Operators**: arithmetic, comparisons, boolean (`and`, `or`, `not`), augmented assignment (`+=`, `-=`, `*=`, `/=`, `**=`)
- **Functions**: lambdas, closures and factories, nested calls, default/keyword arguments
- **Classes**: user-defined classes with method inlining, instance attributes, method chaining, inheritance and `super()`
- **Data**: NumPy arrays; **pytrees** — tuples, lists and (nested) dicts of arrays can be passed as arguments and indexed/looped, with gradients returned in the same structure, and **returned** as outputs (the default seed is a matching pytree of ones — the gradient of the sum of all leaves — and a caller-supplied seed of the same structure is used as the cotangent); differentiable list building with `xs.append(v)` / `v = xs.pop()`; list comprehensions over both constant iterables (unrolled) and runtime iterables (lowered into differentiable loops, runtime `if` filters and nesting included); set/dict comprehensions over compile-time-constant iterables
- **Statements**: `assert`, `pass`, early `return`
- **Higher-order**: `grad(grad(f))` second derivatives, third derivatives for NumPy functions, Hessian-vector products

**📖 Complete reference with examples**: [Python Feature Support Guide](docs/features/PYTHON_FEATURE_SUPPORT.md) — plus focused feature docs under [`docs/features/`](docs/features/).

Supported: `break`/`continue` (lowered into guard flags with exact gradients). Not supported: `@property`/`@classmethod`/`@staticmethod`, generators, and in-place array mutation through augmented subscript assignment. See the feature guide for the full list.

---

## ⚡ Advanced Optimization Pipeline

`tangent.grad(f, optimized=True)` runs a multi-pass optimization pipeline that produces production-grade gradient code:

1. **Constant folding** — evaluate constant expressions at compile time
2. **Dead code elimination** — activity analysis + backward slicing remove unused computation (typically 30–50% of generated code)
3. **Assignment propagation** — inline single-use variables
4. **Strength reduction** — `x ** 2` → `x * x`, `x / c` → `x * (1/c)`
5. **Common subexpression elimination** — reuse repeated subexpressions
6. **Algebraic simplification** — SymPy-based identities (`sin² + cos² → 1`)
7. **Fixed-point iteration** — repeat until stable

**Measured impact** on the building-energy example: **2.35×** end-to-end with the full pipeline (1.95× from DCE alone).

```python
df = tangent.grad(f, optimized=True)          # production
df = tangent.grad(f, optimized=False)         # all intermediate steps (education/debugging)
df = tangent.grad(f, optimized=True, verbose=1)  # prints what each pass did
```

**Deep dives**: [Symbolic Optimizations](docs/optimizations/SYMBOLIC_OPTIMIZATIONS_COMPLETE.md) · [Strength Reduction](docs/optimizations/STRENGTH_REDUCTION_COMPLETE.md) · [Performance Analysis](docs/optimizations/PERFORMANCE_ANALYSIS.md) · [Straight-Line Coarsening](docs/optimizations/COARSENING.md) · [DCE implementation](tangent/optimizations/dce.py)

### Straight-line coarsening (opt-in)

A different, symbolic strategy is available for hot straight-line kernels.
Instead of emitting one adjoint statement (and one tape push/pop) per
primitive op, Tangent lifts the whole segment into a single SymPy expression,
differentiates it once, and emits a compact vector-Jacobian product:

```python
df = tangent.grad(f, optimizations={'coarsening': True})
```

For a small straight-line kernel the difference is dramatic — the per-op
reverse pass emits dozens of adjoint statements and tape pushes, while
coarsening emits one compact VJP:

```python
def kernel(a, b, c):
    return (np.exp(np.sin(a * b)) + c) * a

# Coarsened adjoint (auto-generated):
#   ba = bret * (c + a*b*cos(a*b)*exp(sin(a*b)) + exp(sin(a*b)))
#   bb = bret * a**2 * cos(a*b) * exp(sin(a*b))
#   bc = a * bret
```

It currently coarsens the elementwise ops `sin, cos, tan, exp, log, sqrt,
arcsin, arccos, arctan` (and `+ - * / **`). It is a prototype and
deliberately conservative: it only applies to reverse-mode gradients of pure
straight-line segments of NumPy elementwise arithmetic. Anything else —
control flow, reductions such as `np.sum`, non-NumPy backends
(JAX/PyTorch/TensorFlow/Keras), varargs, multi-output configurations, or
`preserve_result` — transparently falls back to the standard pipeline, so
enabling it never changes correctness. Requires the `symbolic` extra
(see [Installation](#installation)). See
[tangent/optimizations/coarsening.py](tangent/optimizations/coarsening.py),
[docs/optimizations/COARSENING.md](docs/optimizations/COARSENING.md), and the
worked demo in [`examples/recent_features.py`](examples/recent_features.py).

---

## 🎨 Visualization Tools

Interactive tools for understanding autodiff (install with the `viz` extra, see
[Installation](#installation)):

| Tool | What it shows |
|---|---|
| `tangent.visualize(f, mode='graph')` | Computation graph: inputs, operations, output |
| `tangent.visualize(f, mode='flow', inputs=(2.0,))` | Forward values + backward gradient propagation |
| `tangent.compare_gradients(f, (x,))` | Autodiff vs numerical gradients, side by side |
| `tangent.show_gradient_code(f)` | Pretty-printed original + generated gradient code |

```python
import tangent
import matplotlib.pyplot as plt

def f(x):
    return x * x + 2.0 * x + 1.0

fig = tangent.visualize(f, mode='flow', inputs=(2.0,))
plt.show()
```

![Computation Graph](assets/computation_graph.png)

Run `python examples/demo_visualization.py` to generate the full set of demo plots.

---

## 🔬 Advanced Features

### Multiple gradients

```python
def f(x, y):
    return x * x * y + x * y * y

df = tangent.grad(f, wrt=(0, 1))
grad_x, grad_y = df(2.0, 3.0)   # ∂f/∂x = 21.0, ∂f/∂y = 16.0
```

### Preserve results

```python
df = tangent.grad(f, preserve_result=True)
gradient, result = df(x)   # both the gradient and the primal value
```

### Forward and reverse mode

```python
df_rev = tangent.grad(f)                          # reverse mode (default)
df_fwd = tangent.autodiff(f, mode='forward')      # forward mode
```

### Second and third derivatives

```python
def f(x):
    return x ** 3

ddf = tangent.grad(tangent.grad(f))
print(ddf(2.0))   # 12.0  (d²/dx² x³ = 6x)

dddf = tangent.grad(ddf)
print(dddf(2.0))  # 6.0   (d³/dx³ x³ = 6)
```

Second derivatives work in both optimized and unoptimized modes, including
through loops, across backends, and through hand-written use of the
low-level tape API (`tangent.push`/`pop`/`Stack`) — dead-code elimination is
tape-aware and only removes push/pop pairs together. Third derivatives
(differentiating the second-order adjoint code again) work for ordinary
NumPy functions in both modes. Fourth order and above is not yet reliable.

### Automatic caching

Compiled gradient functions are cached per (source, transform options), so
repeated `tangent.grad(f)` calls are orders of magnitude faster than the
first compilation. Inspect with `tangent.get_cache_stats()`.

---

## ⚠️ Known Limitations

Documented honestly — see [Python Feature Support](docs/features/PYTHON_FEATURE_SUPPORT.md) for details:

- **Fourth-order and higher derivatives**: second and third derivatives are
  supported, but the fourth and beyond are not yet reliable — the optimized
  path can return incorrect values and the unoptimized path reaches the tape
  machinery above.
- **Containers (pytrees)**: arguments and return values may be tuples, lists
  and (nested) dicts of arrays, including second derivatives through container
  arguments. A structurally mismatched container seed is rejected with a
  `ValueError` (`tangent.match_seed` reconciles the seed with the return
  value's structure at runtime). Third and higher derivatives through
  container *outputs* are untested territory.
- **TF seed dtype** — see [Backend Support](#-backend-support).
- **SciPy** support (`scipy.special`, `scipy.linalg.solve`/`inv`) loads when
  SciPy is installed; see [Backend Support](#-backend-support).
- **Gradient checkpointing** (`tangent.grad(f, checkpoint=True)`) uses segment
  (√n) recomputation: eligible loops run untaped with state snapshots every
  ceil(√n) iterations, and the backward pass replays one segment at a time —
  peak tape memory drops from O(n) to O(√n) with *identical* gradients
  (measured: 49.2 MB → 1.6 MB, a 96.8% reduction, on a 2000-iteration loop
  carrying a 1000-float state; see `benchmarks/checkpointing_memory.py`).
  Eligible `for` loops (constant bounds ≥ 100) use segment checkpointing;
  `while` loops and data-dependent iteration use online (Stumm–Walther)
  checkpointing under a fixed snapshot budget; `with tangent.checkpoint():`
  annotates specific loops (any runtime bound). First-order reverse mode only —
  higher-order derivatives of a checkpointed gradient are not supported. See
  the [Checkpointing User Guide](docs/checkpointing_user_guide.md).

---

## 📖 Examples

### Linear regression

```python
import tangent
import numpy as np

X = np.random.randn(100, 1)
y = 3 * X + 2 + np.random.randn(100, 1) * 0.5

def mse_loss(w, b):
    return np.mean((w * X + b - y) ** 2)

dmse_dw = tangent.grad(mse_loss, wrt=(0,))
dmse_db = tangent.grad(mse_loss, wrt=(1,))

w, b, lr = 0.0, 0.0, 0.1
for epoch in range(50):
    w -= lr * dmse_dw(w, b)
    b -= lr * dmse_db(w, b)
```

### Neural network with JAX

```python
import tangent
import jax.numpy as jnp
import jax

def neural_network(W1, b1, W2, b2, X, y):
    hidden = jax.nn.relu(jnp.dot(X, W1) + b1)
    output = jax.nn.sigmoid(jnp.dot(hidden, W2) + b2)
    return -jnp.mean(y * jnp.log(output) + (1 - y) * jnp.log(1 - output))

dnn_dW1 = tangent.grad(neural_network, wrt=(0,))
# ... one grad per parameter; use in your training loop
```

### Runnable scripts

See [`examples/`](examples/README.md) for self-contained, runnable demos. The
best starting point is **[`examples/recent_features.py`](examples/recent_features.py)**,
which showcases coarsening, pytree arguments, multi-backend gradients,
differentiable concat/stack, and second derivatives in one script:

```bash
python examples/recent_features.py
```

### Notebooks

- [Tangent Tutorial](https://colab.research.google.com/github/pedronahum/tangent/blob/master/notebooks/tangent_tutorial.ipynb) — general introduction
- [Gallery of Gradients](https://colab.research.google.com/github/pedronahum/tangent/blob/master/examples/Gallery_of_Gradients.ipynb) — readable-code showcase
- [Building Energy Optimization](https://colab.research.google.com/github/pedronahum/tangent/blob/master/examples/Building_Energy_Optimization_with_Tangent.ipynb) — real-world application

---

## 🧪 Testing

The suite covers core autodiff, every Python feature, all six backends, and
second and third derivatives. The cross-backend catalog is checked two ways:
against hand-derived analytic gradients **and** against an independent
finite-difference oracle, so newly added adjoints are verified automatically:

```bash
pytest tests/                        # core suite (no backends required)
pytest tests/test_backend_coverage.py  # cross-backend op catalog (+ FD oracle)
pytest tests/test_coarsening.py      # straight-line coarsening
pytest tests/test_matmul_operator.py # @ operator (NumPy)
pytest tests/test_numpy_method_calls.py  # NumPy array-method rewrite
pytest tests/test_torch.py           # PyTorch-specific tests
pytest tests/test_keras.py           # Keras tests (any backend)
pytest tests/test_tinygrad.py        # tinygrad-specific tests
```

Current status: **79,000+ parameterized test cases pass, with zero failures
and zero expected-failure (`xfail`) markers** (last local measurement: 79,710
passed, 55 skipped, with NumPy, JAX, PyTorch-CPU, tinygrad, Keras 3, SymPy,
SciPy and TensorFlow all installed). CI runs the suite on
Python 3.9–3.13 and exercises the cross-backend catalog against every
installed backend.

---

## 📊 Repository Structure

```
tangent/
├── tangent/                      # Core library
│   ├── grad_util.py              # Main autodiff engine (grad/autodiff/vjp/jvp)
│   ├── reverse_ad.py             # Reverse-mode transformation
│   ├── forward_ad.py             # Forward-mode transformation
│   ├── grads.py                  # Core NumPy adjoints
│   ├── tangents.py               # Core forward-mode tangents
│   ├── numpy_extended.py         # Extended NumPy adjoints
│   ├── jax_extensions.py         # JAX adjoints + tangents
│   ├── tf_extensions.py          # TensorFlow adjoints + tangents
│   ├── tf_extended.py            # Extended TensorFlow adjoints
│   ├── torch_extensions.py       # PyTorch adjoints + tangents
│   ├── keras_extensions.py       # Keras 3 (backend-agnostic) adjoints + tangents
│   ├── tinygrad_extensions.py    # tinygrad adjoints + tangents
│   ├── class_desugar.py          # Class method inlining
│   ├── visualization.py          # Visualization tools
│   ├── function_cache.py         # Gradient-function caching
│   ├── optimizations/            # DCE, CSE, strength reduction, algebraic
│   └── checkpointing_simple.py   # Manual forward-pass checkpointing helpers
├── tests/                        # 90+ test modules (79k+ cases)
│   ├── test_backend_coverage.py  # Cross-backend op catalog
│   ├── test_torch.py             # PyTorch tests
│   ├── test_keras.py             # Keras tests
│   ├── test_jax.py               # JAX tests
│   ├── test_tensorflow.py        # TensorFlow tests
│   └── ...                       # Feature and engine tests
├── examples/                     # Scripts and notebooks
├── notebooks/                    # Interactive tutorials
├── benchmarks/                   # Performance benchmarks
└── docs/                         # Feature/optimization/benchmark docs
```

---

## 📚 Documentation

- **[→ Full Documentation Index](docs/INDEX.md)**
- **[Python Feature Support](docs/features/PYTHON_FEATURE_SUPPORT.md)** — the definitive feature reference
- **[Framework Comparison](docs/benchmarks/FRAMEWORK_COMPARISON.md)** — Tangent vs TensorFlow vs PyTorch benchmarks
- **[Optimizations](docs/optimizations/)** — CSE, strength reduction, performance analysis
- **[Checkpointing User Guide](docs/checkpointing_user_guide.md)** — gradient checkpointing: what works today and what doesn't

---

## 🤝 Contributing

Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md). Good starting points:

- Additional gradient definitions (extend any backend module + the cross-backend catalog)
- The open items in [Known Limitations](#-known-limitations)
- Documentation improvements

1. Fork the repository
2. Create a feature branch
3. Add tests for your changes (`pytest tests/` must stay green)
4. Submit a pull request

---

## 📝 License

Apache License 2.0 — see [LICENSE](LICENSE).

Original work Copyright 2017 Google Inc.
Modified work Copyright 2024–2026 Pedro Nahum

---

## 🙏 Acknowledgments

- Original Tangent library by Google Research
- The JAX, TensorFlow, and PyTorch teams for the numerical computing ecosystems
- The Python scientific computing community

---

## 📬 Contact

- **Repository**: [github.com/pedronahum/tangent](https://github.com/pedronahum/tangent)
- **Issues**: [github.com/pedronahum/tangent/issues](https://github.com/pedronahum/tangent/issues)
- **Author**: [@pedronahum](https://github.com/pedronahum)

---

**Built with ❤️ for the machine learning and scientific computing communities**
