<commit_before>"""Generic trainer for TensorFlow models."""
#  Copyright 2015-present Scikit Flow Authors. All Rights Reserved.
#
#  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.

from __future__ import division, print_function, absolute_import

import sys
import math
from six.moves import xrange   # pylint: disable=redefined-builtin

import numpy as np
import tensorflow as tf


OPTIMIZER_CLS_NAMES = {
    "SGD": tf.train.GradientDescentOptimizer,
    "Adagrad": tf.train.AdagradOptimizer,
    "Adam": tf.train.AdamOptimizer,
}


def _print_report(print_loss_buffer, global_step):
    """Prints report for given losses and global step."""
    avg_loss = np.mean(print_loss_buffer)
    print("Step #{step}, avg. loss: {loss:.5f}".format(step=global_step,
                                                       loss=avg_loss))


class TensorFlowTrainer(object):
    """General trainer class.

    Attributes:
      model: Model object.
      gradients: Gradients tensor.
    """

    def __init__(self, loss, global_step, optimizer,
                 learning_rate, clip_gradients=5.0, exponential_decay=None):
        """Build a trainer part of graph.

        Args:
          loss: Tensor that evaluates to model's loss.
          global_step: Tensor with global step of the model.
          optimizer: Name of the optimizer class (SGD, Adam, Adagrad) or class.
          learning_rate: This would be the initial learning_rate if
                         exponential_decay is specified.
          exponential_decay: Whether to apply exponential_decay to the learning_rate.
                             A dict type containing the following keys: global_step(int),
                             decay_steps(int), decay_rate(float), and staircase(bool).
        """
        self.loss = loss
        self.global_step = global_step
        if exponential_decay is not None:
            if isinstance(exponential_decay, dict):
                self._learning_rate = tf.train.exponential_decay(
                    learning_rate, exponential_decay["global_step"],
                    exponential_decay["decay_steps"], exponential_decay["decay_rate"],
                    exponential_decay["staircase"])
            else:
                raise ValueError("exponential_decay must be a dict type.")
        else:
            self._learning_rate = tf.get_variable(
            "learning_rate",
            [],
            initializer=tf.constant_initializer(learning_rate))
        params = tf.trainable_variables()
        self.gradients = tf.gradients(loss, params)
        if clip_gradients > 0.0:
            self.gradients, self.gradients_norm = tf.clip_by_global_norm(
                self.gradients, clip_gradients)
        grads_and_vars = zip(self.gradients, params)
        if isinstance(optimizer, str):<commit_msg>* Locally disable pylint for redefined-variable-type<commit_after>"""Generic trainer for TensorFlow models."""
#  Copyright 2015-present Scikit Flow Authors. All Rights Reserved.
#
#  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.

from __future__ import division, print_function, absolute_import

import sys
import math
from six.moves import xrange   # pylint: disable=redefined-builtin

import numpy as np
import tensorflow as tf


OPTIMIZER_CLS_NAMES = {
    "SGD": tf.train.GradientDescentOptimizer,
    "Adagrad": tf.train.AdagradOptimizer,
    "Adam": tf.train.AdamOptimizer,
}


def _print_report(print_loss_buffer, global_step):
    """Prints report for given losses and global step."""
    avg_loss = np.mean(print_loss_buffer)
    print("Step #{step}, avg. loss: {loss:.5f}".format(step=global_step,
                                                       loss=avg_loss))


class TensorFlowTrainer(object):
    """General trainer class.

    Attributes:
      model: Model object.
      gradients: Gradients tensor.
    """

    def __init__(self, loss, global_step, optimizer,
                 learning_rate, clip_gradients=5.0, exponential_decay=None):
        """Build a trainer part of graph.

        Args:
          loss: Tensor that evaluates to model's loss.
          global_step: Tensor with global step of the model.
          optimizer: Name of the optimizer class (SGD, Adam, Adagrad) or class.
          learning_rate: This would be the initial learning_rate if
                         exponential_decay is specified.
          exponential_decay: Whether to apply exponential_decay to the learning_rate.
                             A dict type containing the following keys: global_step(int),
                             decay_steps(int), decay_rate(float), and staircase(bool).
        """
        self.loss = loss
        self.global_step = global_step
        # pylint: disable=redefined-variable-type
        if exponential_decay is not None:
            if isinstance(exponential_decay, dict):
                self._learning_rate = tf.train.exponential_decay(
                    learning_rate, exponential_decay["global_step"],
                    exponential_decay["decay_steps"], exponential_decay["decay_rate"],
                    exponential_decay["staircase"])
            else:
                raise ValueError("exponential_decay must be a dict type.")
        else:
            self._learning_rate = tf.get_variable(
                "learning_rate",
                [],
                initializer=tf.constant_initializer(learning_rate))
        params = tf.trainable_variables()
        self.gradients = tf.gradients(loss, params)
        if clip_gradients > 0.0:
            self.gradients, self.gradients_norm = tf.clip_by_global_norm(
                self.gradients, clip_gradients)
        grads_and_vars = zip(self.gradients, params)
        if isinstance(optimizer, str):
{'fraction_non_alphanumeric': 0.07958426132145509, 'fraction_numerical': 0.003860430586488493, 'mean_word_length': 2.547130068457083, 'pattern_counts': {'":': 6, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5065771', 'n_tokens_mistral': 1862, 'n_tokens_neox': 1798, 'n_words': 558}