# AUTOGENERATED FROM: babilim/core/gradient_tape.ipynb

# Cell: 0
"""doc
# babilim.core.gradient_tape

> Keeps track of gradiens in a block.

This code is under the MIT License.
"""

# Cell: 1
# MIT License
#
# Copyright (c) 2019 Michael Fuerst
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from typing import List
import babilim
from babilim import PYTORCH_BACKEND, TF_BACKEND


# Cell: 2
"""doc
# Gradient Tape

The gradient tape helps with keeping track of the gradients with a unified API for pytorch and tensorflow.
"""

# Cell: 3
def GradientTape(variables: List) -> object:
    """
    Collect the gradients for the block within a with statement.

    :param variables: The variables for which the gradients should be tracked.
    """
    if babilim.get_backend() == PYTORCH_BACKEND:
        from babilim.core.gradient_tape_pt import GradientTapePT
        return GradientTapePT(variables)
    elif babilim.get_backend() == TF_BACKEND:
        from babilim.core.gradient_tape_tf import GradientTapeTF
        return GradientTapeTF(variables)
    else:
        raise RuntimeError("No variable implementation for this backend was found. (backend={})".format(babilim.get_backend()))


# Cell: 4
"""doc
A simple example illustrates the usage best.

```python
with GradientTape(model.trainable_variables) as tape:
    preds = model(**features._asdict())
    loss = loss_fn(preds, labels)
tape.gradient(loss)
```
"""