# Lint as: python3
# Copyright 2021 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.
# ==============================================================================
"""Learning rate schedule."""

import math

import jax
from jax import numpy as jnp
from lingvo.jax import py_utils
from lingvo.jax import pytypes
import optax

JTensor = pytypes.JTensor
InstantiableParams = py_utils.InstantiableParams


class BaseSchedule:
  """Base class for all schedules."""

  @classmethod
  def Params(cls) -> InstantiableParams:  # pylint:disable=invalid-name
    p = InstantiableParams(cls)
    return p

  def __init__(self, params: InstantiableParams) -> None:
    self._params = params.Copy()

  @property
  def params(self) -> InstantiableParams:
    return self._params

  def value(self, count: JTensor) -> JTensor:  # pylint:disable=invalid-name
    """Returns the value of schedule at step 'count'.

    Args:
      count: a scalar uint32 array.

    Returns:
      A float32 value of the schedule at step 'count' as a scalar array.
    """
    raise NotImplementedError()


class Constant(BaseSchedule):
  """A schedule whose value is a constant."""

  @classmethod
  def Params(cls) -> InstantiableParams:  # pylint:disable=invalid-name
    p = super().Params()
    p.Define('value', 1., 'The constant value.')
    return p

  def value(self, count: JTensor) -> JTensor:
    del count
    return jnp.array(self.params.value, dtype=jnp.float32)


class Polynomial(BaseSchedule):
  """Polynomial learning rate schedule.

  If x < x0, returns y0. If x >= x1, returns y1. Otherwise, interpolate with
  a polynomial between (x0, y0) and (x1, y1).
  """

  @classmethod
  def Params(cls) -> InstantiableParams:  # pylint:disable=invalid-name
    p = super().Params()
    p.Define('power', 1, 'Polynomial power.')
    p.Define('start', (0, 1.), '(x0, y0)')
    p.Define('limit', (1, 1.), '(x1, y1)')
    p.Define('origin', 'start',
             'Origin of the polynomial. Can be "start" or "limit".')
    return p

  def __init__(self, params: InstantiableParams) -> None:
    super().__init__(params)
    p = self.params
    if len(p.start) != 2:
      raise ValueError(f'{p.start} must be of length 2.')
    if len(p.limit) != 2:
      raise ValueError(f'{p.limit} must be of length 2.')
    x0, _ = p.start
    x1, _ = p.limit
    if x0 >= x1:
      raise ValueError(f'{x0} must be < {x1}')
    if p.origin not in {'start', 'limit'}:
      raise ValueError('Invalid parameter origin: %s' % p.origin)

  def value(self, count: JTensor) -> JTensor:
    p = self.params
    x = jnp.array(count).astype(jnp.float32)