# Copyright 2017 The TensorFlow 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.
# ==============================================================================
"""Tests for tf.contrib.kfac.estimator."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np

from tensorflow.contrib.kfac.python.ops import estimator
from tensorflow.contrib.kfac.python.ops import layer_collection as lc
from tensorflow.contrib.kfac.python.ops import utils
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import linalg_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
from tensorflow.python.training import training_util

_ALL_ESTIMATION_MODES = ["gradients", "empirical", "curvature_prop", "exact"]


class EstimatorTest(test.TestCase):

  def setUp(self):
    self._graph = ops.Graph()
    with self._graph.as_default():
      self.layer_collection = lc.LayerCollection()

      self.inputs = random_ops.random_normal((2, 2), dtype=dtypes.float32)
      self.weights = variable_scope.get_variable(
          "w", shape=(2, 2), dtype=dtypes.float32)
      self.bias = variable_scope.get_variable(
          "b", initializer=init_ops.zeros_initializer(), shape=(2, 1))
      self.output = math_ops.matmul(self.inputs, self.weights) + self.bias

      # Only register the weights.
      self.layer_collection.register_fully_connected(
          params=(self.weights,), inputs=self.inputs, outputs=self.output)

      self.outputs = math_ops.tanh(self.output)
      self.targets = array_ops.zeros_like(self.outputs)
      self.layer_collection.register_categorical_predictive_distribution(
          logits=self.outputs, targets=self.targets)

  def testEstimatorInitManualRegistration(self):
    with self._graph.as_default():
      # We should be able to build an estimator for only the registered vars.
      estimator.FisherEstimatorRoundRobin(
          variables=[self.weights],
          cov_ema_decay=0.1,
          damping=0.2,
          layer_collection=self.layer_collection
      )

      # Check that we throw an error if we try to build an estimator for vars
      # that were not manually registered.
      with self.assertRaises(ValueError):
        est = estimator.FisherEstimatorRoundRobin(
            variables=[self.weights, self.bias],
            cov_ema_decay=0.1,
            damping=0.2,
            layer_collection=self.layer_collection
        )
        est.make_ops_and_vars()

      # Check that we throw an error if we don't include registered variables,
      # i.e. self.weights
      with self.assertRaises(ValueError):
        est = estimator.FisherEstimatorRoundRobin(
            variables=[],
            cov_ema_decay=0.1,
            damping=0.2,
            layer_collection=self.layer_collection)
        est.make_ops_and_vars()

  @test.mock.patch.object(utils.SubGraph, "variable_uses", return_value=42)
  def testVariableWrongNumberOfUses(self, mock_uses):
    with self.assertRaises(ValueError):
      est = estimator.FisherEstimatorRoundRobin(
          variables=[self.weights],
          cov_ema_decay=0.1,
          damping=0.2,
          layer_collection=self.layer_collection)
      est.make_ops_and_vars()

  def testInvalidEstimationMode(self):
    with self.assertRaises(ValueError):
      est = estimator.FisherEstimatorRoundRobin(
          variables=[self.weights],
          cov_ema_decay=0.1,
          damping=0.2,
          layer_collection=self.layer_collection,
          estimation_mode="not_a_real_mode")
      est.make_ops_and_vars()

  def testGradientsModeBuild(self):
    with self._graph.as_default():
      est = estimator.FisherEstimatorRoundRobin(
          variables=[self.weights],
          cov_ema_decay=0.1,
          damping=0.2,
          layer_collection=self.layer_collection,
          estimation_mode="gradients")
      est.make_ops_and_vars()

  def testEmpiricalModeBuild(self):
    with self._graph.as_default():
      est = estimator.FisherEstimatorRoundRobin(
          variables=[self.weights],
          cov_ema_decay=0.1,
          damping=0.2,
          layer_collection=self.layer_collection,
          estimation_mode="empirical")
      est.make_ops_and_vars()

  def testCurvaturePropModeBuild(self):
    with self._graph.as_default():
      est = estimator.FisherEstimatorRoundRobin(
          variables=[self.weights],
          cov_ema_decay=0.1,
          damping=0.2,
          layer_collection=self.layer_collection,
          estimation_mode="curvature_prop")
      est.make_ops_and_vars()