# Path: t5x/examples/scalable_t5/layers.py
# def _compute_fans(shape: jax.core.NamedShape, in_axis=-2, out_axis=-1):
# def variance_scaling(scale, mode, distribution, in_axis=-2, out_axis=-1,
#                      dtype=jnp.float_):
#   def init(key, shape, dtype=dtype):
# def nd_dense_init(scale, mode, distribution):
#   def init_fn(key, shape, dtype, in_axis, out_axis):
# def dot_product_attention(query: Array,
#                           key: Array,
#                           value: Array,
#                           bias: Optional[Array] = None,
#                           dropout_rng: Optional[PRNGKey] = None,
#                           dropout_rate: float = 0.,
#                           deterministic: bool = False,
#                           dtype: DType = jnp.float32,
#                           float32_logits: bool = False):
#   def __call__(self,
#                inputs_q: Array,
#                inputs_kv: Array,
#                mask: Optional[Array] = None,
#                bias: Optional[Array] = None,
#                *,
#                decode: bool = False,
#                deterministic: bool = False) -> Array:
# def _normalize_axes(axes: Iterable[int], ndim: int) -> Tuple[int]:
# def _canonicalize_tuple(x):
#   def __call__(self, inputs: Array) -> Array:
# def _convert_to_activation_function(
#     fn_or_string: Union[str, Callable]) -> Callable:
#   def __call__(self, inputs, decode: bool = False, deterministic: bool = False):
#   def setup(self):
#   def __call__(self, inputs: Array) -> Array:
#   def attend(self, query: Array) -> Array:
#   def _relative_position_bucket(relative_position,
#                                 bidirectional=True,
#                                 num_buckets=32,
#                                 max_distance=128):
#   def __call__(self, qlen, klen, bidirectional=True):
#   def __call__(self, x: jnp.ndarray) -> jnp.ndarray:
# def make_attention_mask(query_input: Array,
#                         key_input: Array,
#                         pairwise_fn: Callable = jnp.multiply,
#                         extra_batch_dims: int = 0,
#                         dtype: DType = jnp.float32) -> Array:
# def make_causal_mask(x: Array,
#                      extra_batch_dims: int = 0,
#                      dtype: DType = jnp.float32) -> Array:
# def combine_masks(*masks: Optional[Array], dtype: DType = jnp.float32):
# def combine_biases(*masks: Optional[Array]):
# def make_decoder_mask(decoder_target_tokens: Array,
#                       dtype: DType,
#                       decoder_causal_attention: Optional[Array] = None,
#                       decoder_segment_ids: Optional[Array] = None) -> Array:
# class MultiHeadDotProductAttention(nn.Module):
# class DenseGeneral(nn.Module):
# class MlpBlock(nn.Module):
# class Embed(nn.Module):
# class RelativePositionBiases(nn.Module):
# class LayerNorm(nn.Module):


import dataclasses
import jax
import jax.numpy as jnp
import numpy as np
from typing import Optional
from unittest import mock
from absl.testing import absltest
from absl.testing import parameterized
from flax import linen as nn
from flax.core import freeze
from flax.linen import partitioning as nn_partitioning
from jax import random
from jax.nn import initializers
from t5x.examples.scalable_t5 import layers
# Copyright 2022 The T5X Authors.
#
# 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 attention classes."""



# Parse absl flags test_srcdir and test_tmpdir.
jax.config.parse_flags_with_absl()

Array = jnp.ndarray
AxisMetadata = nn_partitioning.AxisMetadata  # pylint: disable=invalid-name



# Path: t5x/examples/scalable_t5/layers.py
# def _compute_fans(shape: jax.core.NamedShape, in_axis=-2, out_axis=-1):
# def variance_scaling(scale, mode, distribution, in_axis=-2, out_axis=-1,
#                      dtype=jnp.float_):
#   def init(key, shape, dtype=dtype):
# def nd_dense_init(scale, mode, distribution):
#   def init_fn(key, shape, dtype, in_axis, out_axis):
# def dot_product_attention(query: Array,
#                           key: Array,
#                           value: Array,
#                           bias: Optional[Array] = None,
#                           dropout_rng: Optional[PRNGKey] = None,
#                           dropout_rate: float = 0.,
#                           deterministic: bool = False,
#                           dtype: DType = jnp.float32,
#                           float32_logits: bool = False):
#   def __call__(self,
#                inputs_q: Array,
#                inputs_kv: Array,
#                mask: Optional[Array] = None,
#                bias: Optional[Array] = None,
#                *,
#                decode: bool = False,
#                deterministic: bool = False) -> Array:
# def _normalize_axes(axes: Iterable[int], ndim: int) -> Tuple[int]:
# def _canonicalize_tuple(x):
#   def __call__(self, inputs: Array) -> Array:
# def _convert_to_activation_function(
#     fn_or_string: Union[str, Callable]) -> Callable:
#   def __call__(self, inputs, decode: bool = False, deterministic: bool = False):
#   def setup(self):
#   def __call__(self, inputs: Array) -> Array:
#   def attend(self, query: Array) -> Array:
#   def _relative_position_bucket(relative_position,
#                                 bidirectional=True,
#                                 num_buckets=32,
#                                 max_distance=128):
#   def __call__(self, qlen, klen, bidirectional=True):
#   def __call__(self, x: jnp.ndarray) -> jnp.ndarray:
# def make_attention_mask(query_input: Array,
#                         key_input: Array,
#                         pairwise_fn: Callable = jnp.multiply,
#                         extra_batch_dims: int = 0,
#                         dtype: DType = jnp.float32) -> Array:
# def make_causal_mask(x: Array,
#                      extra_batch_dims: int = 0,
#                      dtype: DType = jnp.float32) -> Array:
# def combine_masks(*masks: Optional[Array], dtype: DType = jnp.float32):
# def combine_biases(*masks: Optional[Array]):
# def make_decoder_mask(decoder_target_tokens: Array,
#                       dtype: DType,
#                       decoder_causal_attention: Optional[Array] = None,
#                       decoder_segment_ids: Optional[Array] = None) -> Array:
# class MultiHeadDotProductAttention(nn.Module):
# class DenseGeneral(nn.Module):
# class MlpBlock(nn.Module):
# class Embed(nn.Module):
# class RelativePositionBiases(nn.Module):
# class LayerNorm(nn.Module):


# Path: t5x/examples/scalable_t5/layers_test.py
import dataclasses
import jax
import jax.numpy as jnp
import numpy as np
from typing import Optional
from unittest import mock
from absl.testing import absltest
from absl.testing import parameterized
from flax import linen as nn
from flax.core import freeze
from flax.linen import partitioning as nn_partitioning
from jax import random
from jax.nn import initializers
from t5x.examples.scalable_t5 import layers

# Copyright 2022 The T5X Authors.
#
# 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 attention classes."""



# Parse absl flags test_srcdir and test_tmpdir.
jax.config.parse_flags_with_absl()

Array = jnp.ndarray
AxisMetadata = nn_partitioning.AxisMetadata  # pylint: disable=invalid-name



class SelfAttention(layers.MultiHeadDotProductAttention):