""" ModuleFormer model configuration"""
from collections import OrderedDict
from typing import Any, List, Mapping, Optional

from transformers import PreTrainedTokenizer, TensorType, is_torch_available
from transformers.configuration_utils import PretrainedConfig
from transformers.onnx import OnnxConfigWithPast, PatchingSpec
from transformers.utils import logging

logger = logging.get_logger(__name__)

# SPARSEGPT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
#     "moduleformer-small": "https://huggingface.co/moduleformer-small/resolve/main/config.json",
# }

class ModuleFormerConfig(PretrainedConfig):
    r"""
    This is the configuration class to store the configuration of a [`ModuleFormerModel`]. It is used to instantiate a
    ModuleFormer model according to the specified arguments, defining the model architecture. Instantiating a configuration
    with the defaults will yield a similar configuration to that of the ModuleFormer
    [moduleformer-small](https://huggingface.co/moduleformer-small) architecture. Configuration objects
    inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from
    [`PretrainedConfig`] for more information.

    Args:
        vocab_size (`int`, *optional*, defaults to 50400):
            Vocabulary size of the ModuleFormer model. Defines the number of different tokens that can be represented by the
            `inputs_ids` passed when calling [`ModuleFormerModel`].
        n_positions (`int`, *optional*, defaults to 2048):
            The maximum sequence length that this model might ever be used with. Typically set this to something large
            just in case (e.g., 512 or 1024 or 2048).
        n_embd (`int`, *optional*, defaults to 4096):
            Dimensionality of the embeddings and hidden states.
        n_layer (`int`, *optional*, defaults to 28):
            Number of hidden layers in the Transformer encoder.
        n_head (`int`, *optional*, defaults to 16):
            Number of attention heads for each attention layer in the Transformer encoder.
        rotary_dim (`int`, *optional*, defaults to 64):
            Number of dimensions in the embedding that Rotary Position Embedding is applied to.
        n_inner (`int`, *optional*, defaults to None):
            Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd
        activation_function (`str`, *optional*, defaults to `"gelu_new"`):
            Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new"]`.
        resid_pdrop (`float`, *optional*, defaults to 0.1):
            The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
        embd_pdrop (`int`, *optional*, defaults to 0.1):
            The dropout ratio for the embeddings.
        attn_pdrop (`float`, *optional*, defaults to 0.1):
            The dropout ratio for the attention.
        layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
            The epsilon to use in the layer normalization layers.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        use_cache (`bool`, *optional*, defaults to `True`):
            Whether or not the model should return the last key/values attentions (not used by all models).

    Example:

    ```python
    >>> from transformers import ModuleFormerConfig, ModuleFormerModel

    >>> # Initializing a ModuleFormer 6B configuration
    >>> configuration = ModuleFormerConfig()

    >>> # Initializing a model (with random weights) from the configuration
    >>> model = ModuleFormerModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```"""
    model_type = "moduleformer"
    attribute_map = {
        "max_position_embeddings": "n_positions",
        "hidden_size": "n_embd",
        "num_attention_heads": "n_head",
        "num_hidden_layers": "n_layer",
    }

    def __init__(
        self,
        vocab_size=50295,
        block_size=512,
        history_length=512,
        n_embd=1024,
        n_layer=24,
        n_head=8,
        att_hidden = 512,
        ffd_hidden=2048,
        activation_function="gelu_new",
        resid_pdrop=0.0,
        embd_pdrop=0.0,
        attn_pdrop=0.0,
        moe_pdrop=0.0,
        sample_topk = 0,
        gating_size = 256,
        n_att_experts = 32,
        k_att = 2,
        n_mlp_experts = 32,
        k_mlp = 2,
        layer_norm_epsilon=1e-5,
        initializer_range=0.02,
        use_cache=True,
        bos_token_id=50256,
        eos_token_id=50256,
        tie_word_embeddings=False,
        aux_loss_type = 'mi',
        aux_loss_weight=0,
        gate_type = "mlp",
        **kwargs,
    ):
        self.vocab_size = vocab_size
        self.history_length = history_length
        self.block_size = block_size
        self.n_embd = n_embd
        self.n_layer = n_layer
        self.n_head = n_head
        self.att_hidden = att_hidden
        self.ffd_hidden = ffd_hidden
        self.activation_function = activation_function
        self.resid_pdrop = resid_pdrop
        self.embd_pdrop = embd_pdrop
        self.attn_pdrop = attn_pdrop
        self.moe_pdrop = moe_pdrop
        self.layer_norm_epsilon = layer_norm_epsilon
        self.initializer_range = initializer_range
        self.use_cache = use_cache
        self.sample_topk = sample_topk
        self.gating_size = gating_size
        self.n_att_experts = n_att_experts
        self.k_att = k_att
        self.n_mlp_experts = n_mlp_experts
        self.k_mlp = k_mlp
        self.aux_loss_type = aux_loss_type
        self.aux_loss_weight = aux_loss_weight
        self.gate_type = gate_type
        self.n_ctx = history_length * n_layer

        self.bos_token_id = bos_token_id
        self.eos_token_id = eos_token_id

        super().__init__(
            bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs
        )

class ModuleFormerOnnxConfig(OnnxConfigWithPast):
    def __init__(
        self,
        config: PretrainedConfig,
        task: str = "default",
        patching_specs: List[PatchingSpec] = None,
        use_past: bool = False,
    ):
        """
        Initialize the ModuleFormerOnnxConfig.

        Args:
            config (PretrainedConfig): Pretrained model configuration.
            task (str): Task description.
            patching_specs (List[PatchingSpec]): List of patching specifications.
            use_past (bool): Whether to use past tokens in the configuration.
        """
        super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past)
        if not getattr(self._config, "pad_token_id", None):
            # TODO: how to do that better?
            self._config.pad_token_id = 0

    @property
    def inputs(self) -> Mapping[str, Mapping[int, str]]:
        """
        Define the input mappings.

        Returns:
            Mapping[str, Mapping[int, str]]: Input mappings.
        """
        common_inputs = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
        if self.use_past:
            self.fill_with_past_key_values_(common_inputs, direction="inputs")
            common_inputs["attention_mask"] = {0: "batch", 1: "past_sequence + sequence"}
        else:
            common_inputs["attention_mask"] = {0: "batch", 1: "sequence"}

        return common_inputs

    @property
    def num_layers(self) -> int:
        """
        Get the number of layers.

        Returns:
            int: Number of layers.
        """
        return self._config.n_layer

    @property
    def num_attention_heads(self) -> int:
        """
        Get the number of attention heads.

        Returns:
            int: Number of attention heads.
        """
        return self._config.n_head

    def generate_dummy_inputs(
        self,
        tokenizer: PreTrainedTokenizer,
        batch_size: int = -1,
        seq_length: int = -1,
        is_pair: bool = False,
        framework: Optional[TensorType] = None,
    ) -> Mapping[str, Any]:
        """
        Generate dummy inputs for testing.

        Args:
            tokenizer (PreTrainedTokenizer): Pretrained tokenizer.
            batch_size (int): Batch size.
            seq_length (int): Sequence length.
            is_pair (bool): Whether the input is a pair.
            framework (Optional[TensorType]): Tensor framework.

        Returns:
            Mapping[str, Any]: Dummy inputs.
        """
        common_inputs = super(OnnxConfigWithPast, self).generate_dummy_inputs(
            tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
        )

        # We need to order the input in the way they appears in the forward()
        ordered_inputs = OrderedDict({"input_ids": common_inputs["input_ids"]})

        # Need to add the past_keys
        if self.use_past:
            if not is_torch_available():
                raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
            else:
                import torch

                batch, seqlen = common_inputs["input_ids"].shape
                # Not using the same length for past_key_values
                past_key_values_length = seqlen + 2
                past_shape = (
                    batch,
                    self.num_attention_heads,
                    past_key_values_length,
                    self._config.hidden_size // self.num_attention_heads,
                )
                ordered_inputs["past_key_values"] = [
                    (torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(self.num_layers)
                ]

        ordered_inputs["attention_mask"] = common_inputs["attention_mask"]
        if self.use_past:
            mask_dtype = ordered_inputs["attention_mask"].dtype
            ordered_inputs["attention_mask"] = torch.cat(
                [ordered_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
            )

        return ordered_inputs

    @property
    def default_onnx_opset(self) -> int:
        """
        Get the default ONNX opset version.

        Returns:
            int: Default ONNX opset version.
        """
        return 13


ModuleFormerConfig

""" ModuleFormer model configuration"""
from collections import OrderedDict
from typing import Any, List, Mapping, Optional

from transformers import PreTrainedTokenizer, TensorType, is_torch_available
from transformers.configuration_utils import PretrainedConfig
from transformers.onnx import OnnxConfigWithPast, PatchingSpec
from transformers.utils import logging

logger = logging.get_logger(__name__)

# SPARSEGPT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
#     "moduleformer-small": "https://huggingface.co/moduleformer-small/resolve/main/config.json",
# }

class ModuleFormerConfig(PretrainedConfig):
    r"""
    This is the configuration class to store the configuration of a [`ModuleFormerModel`]. It is used to instantiate a
    ModuleFormer model according to the specified arguments, defining the model architecture. Instantiating a configuration
    with the defaults will yield a similar configuration to that of the ModuleFormer
    [moduleformer-small](https://huggingface.co/moduleformer-small) architecture. Configuration objects
    inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from
    [`PretrainedConfig`] for more information.

    Args:
        vocab_size (`int`, *optional*, defaults to 50400):
            Vocabulary size of the ModuleFormer model. Defines the number of different tokens that can be represented by the
            `inputs_ids` passed when calling [`ModuleFormerModel`].
        n_positions (`int`, *optional*, defaults to 2048):
            The maximum sequence length that this model might ever be used with. Typically set this to something large
            just in case (e.g., 512 or 1024 or 2048).
        n_embd (`int`, *optional*, defaults to 4096):
            Dimensionality of the embeddings and hidden states.
        n_layer (`int`, *optional*, defaults to 28):
            Number of hidden layers in the Transformer encoder.
        n_head (`int`, *optional*, defaults to 16):
            Number of attention heads for each attention layer in the Transformer encoder.
        rotary_dim (`int`, *optional*, defaults to 64):
            Number of dimensions in the embedding that Rotary Position Embedding is applied to.
        n_inner (`int`, *optional*, defaults to None):
            Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd
        activation_function (`str`, *optional*, defaults to `"gelu_new"`):
            Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new"]`.
        resid_pdrop (`float`, *optional*, defaults to 0.1):
            The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
        embd_pdrop (`int`, *optional*, defaults to 0.1):
            The dropout ratio for the embeddings.
        attn_pdrop (`float`, *optional*, defaults to 0.1):
            The dropout ratio for the attention.
        layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
            The epsilon to use in the layer normalization layers.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        use_cache (`bool`, *optional*, defaults to `True`):
            Whether or not the model should return the last key/values attentions (not used by all models).

    Example:

    ```python
    >>> from transformers import ModuleFormerConfig, ModuleFormerModel

    >>> # Initializing a ModuleFormer 6B configuration
    >>> configuration = ModuleFormerConfig()

    >>> # Initializing a model (with random weights) from the configuration
    >>> model = ModuleFormerModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```"""
    model_type = "moduleformer"
    attribute_map = {
        "max_position_embeddings": "n_positions",
        "hidden_size": "n_embd",
        "num_attention_heads": "n_head",
        "num_hidden_layers": "n_layer",
    }

    def __init__(
        self,
        vocab_size=50295,
        block_size=512,
        history_length=512,
        n_embd=1024,
        n_layer=24,
        n_head=8,
        att_hidden = 512,
        ffd_hidden=2048,
        activation_function="gelu_new",
        resid_pdrop=0.0,
        embd_pdrop=0.0,
        attn_pdrop=0.0,
        moe_pdrop=0.0,
        sample_topk = 0,
        gating_size = 256,
        n_att_experts = 32,
        k_att = 2,
        n_mlp_experts = 32,
        k_mlp = 2,
        layer_norm_epsilon=1e-5,
        initializer_range=0.02,
        use_cache=True,
        bos_token_id=50256,
        eos_token_id=50256,
        tie_word_embeddings=False,
        aux_loss_type = 'mi',
        aux_loss_weight=0,
        gate_type = "mlp",
        **kwargs,
    ):
        self.vocab_size = vocab_size
        self.history_length = history_length
        self.block_size = block_size
        self.n_embd = n_embd
        self.n_layer = n_layer
        self.n_head = n_head
        self.att_hidden = att_hidden
        self.ffd_hidden = ffd_hidden
        self.activation_function = activation_function
        self.resid_pdrop = resid_pdrop
        self.embd_pdrop = embd_pdrop
        self.attn_pdrop = attn_pdrop
        self.moe_pdrop = moe_pdrop
        self.layer_norm_epsilon = layer_norm_epsilon
        self.initializer_range = initializer_range
        self.use_cache = use_cache
        self.sample_topk = sample_topk
        self.gating_size = gating_size
        self.n_att_experts = n_att_experts
        self.k_att = k_att
        self.n_mlp_experts = n_mlp_experts
        self.k_mlp = k_mlp
        self.aux_loss_type = aux_loss_type
        self.aux_loss_weight = aux_loss_weight
        self.gate_type = gate_type
        self.n_ctx = history_length * n_layer

        self.bos_token_id = bos_token_id
        self.eos_token_id = eos_token_id

        super().__init__(
            bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs
        )

class ModuleFormerOnnxConfig(OnnxConfigWithPast):
    def __init__(
        self,
        config: PretrainedConfig,
        task: str = "default",
        patching_specs: List[PatchingSpec] = None,
        use_past: bool = False,
    ):
        """
        Initialize the ModuleFormerOnnxConfig.

        Args:
            config (PretrainedConfig): Pretrained model configuration.
            task (str): Task description.
            patching_specs (List[PatchingSpec]): List of patching specifications.
            use_past (bool): Whether to use past tokens in the configuration.
        """
        super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past)


ModuleFormerOnnxConfig

        self.use_cache = use_cache
        self.sample_topk = sample_topk
        self.gating_size = gating_size
        self.n_att_experts = n_att_experts
        self.k_att = k_att
        self.n_mlp_experts = n_mlp_experts
        self.k_mlp = k_mlp
        self.aux_loss_type = aux_loss_type
        self.aux_loss_weight = aux_loss_weight
        self.gate_type = gate_type
        self.n_ctx = history_length * n_layer

        self.bos_token_id = bos_token_id
        self.eos_token_id = eos_token_id

        super().__init__(
            bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs
        )

class ModuleFormerOnnxConfig(OnnxConfigWithPast):
    def __init__(
        self,
        config: PretrainedConfig,
        task: str = "default",
        patching_specs: List[PatchingSpec] = None,
        use_past: bool = False,
    ):
        """
        Initialize the ModuleFormerOnnxConfig.

        Args:
            config (PretrainedConfig): Pretrained model configuration.
            task (str): Task description.
            patching_specs (List[PatchingSpec]): List of patching specifications.
            use_past (bool): Whether to use past tokens in the configuration.
        """
        super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past)
        if not getattr(self._config, "pad_token_id", None):
            # TODO: how to do that better?
            self._config.pad_token_id = 0

    @property
    def inputs(self) -> Mapping[str, Mapping[int, str]]:
        """
        Define the input mappings.

        Returns:
            Mapping[str, Mapping[int, str]]: Input mappings.
        """
        common_inputs = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
        if self.use_past:
            self.fill_with_past_key_values_(common_inputs, direction="inputs")
            common_inputs["attention_mask"] = {0: "batch", 1: "past_sequence + sequence"}
        else:
            common_inputs["attention_mask"] = {0: "batch", 1: "sequence"}

        return common_inputs

    @property
    def num_layers(self) -> int:
        """
        Get the number of layers.

        Returns:
            int: Number of layers.
        """
        return self._config.n_layer

    @property
    def num_attention_heads(self) -> int:
        """
        Get the number of attention heads.

        Returns:
            int: Number of attention heads.
        """
        return self._config.n_head

    def generate_dummy_inputs(
        self,
        tokenizer: PreTrainedTokenizer,
        batch_size: int = -1,
        seq_length: int = -1,
        is_pair: bool = False,
        framework: Optional[TensorType] = None,
    ) -> Mapping[str, Any]:
        """
        Generate dummy inputs for testing.

        Args:
            tokenizer (PreTrainedTokenizer): Pretrained tokenizer.
            batch_size (int): Batch size.
            seq_length (int): Sequence length.
            is_pair (bool): Whether the input is a pair.
            framework (Optional[TensorType]): Tensor framework.

        Returns:
            Mapping[str, Any]: Dummy inputs.
        """
        common_inputs = super(OnnxConfigWithPast, self).generate_dummy_inputs(
            tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
        )

        # We need to order the input in the way they appears in the forward()
        ordered_inputs = OrderedDict({"input_ids": common_inputs["input_ids"]})

        # Need to add the past_keys
        if self.use_past:
            if not is_torch_available():
                raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
            else:
                import torch

                batch, seqlen = common_inputs["input_ids"].shape
                # Not using the same length for past_key_values
                past_key_values_length = seqlen + 2
                past_shape = (
                    batch,
                    self.num_attention_heads,
                    past_key_values_length,
                    self._config.hidden_size // self.num_attention_heads,
                )
                ordered_inputs["past_key_values"] = [
                    (torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(self.num_layers)
                ]

        ordered_inputs["attention_mask"] = common_inputs["attention_mask"]
        if self.use_past:
            mask_dtype = ordered_inputs["attention_mask"].dtype
            ordered_inputs["attention_mask"] = torch.cat(
                [ordered_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
            )

        return ordered_inputs

    @property
    def default_onnx_opset(self) -> int:
        """
        Get the default ONNX opset version.

        Returns:
            int: Default ONNX opset version.
        """
        return 13


        self.sample_topk = sample_topk
        self.gating_size = gating_size
        self.n_att_experts = n_att_experts
        self.k_att = k_att
        self.n_mlp_experts = n_mlp_experts
        self.k_mlp = k_mlp
        self.aux_loss_type = aux_loss_type
        self.aux_loss_weight = aux_loss_weight
        self.gate_type = gate_type
        self.n_ctx = history_length * n_layer

        self.bos_token_id = bos_token_id
        self.eos_token_id = eos_token_id

        super().__init__(
            bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs
        )

class ModuleFormerOnnxConfig(OnnxConfigWithPast):
    def __init__(
        self,
        config: PretrainedConfig,
        task: str = "default",
        patching_specs: List[PatchingSpec] = None,
        use_past: bool = False,
    ):
        """
        Initialize the ModuleFormerOnnxConfig.

        Args:
            config (PretrainedConfig): Pretrained model configuration.
            task (str): Task description.
            patching_specs (List[PatchingSpec]): List of patching specifications.
            use_past (bool): Whether to use past tokens in the configuration.
        """
        super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past)
        if not getattr(self._config, "pad_token_id", None):
            # TODO: how to do that better?
            self._config.pad_token_id = 0

    @property
    def inputs(self) -> Mapping[str, Mapping[int, str]]:
        """
        Define the input mappings.

        Returns:
            Mapping[str, Mapping[int, str]]: Input mappings.
        """
        common_inputs = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
        if self.use_past:
            self.fill_with_past_key_values_(common_inputs, direction="inputs")
            common_inputs["attention_mask"] = {0: "batch", 1: "past_sequence + sequence"}
        else:
            common_inputs["attention_mask"] = {0: "batch", 1: "sequence"}

        return common_inputs

    @property
    def num_layers(self) -> int:


inputs

        config: PretrainedConfig,
        task: str = "default",
        patching_specs: List[PatchingSpec] = None,
        use_past: bool = False,
    ):
        """
        Initialize the ModuleFormerOnnxConfig.

        Args:
            config (PretrainedConfig): Pretrained model configuration.
            task (str): Task description.
            patching_specs (List[PatchingSpec]): List of patching specifications.
            use_past (bool): Whether to use past tokens in the configuration.
        """
        super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past)
        if not getattr(self._config, "pad_token_id", None):
            # TODO: how to do that better?
            self._config.pad_token_id = 0

    @property
    def inputs(self) -> Mapping[str, Mapping[int, str]]:
        """
        Define the input mappings.

        Returns:
            Mapping[str, Mapping[int, str]]: Input mappings.
        """
        common_inputs = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
        if self.use_past:
            self.fill_with_past_key_values_(common_inputs, direction="inputs")
            common_inputs["attention_mask"] = {0: "batch", 1: "past_sequence + sequence"}
        else:
            common_inputs["attention_mask"] = {0: "batch", 1: "sequence"}

        return common_inputs

    @property
    def num_layers(self) -> int:
        """
        Get the number of layers.

        Returns:
            int: Number of layers.
        """
        return self._config.n_layer

    @property
    def num_attention_heads(self) -> int:
        """
        Get the number of attention heads.

        Returns:
            int: Number of attention heads.
        """
        return self._config.n_head


            self._config.pad_token_id = 0

    @property
    def inputs(self) -> Mapping[str, Mapping[int, str]]:
        """
        Define the input mappings.

        Returns:
            Mapping[str, Mapping[int, str]]: Input mappings.
        """
        common_inputs = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
        if self.use_past:
            self.fill_with_past_key_values_(common_inputs, direction="inputs")
            common_inputs["attention_mask"] = {0: "batch", 1: "past_sequence + sequence"}
        else:
            common_inputs["attention_mask"] = {0: "batch", 1: "sequence"}

        return common_inputs

    @property
    def num_layers(self) -> int:
        """
        Get the number of layers.

        Returns:
            int: Number of layers.
        """
        return self._config.n_layer

    @property
    def num_attention_heads(self) -> int:
        """
        Get the number of attention heads.

        Returns:
            int: Number of attention heads.
        """
        return self._config.n_head

    def generate_dummy_inputs(
        self,
        tokenizer: PreTrainedTokenizer,
        batch_size: int = -1,
        seq_length: int = -1,
        is_pair: bool = False,
        framework: Optional[TensorType] = None,
    ) -> Mapping[str, Any]:
        """


        common_inputs = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
        if self.use_past:
            self.fill_with_past_key_values_(common_inputs, direction="inputs")
            common_inputs["attention_mask"] = {0: "batch", 1: "past_sequence + sequence"}
        else:
            common_inputs["attention_mask"] = {0: "batch", 1: "sequence"}

        return common_inputs

    @property
    def num_layers(self) -> int:
        """
        Get the number of layers.

        Returns:
            int: Number of layers.
        """
        return self._config.n_layer

    @property
    def num_attention_heads(self) -> int:
        """
        Get the number of attention heads.

        Returns:
            int: Number of attention heads.
        """
        return self._config.n_head

    def generate_dummy_inputs(
        self,
        tokenizer: PreTrainedTokenizer,
        batch_size: int = -1,
        seq_length: int = -1,
        is_pair: bool = False,
        framework: Optional[TensorType] = None,
    ) -> Mapping[str, Any]:
        """
        Generate dummy inputs for testing.

        Args:
            tokenizer (PreTrainedTokenizer): Pretrained tokenizer.
            batch_size (int): Batch size.
            seq_length (int): Sequence length.
            is_pair (bool): Whether the input is a pair.
            framework (Optional[TensorType]): Tensor framework.

        Returns:


    @property
    def num_layers(self) -> int:
        """
        Get the number of layers.

        Returns:
            int: Number of layers.
        """
        return self._config.n_layer

    @property
    def num_attention_heads(self) -> int:
        """
        Get the number of attention heads.

        Returns:
            int: Number of attention heads.
        """
        return self._config.n_head

    def generate_dummy_inputs(
        self,
        tokenizer: PreTrainedTokenizer,
        batch_size: int = -1,
        seq_length: int = -1,
        is_pair: bool = False,
        framework: Optional[TensorType] = None,
    ) -> Mapping[str, Any]:
        """
        Generate dummy inputs for testing.

        Args:
            tokenizer (PreTrainedTokenizer): Pretrained tokenizer.
            batch_size (int): Batch size.
            seq_length (int): Sequence length.
            is_pair (bool): Whether the input is a pair.
            framework (Optional[TensorType]): Tensor framework.

        Returns:
            Mapping[str, Any]: Dummy inputs.
        """
        common_inputs = super(OnnxConfigWithPast, self).generate_dummy_inputs(
            tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
        )

        # We need to order the input in the way they appears in the forward()
        ordered_inputs = OrderedDict({"input_ids": common_inputs["input_ids"]})

        # Need to add the past_keys
        if self.use_past:
            if not is_torch_available():
                raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
            else:
                import torch

                batch, seqlen = common_inputs["input_ids"].shape
                # Not using the same length for past_key_values
                past_key_values_length = seqlen + 2
                past_shape = (
                    batch,
                    self.num_attention_heads,
                    past_key_values_length,
                    self._config.hidden_size // self.num_attention_heads,
                )
                ordered_inputs["past_key_values"] = [
                    (torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(self.num_layers)
                ]

        ordered_inputs["attention_mask"] = common_inputs["attention_mask"]
        if self.use_past:
            mask_dtype = ordered_inputs["attention_mask"].dtype
            ordered_inputs["attention_mask"] = torch.cat(
                [ordered_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
            )

        return ordered_inputs

    @property
    def default_onnx_opset(self) -> int:
        """
        Get the default ONNX opset version.

        Returns:
            int: Default ONNX opset version.
        """
        return 13


                past_shape = (
                    batch,
                    self.num_attention_heads,
                    past_key_values_length,
                    self._config.hidden_size // self.num_attention_heads,
                )
                ordered_inputs["past_key_values"] = [
                    (torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(self.num_layers)
                ]

        ordered_inputs["attention_mask"] = common_inputs["attention_mask"]
        if self.use_past:
            mask_dtype = ordered_inputs["attention_mask"].dtype
            ordered_inputs["attention_mask"] = torch.cat(
                [ordered_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
            )

        return ordered_inputs

    @property
    def default_onnx_opset(self) -> int:
        """
        Get the default ONNX opset version.

        Returns:
            int: Default ONNX opset version.
        """
        return 13


moduleformer.utils.gate

import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Any, Dict, List, Optional

# @torch.jit.script
def log_gmm_posterior(z, expert_centroids):
     """
    Compute the log posterior probabilities of data points z belonging to Gaussian mixture components defined by centroids.

    Args:
        z (torch.Tensor): Data points (batch_size x feature_dim).
        expert_centroids (torch.Tensor): Centroids of Gaussian mixture components (num_experts x feature_dim).

    Returns:
        torch.Tensor: Log posterior probabilities for each data point (batch_size x num_experts).
    """
     return (
        torch.matmul(z, expert_centroids.t())
        # - 0.5 * (
        #     torch.einsum('ni,ni->n', z, z)[:, None] +
        #     torch.einsum('ni,ni->n', expert_centroids, expert_centroids)[None, :]
        # )
     )

@torch.jit.script
def compute_gating(k: int, probs: torch.Tensor, top_k_gates: torch.Tensor, top_k_indices: torch.Tensor):
    """
    Compute gating values for the mixture of experts based on probabilities and top-k indices.

    Args:
        k (int): Number of experts to select.
        probs (torch.Tensor): Probability values for each expert (batch_size x num_experts).
        top_k_gates (torch.Tensor): Gating values for top-k experts (batch_size x k).
        top_k_indices (torch.Tensor): Indices of top-k experts (batch_size x k).

    Returns:
        torch.Tensor: Batch-level gating values.
        torch.Tensor: Batch-level expert indices.
        torch.Tensor: Expert size for each expert.
        torch.Tensor: Sorted indices of top-k experts.
    """
    zeros = torch.zeros_like(probs)
    gates = zeros.scatter(1, top_k_indices, 1)
    expert_size = gates.long().sum(0)
    top_k_gates = top_k_gates.flatten()
    top_k_experts = top_k_indices.flatten()
    _, index_sorted_experts = top_k_experts.sort(0)
    batch_index = index_sorted_experts.div(k, rounding_mode='trunc')
    batch_gates = top_k_gates[index_sorted_experts]
    return batch_gates, batch_index, expert_size, index_sorted_experts

class top_k_gating(nn.Module):
    def __init__(
        self,
        input_size,
        num_experts,
        top_k,
        acc_aux_loss=False,
        dropout=0.1,
        hidden_size=256,
        sample_topk=0,
        aux_loss='mi',
        gate_type='mlp',
    ):
        """
        Initialize the top-k gating mechanism.

        Args:
            input_size (int): Size of the input.
            num_experts (int): Number of experts.
            top_k (int): Number of top experts to select.
            acc_aux_loss (bool): Whether to accumulate auxiliary loss statistics.
            dropout (float): Dropout rate for gating network.
            hidden_size (int): Hidden size of the gating network.
            sample_topk (int): Number of top-k experts to sample during training.
            aux_loss (str): Type of auxiliary loss ('mi' or 'switch').
            gate_type (str): Type of gating mechanism ('mlp', 'linear', or 'gmm').
        """
        super().__init__()

        self.num_experts = num_experts
        self.input_size = input_size
        assert top_k <= num_experts
        self.top_k = top_k
        assert sample_topk <= top_k
        self.sample_topk = sample_topk

        self.acc_aux_loss = acc_aux_loss
        self.aux_loss = aux_loss
        self.init_aux_statistics()

        self.gate_type = gate_type
        if gate_type == 'mlp':
            self.w_gate = nn.Sequential(
                nn.Linear(input_size, hidden_size),
                nn.GELU(),
                nn.Dropout(dropout),
                nn.Linear(hidden_size, num_experts, bias=False)
            )
        elif gate_type == 'linear':
            self.w_gate = nn.Sequential(
                nn.Linear(input_size, num_experts, bias=False)
            )
        elif gate_type == 'gmm':
            self.w_gate = nn.Linear(input_size, hidden_size, bias=False)
            self.expert_centroids = nn.Parameter(torch.empty(num_experts, hidden_size))
            nn.init.normal_(self.expert_centroids)
            self.temperature = nn.Parameter(torch.zeros(1))
        else:
            print(gate_type)
            raise NotImplementedError

    def extra_repr(self):
        """
        Return extra representation string for the module.
        """
        return 'k={}, num_experts={}, aux_loss={}'.format(
            self.top_k, self.num_experts, self.aux_loss)

    def init_aux_statistics(self):
        """
        Initialize auxiliary statistics based on the chosen auxiliary loss type.
        """
        if self.aux_loss == 'mi':
            self.p_e = 0.
            self.neg_H_e_given_x = 0.
            self.count_layers = 0
        else:
            self.acc_probs = 0.
            self.acc_freq = 0.
            self.acc_lsesq = 0.
            self.acc_count = 0

    def update_aux_statistics(self, probs, logits, gates, skip_mask=None):
        """
        Update auxiliary statistics based on the current batch.

        Args:
            probs (torch.Tensor): Probability values for each expert.
            logits (torch.Tensor): Logits values for each expert.
            gates (torch.Tensor): Gating values for each expert.
            skip_mask (torch.Tensor): Skip mask tensor.

        """
        if self.aux_loss == 'mi':
            log_prob = torch.log_softmax(logits, dim=-1)
            self.p_e = self.p_e + probs.mean(0)
            self.neg_H_e_given_x = self.neg_H_e_given_x + (probs * log_prob).sum() / probs.size(0)
            self.count_layers += 1
        else:
            self.acc_count = self.acc_count + logits.size(0)
            self.acc_probs = self.acc_probs + probs.sum(0)
            self.acc_freq = self.acc_freq + (gates > 0).float().sum(0)
            lsesq = torch.log(torch.exp(logits).sum(dim=-1)) ** 2
            self.acc_lsesq = self.acc_lsesq + lsesq.sum()

    def get_aux_loss_and_clear(self, eps=1e-8):
        """
        Calculate and return the auxiliary loss based on the accumulated statistics.

        Args:
            eps (float): Small epsilon value for numerical stability.

        Returns:
            torch.Tensor: The calculated auxiliary loss.
        """
        if self.aux_loss == 'mi':
            denominator = self.count_layers
            p_e = self.p_e / denominator
            H_e = -(p_e * (p_e + eps).log()).sum()
            neg_H_e_given_x = self.neg_H_e_given_x / denominator
            miloss = -(neg_H_e_given_x + H_e)
            loss = miloss
        else:
            switchloss =  self.num_experts * (
                F.normalize(self.acc_probs, p=1, dim=0) *
                F.normalize(self.acc_freq, p=1, dim=0)
            ).sum()
            zloss = self.acc_lsesq / self.acc_count
            loss = switchloss + 0.1 * zloss

        self.init_aux_statistics()
        return loss

    def forward(self, x, skip_mask=None):
        """
        Compute the top-k gating for the input.

        See paper: https://arxiv.org/abs/1701.06538.

        Args:
            x (torch.Tensor): Input tensor with shape [batch_size, input_size].
            skip_mask (torch.Tensor): Skip mask tensor (binary) with the same shape as `x`.
            x: input Tensor with shape [batch_size, input_size]
            train: a boolean - we only add noise at training time.
            noise_epsilon: a float

        Returns:
            torch.Tensor: Top-k indices.
            torch.Tensor: Top-k gating values.
            torch.Tensor: Probability values for each expert.
            gates: a Tensor with shape [batch_size, num_experts]
            load: a Tensor with shape [num_experts]
        """

        if self.gate_type in ['linear', 'mlp']:
            logits = self.w_gate(x)
        elif self.gate_type == 'gmm':
            z = self.w_gate(x)
            logits = log_gmm_posterior(F.normalize(z, p=2, dim=-1), F.normalize(self.expert_centroids, p=2, dim=-1)) * self.temperature.exp()

        probs = torch.softmax(logits, dim=1)
        if skip_mask is not None:
            probs = torch.masked_fill(probs, (skip_mask == 0), 0)
            logits = torch.masked_fill(logits, (skip_mask == 0), 0)

        if self.training and (self.sample_topk > 0):
            _, top_km1_indices = probs.topk(self.top_k - self.sample_topk, dim=1)
            masked_probs = probs + 1e-6
            masked_probs[torch.arange(probs.size(0)).unsqueeze(
                1), top_km1_indices] = 0
            k_indices = torch.multinomial(masked_probs, self.sample_topk)
            top_k_indices = torch.cat([top_km1_indices, k_indices], dim=-1)
            top_k_gates = torch.gather(probs, 1, top_k_indices)
        else:
            top_k_gates, top_k_indices = probs.topk(self.top_k, dim=1)

        # if self.top_k > 1:
        #     top_k_gates = top_k_gates / (top_k_gates.sum(dim=1, keepdim=True) + 1e-6)

        # gate = torch.zeros_like(top_k_gates)
        # gate[:, 0] = 1
        # top_k_gates = (gate - top_k_gates).detach() + top_k_gates

        zeros = torch.zeros_like(probs)
        gates = zeros.scatter(1, top_k_indices, top_k_gates)
        self.update_aux_statistics(probs, logits, gates, skip_mask)
        if not self.acc_aux_loss:
            self.loss = self.get_aux_loss_and_clear()
        else:
            self.loss = 0

        return top_k_indices, top_k_gates, probs

        # batch_gates, batch_index, expert_size, gates, index_sorted_experts = \
        #     compute_gating(self.top_k, probs, top_k_gates, top_k_indices)

        # return batch_gates, batch_index, expert_size.tolist(), gates, index_sorted_experts


import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Any, Dict, List, Optional

# @torch.jit.script
def log_gmm_posterior(z, expert_centroids):
     """
    Compute the log posterior probabilities of data points z belonging to Gaussian mixture components defined by centroids.

    Args:
        z (torch.Tensor): Data points (batch_size x feature_dim).
        expert_centroids (torch.Tensor): Centroids of Gaussian mixture components (num_experts x feature_dim).

    Returns:
        torch.Tensor: Log posterior probabilities for each data point (batch_size x num_experts).
    """
     return (
        torch.matmul(z, expert_centroids.t())
        # - 0.5 * (
        #     torch.einsum('ni,ni->n', z, z)[:, None] +
        #     torch.einsum('ni,ni->n', expert_centroids, expert_centroids)[None, :]
        # )
     )

@torch.jit.script
def compute_gating(k: int, probs: torch.Tensor, top_k_gates: torch.Tensor, top_k_indices: torch.Tensor):
    """
    Compute gating values for the mixture of experts based on probabilities and top-k indices.

    Args:
        k (int): Number of experts to select.
        probs (torch.Tensor): Probability values for each expert (batch_size x num_experts).
        top_k_gates (torch.Tensor): Gating values for top-k experts (batch_size x k).
        top_k_indices (torch.Tensor): Indices of top-k experts (batch_size x k).

    Returns:
        torch.Tensor: Batch-level gating values.
        torch.Tensor: Batch-level expert indices.
        torch.Tensor: Expert size for each expert.
        torch.Tensor: Sorted indices of top-k experts.
    """
    zeros = torch.zeros_like(probs)


     """
    Compute the log posterior probabilities of data points z belonging to Gaussian mixture components defined by centroids.

    Args:
        z (torch.Tensor): Data points (batch_size x feature_dim).
        expert_centroids (torch.Tensor): Centroids of Gaussian mixture components (num_experts x feature_dim).

    Returns:
        torch.Tensor: Log posterior probabilities for each data point (batch_size x num_experts).
    """
     return (
        torch.matmul(z, expert_centroids.t())
        # - 0.5 * (
        #     torch.einsum('ni,ni->n', z, z)[:, None] +
        #     torch.einsum('ni,ni->n', expert_centroids, expert_centroids)[None, :]
        # )
     )

@torch.jit.script
def compute_gating(k: int, probs: torch.Tensor, top_k_gates: torch.Tensor, top_k_indices: torch.Tensor):
    """
    Compute gating values for the mixture of experts based on probabilities and top-k indices.

    Args:
        k (int): Number of experts to select.
        probs (torch.Tensor): Probability values for each expert (batch_size x num_experts).
        top_k_gates (torch.Tensor): Gating values for top-k experts (batch_size x k).
        top_k_indices (torch.Tensor): Indices of top-k experts (batch_size x k).

    Returns:
        torch.Tensor: Batch-level gating values.
        torch.Tensor: Batch-level expert indices.
        torch.Tensor: Expert size for each expert.
        torch.Tensor: Sorted indices of top-k experts.
    """
    zeros = torch.zeros_like(probs)
    gates = zeros.scatter(1, top_k_indices, 1)
    expert_size = gates.long().sum(0)
    top_k_gates = top_k_gates.flatten()
    top_k_experts = top_k_indices.flatten()
    _, index_sorted_experts = top_k_experts.sort(0)
    batch_index = index_sorted_experts.div(k, rounding_mode='trunc')
    batch_gates = top_k_gates[index_sorted_experts]
    return batch_gates, batch_index, expert_size, index_sorted_experts

class top_k_gating(nn.Module):
    def __init__(
        self,
        input_size,
        num_experts,
        top_k,
        acc_aux_loss=False,
        dropout=0.1,
        hidden_size=256,
        sample_topk=0,
        aux_loss='mi',
        gate_type='mlp',
    ):
        """
        Initialize the top-k gating mechanism.

        Args:
            input_size (int): Size of the input.


        top_k_gates (torch.Tensor): Gating values for top-k experts (batch_size x k).
        top_k_indices (torch.Tensor): Indices of top-k experts (batch_size x k).

    Returns:
        torch.Tensor: Batch-level gating values.
        torch.Tensor: Batch-level expert indices.
        torch.Tensor: Expert size for each expert.
        torch.Tensor: Sorted indices of top-k experts.
    """
    zeros = torch.zeros_like(probs)
    gates = zeros.scatter(1, top_k_indices, 1)
    expert_size = gates.long().sum(0)
    top_k_gates = top_k_gates.flatten()
    top_k_experts = top_k_indices.flatten()
    _, index_sorted_experts = top_k_experts.sort(0)
    batch_index = index_sorted_experts.div(k, rounding_mode='trunc')
    batch_gates = top_k_gates[index_sorted_experts]
    return batch_gates, batch_index, expert_size, index_sorted_experts

class top_k_gating(nn.Module):
    def __init__(
        self,
        input_size,
        num_experts,
        top_k,
        acc_aux_loss=False,
        dropout=0.1,
        hidden_size=256,
        sample_topk=0,
        aux_loss='mi',
        gate_type='mlp',
    ):
        """
        Initialize the top-k gating mechanism.

        Args:
            input_size (int): Size of the input.
            num_experts (int): Number of experts.
            top_k (int): Number of top experts to select.
            acc_aux_loss (bool): Whether to accumulate auxiliary loss statistics.
            dropout (float): Dropout rate for gating network.
            hidden_size (int): Hidden size of the gating network.
            sample_topk (int): Number of top-k experts to sample during training.
            aux_loss (str): Type of auxiliary loss ('mi' or 'switch').
            gate_type (str): Type of gating mechanism ('mlp', 'linear', or 'gmm').
        """
        super().__init__()

        self.num_experts = num_experts
        self.input_size = input_size
        assert top_k <= num_experts
        self.top_k = top_k
        assert sample_topk <= top_k
        self.sample_topk = sample_topk

        self.acc_aux_loss = acc_aux_loss
        self.aux_loss = aux_loss
        self.init_aux_statistics()

        self.gate_type = gate_type
        if gate_type == 'mlp':
            self.w_gate = nn.Sequential(
                nn.Linear(input_size, hidden_size),
                nn.GELU(),
                nn.Dropout(dropout),
                nn.Linear(hidden_size, num_experts, bias=False)
            )
        elif gate_type == 'linear':
            self.w_gate = nn.Sequential(
                nn.Linear(input_size, num_experts, bias=False)
            )
        elif gate_type == 'gmm':
            self.w_gate = nn.Linear(input_size, hidden_size, bias=False)
            self.expert_centroids = nn.Parameter(torch.empty(num_experts, hidden_size))
            nn.init.normal_(self.expert_centroids)
            self.temperature = nn.Parameter(torch.zeros(1))
        else:
            print(gate_type)
            raise NotImplementedError

    def extra_repr(self):
        """
        Return extra representation string for the module.
        """
        return 'k={}, num_experts={}, aux_loss={}'.format(
            self.top_k, self.num_experts, self.aux_loss)

    def init_aux_statistics(self):
        """
        Initialize auxiliary statistics based on the chosen auxiliary loss type.
        """
        if self.aux_loss == 'mi':
            self.p_e = 0.
            self.neg_H_e_given_x = 0.
            self.count_layers = 0
        else:
            self.acc_probs = 0.
            self.acc_freq = 0.
            self.acc_lsesq = 0.
            self.acc_count = 0

    def update_aux_statistics(self, probs, logits, gates, skip_mask=None):
        """
        Update auxiliary statistics based on the current batch.

        Args:
            probs (torch.Tensor): Probability values for each expert.
            logits (torch.Tensor): Logits values for each expert.
            gates (torch.Tensor): Gating values for each expert.
            skip_mask (torch.Tensor): Skip mask tensor.

        """
        if self.aux_loss == 'mi':
            log_prob = torch.log_softmax(logits, dim=-1)
            self.p_e = self.p_e + probs.mean(0)
            self.neg_H_e_given_x = self.neg_H_e_given_x + (probs * log_prob).sum() / probs.size(0)
            self.count_layers += 1
        else:
            self.acc_count = self.acc_count + logits.size(0)
            self.acc_probs = self.acc_probs + probs.sum(0)
            self.acc_freq = self.acc_freq + (gates > 0).float().sum(0)
            lsesq = torch.log(torch.exp(logits).sum(dim=-1)) ** 2
            self.acc_lsesq = self.acc_lsesq + lsesq.sum()

    def get_aux_loss_and_clear(self, eps=1e-8):
        """
        Calculate and return the auxiliary loss based on the accumulated statistics.

        Args:
            eps (float): Small epsilon value for numerical stability.

        Returns:
            torch.Tensor: The calculated auxiliary loss.
        """
        if self.aux_loss == 'mi':
            denominator = self.count_layers
            p_e = self.p_e / denominator
            H_e = -(p_e * (p_e + eps).log()).sum()
            neg_H_e_given_x = self.neg_H_e_given_x / denominator
            miloss = -(neg_H_e_given_x + H_e)
            loss = miloss
        else:
            switchloss =  self.num_experts * (
                F.normalize(self.acc_probs, p=1, dim=0) *
                F.normalize(self.acc_freq, p=1, dim=0)
            ).sum()
            zloss = self.acc_lsesq / self.acc_count
            loss = switchloss + 0.1 * zloss

        self.init_aux_statistics()
        return loss

    def forward(self, x, skip_mask=None):
        """
        Compute the top-k gating for the input.

        See paper: https://arxiv.org/abs/1701.06538.

        Args:
            x (torch.Tensor): Input tensor with shape [batch_size, input_size].
            skip_mask (torch.Tensor): Skip mask tensor (binary) with the same shape as `x`.
            x: input Tensor with shape [batch_size, input_size]
            train: a boolean - we only add noise at training time.
            noise_epsilon: a float

        Returns:
            torch.Tensor: Top-k indices.
            torch.Tensor: Top-k gating values.
            torch.Tensor: Probability values for each expert.
            gates: a Tensor with shape [batch_size, num_experts]
            load: a Tensor with shape [num_experts]
        """

        if self.gate_type in ['linear', 'mlp']:
            logits = self.w_gate(x)
        elif self.gate_type == 'gmm':
            z = self.w_gate(x)
            logits = log_gmm_posterior(F.normalize(z, p=2, dim=-1), F.normalize(self.expert_centroids, p=2, dim=-1)) * self.temperature.exp()

        probs = torch.softmax(logits, dim=1)
        if skip_mask is not None:
            probs = torch.masked_fill(probs, (skip_mask == 0), 0)
            logits = torch.masked_fill(logits, (skip_mask == 0), 0)

        if self.training and (self.sample_topk > 0):
            _, top_km1_indices = probs.topk(self.top_k - self.sample_topk, dim=1)
            masked_probs = probs + 1e-6
            masked_probs[torch.arange(probs.size(0)).unsqueeze(
                1), top_km1_indices] = 0
            k_indices = torch.multinomial(masked_probs, self.sample_topk)
            top_k_indices = torch.cat([top_km1_indices, k_indices], dim=-1)
            top_k_gates = torch.gather(probs, 1, top_k_indices)
        else:
            top_k_gates, top_k_indices = probs.topk(self.top_k, dim=1)

        # if self.top_k > 1:
        #     top_k_gates = top_k_gates / (top_k_gates.sum(dim=1, keepdim=True) + 1e-6)

        # gate = torch.zeros_like(top_k_gates)
        # gate[:, 0] = 1
        # top_k_gates = (gate - top_k_gates).detach() + top_k_gates

        zeros = torch.zeros_like(probs)
        gates = zeros.scatter(1, top_k_indices, top_k_gates)
        self.update_aux_statistics(probs, logits, gates, skip_mask)
        if not self.acc_aux_loss:
            self.loss = self.get_aux_loss_and_clear()
        else:
            self.loss = 0

        return top_k_indices, top_k_gates, probs

        # batch_gates, batch_index, expert_size, gates, index_sorted_experts = \
        #     compute_gating(self.top_k, probs, top_k_gates, top_k_indices)

        # return batch_gates, batch_index, expert_size.tolist(), gates, index_sorted_experts


        top_k_indices (torch.Tensor): Indices of top-k experts (batch_size x k).

    Returns:
        torch.Tensor: Batch-level gating values.
        torch.Tensor: Batch-level expert indices.
        torch.Tensor: Expert size for each expert.
        torch.Tensor: Sorted indices of top-k experts.
    """
    zeros = torch.zeros_like(probs)
    gates = zeros.scatter(1, top_k_indices, 1)
    expert_size = gates.long().sum(0)
    top_k_gates = top_k_gates.flatten()
    top_k_experts = top_k_indices.flatten()
    _, index_sorted_experts = top_k_experts.sort(0)
    batch_index = index_sorted_experts.div(k, rounding_mode='trunc')
    batch_gates = top_k_gates[index_sorted_experts]
    return batch_gates, batch_index, expert_size, index_sorted_experts

class top_k_gating(nn.Module):
    def __init__(
        self,
        input_size,
        num_experts,
        top_k,
        acc_aux_loss=False,
        dropout=0.1,
        hidden_size=256,
        sample_topk=0,
        aux_loss='mi',
        gate_type='mlp',
    ):
        """
        Initialize the top-k gating mechanism.

        Args:
            input_size (int): Size of the input.
            num_experts (int): Number of experts.
            top_k (int): Number of top experts to select.
            acc_aux_loss (bool): Whether to accumulate auxiliary loss statistics.
            dropout (float): Dropout rate for gating network.
            hidden_size (int): Hidden size of the gating network.
            sample_topk (int): Number of top-k experts to sample during training.
            aux_loss (str): Type of auxiliary loss ('mi' or 'switch').
            gate_type (str): Type of gating mechanism ('mlp', 'linear', or 'gmm').
        """
        super().__init__()

        self.num_experts = num_experts
        self.input_size = input_size
        assert top_k <= num_experts
        self.top_k = top_k
        assert sample_topk <= top_k
        self.sample_topk = sample_topk

        self.acc_aux_loss = acc_aux_loss
        self.aux_loss = aux_loss
        self.init_aux_statistics()

        self.gate_type = gate_type
        if gate_type == 'mlp':
            self.w_gate = nn.Sequential(
                nn.Linear(input_size, hidden_size),
                nn.GELU(),
                nn.Dropout(dropout),
                nn.Linear(hidden_size, num_experts, bias=False)
            )
        elif gate_type == 'linear':
            self.w_gate = nn.Sequential(
                nn.Linear(input_size, num_experts, bias=False)
            )
        elif gate_type == 'gmm':
            self.w_gate = nn.Linear(input_size, hidden_size, bias=False)
            self.expert_centroids = nn.Parameter(torch.empty(num_experts, hidden_size))
            nn.init.normal_(self.expert_centroids)
            self.temperature = nn.Parameter(torch.zeros(1))
        else:
            print(gate_type)
            raise NotImplementedError

    def extra_repr(self):
        """
        Return extra representation string for the module.
        """
        return 'k={}, num_experts={}, aux_loss={}'.format(
            self.top_k, self.num_experts, self.aux_loss)

    def init_aux_statistics(self):
        """
        Initialize auxiliary statistics based on the chosen auxiliary loss type.
        """
        if self.aux_loss == 'mi':
            self.p_e = 0.
            self.neg_H_e_given_x = 0.
            self.count_layers = 0
        else:
            self.acc_probs = 0.
            self.acc_freq = 0.
            self.acc_lsesq = 0.


        if gate_type == 'mlp':
            self.w_gate = nn.Sequential(
                nn.Linear(input_size, hidden_size),
                nn.GELU(),
                nn.Dropout(dropout),
                nn.Linear(hidden_size, num_experts, bias=False)
            )
        elif gate_type == 'linear':
            self.w_gate = nn.Sequential(
                nn.Linear(input_size, num_experts, bias=False)
            )
        elif gate_type == 'gmm':
            self.w_gate = nn.Linear(input_size, hidden_size, bias=False)
            self.expert_centroids = nn.Parameter(torch.empty(num_experts, hidden_size))
            nn.init.normal_(self.expert_centroids)
            self.temperature = nn.Parameter(torch.zeros(1))
        else:
            print(gate_type)
            raise NotImplementedError

    def extra_repr(self):
        """
        Return extra representation string for the module.
        """
        return 'k={}, num_experts={}, aux_loss={}'.format(
            self.top_k, self.num_experts, self.aux_loss)

    def init_aux_statistics(self):
        """
        Initialize auxiliary statistics based on the chosen auxiliary loss type.
        """
        if self.aux_loss == 'mi':
            self.p_e = 0.
            self.neg_H_e_given_x = 0.
            self.count_layers = 0
        else:
            self.acc_probs = 0.
            self.acc_freq = 0.
            self.acc_lsesq = 0.
            self.acc_count = 0

    def update_aux_statistics(self, probs, logits, gates, skip_mask=None):
        """
        Update auxiliary statistics based on the current batch.

        Args:


        elif gate_type == 'linear':
            self.w_gate = nn.Sequential(
                nn.Linear(input_size, num_experts, bias=False)
            )
        elif gate_type == 'gmm':
            self.w_gate = nn.Linear(input_size, hidden_size, bias=False)
            self.expert_centroids = nn.Parameter(torch.empty(num_experts, hidden_size))
            nn.init.normal_(self.expert_centroids)
            self.temperature = nn.Parameter(torch.zeros(1))
        else:
            print(gate_type)
            raise NotImplementedError

    def extra_repr(self):
        """
        Return extra representation string for the module.
        """
        return 'k={}, num_experts={}, aux_loss={}'.format(
            self.top_k, self.num_experts, self.aux_loss)

    def init_aux_statistics(self):
        """
        Initialize auxiliary statistics based on the chosen auxiliary loss type.
        """
        if self.aux_loss == 'mi':
            self.p_e = 0.
            self.neg_H_e_given_x = 0.
            self.count_layers = 0
        else:
            self.acc_probs = 0.
            self.acc_freq = 0.
            self.acc_lsesq = 0.
            self.acc_count = 0

    def update_aux_statistics(self, probs, logits, gates, skip_mask=None):
        """
        Update auxiliary statistics based on the current batch.

        Args:
            probs (torch.Tensor): Probability values for each expert.
            logits (torch.Tensor): Logits values for each expert.
            gates (torch.Tensor): Gating values for each expert.
            skip_mask (torch.Tensor): Skip mask tensor.

        """
        if self.aux_loss == 'mi':
            log_prob = torch.log_softmax(logits, dim=-1)
            self.p_e = self.p_e + probs.mean(0)
            self.neg_H_e_given_x = self.neg_H_e_given_x + (probs * log_prob).sum() / probs.size(0)
            self.count_layers += 1
        else:
            self.acc_count = self.acc_count + logits.size(0)
            self.acc_probs = self.acc_probs + probs.sum(0)


        """
        Return extra representation string for the module.
        """
        return 'k={}, num_experts={}, aux_loss={}'.format(
            self.top_k, self.num_experts, self.aux_loss)

    def init_aux_statistics(self):
        """
        Initialize auxiliary statistics based on the chosen auxiliary loss type.
        """
        if self.aux_loss == 'mi':
            self.p_e = 0.
            self.neg_H_e_given_x = 0.
            self.count_layers = 0
        else:
            self.acc_probs = 0.
            self.acc_freq = 0.
            self.acc_lsesq = 0.
            self.acc_count = 0

    def update_aux_statistics(self, probs, logits, gates, skip_mask=None):
        """
        Update auxiliary statistics based on the current batch.

        Args:
            probs (torch.Tensor): Probability values for each expert.
            logits (torch.Tensor): Logits values for each expert.
            gates (torch.Tensor): Gating values for each expert.
            skip_mask (torch.Tensor): Skip mask tensor.

        """
        if self.aux_loss == 'mi':
            log_prob = torch.log_softmax(logits, dim=-1)
            self.p_e = self.p_e + probs.mean(0)
            self.neg_H_e_given_x = self.neg_H_e_given_x + (probs * log_prob).sum() / probs.size(0)
            self.count_layers += 1
        else:
            self.acc_count = self.acc_count + logits.size(0)
            self.acc_probs = self.acc_probs + probs.sum(0)
            self.acc_freq = self.acc_freq + (gates > 0).float().sum(0)
            lsesq = torch.log(torch.exp(logits).sum(dim=-1)) ** 2
            self.acc_lsesq = self.acc_lsesq + lsesq.sum()

    def get_aux_loss_and_clear(self, eps=1e-8):
        """
        Calculate and return the auxiliary loss based on the accumulated statistics.

        Args:
            eps (float): Small epsilon value for numerical stability.

        Returns:
            torch.Tensor: The calculated auxiliary loss.
        """
        if self.aux_loss == 'mi':
            denominator = self.count_layers
            p_e = self.p_e / denominator
            H_e = -(p_e * (p_e + eps).log()).sum()
            neg_H_e_given_x = self.neg_H_e_given_x / denominator
            miloss = -(neg_H_e_given_x + H_e)
            loss = miloss
        else:
            switchloss =  self.num_experts * (


        Args:
            probs (torch.Tensor): Probability values for each expert.
            logits (torch.Tensor): Logits values for each expert.
            gates (torch.Tensor): Gating values for each expert.
            skip_mask (torch.Tensor): Skip mask tensor.

        """
        if self.aux_loss == 'mi':
            log_prob = torch.log_softmax(logits, dim=-1)
            self.p_e = self.p_e + probs.mean(0)
            self.neg_H_e_given_x = self.neg_H_e_given_x + (probs * log_prob).sum() / probs.size(0)
            self.count_layers += 1
        else:
            self.acc_count = self.acc_count + logits.size(0)
            self.acc_probs = self.acc_probs + probs.sum(0)
            self.acc_freq = self.acc_freq + (gates > 0).float().sum(0)
            lsesq = torch.log(torch.exp(logits).sum(dim=-1)) ** 2
            self.acc_lsesq = self.acc_lsesq + lsesq.sum()

    def get_aux_loss_and_clear(self, eps=1e-8):
        """
        Calculate and return the auxiliary loss based on the accumulated statistics.

        Args:
            eps (float): Small epsilon value for numerical stability.

        Returns:
            torch.Tensor: The calculated auxiliary loss.
        """
        if self.aux_loss == 'mi':
            denominator = self.count_layers
            p_e = self.p_e / denominator
            H_e = -(p_e * (p_e + eps).log()).sum()
            neg_H_e_given_x = self.neg_H_e_given_x / denominator
            miloss = -(neg_H_e_given_x + H_e)
            loss = miloss
        else:
            switchloss =  self.num_experts * (
                F.normalize(self.acc_probs, p=1, dim=0) *
                F.normalize(self.acc_freq, p=1, dim=0)
            ).sum()
            zloss = self.acc_lsesq / self.acc_count
            loss = switchloss + 0.1 * zloss

        self.init_aux_statistics()
        return loss

    def forward(self, x, skip_mask=None):
        """
        Compute the top-k gating for the input.

        See paper: https://arxiv.org/abs/1701.06538.

        Args:
            x (torch.Tensor): Input tensor with shape [batch_size, input_size].
            skip_mask (torch.Tensor): Skip mask tensor (binary) with the same shape as `x`.
            x: input Tensor with shape [batch_size, input_size]
            train: a boolean - we only add noise at training time.
            noise_epsilon: a float

        Returns:
            torch.Tensor: Top-k indices.
            torch.Tensor: Top-k gating values.
            torch.Tensor: Probability values for each expert.
            gates: a Tensor with shape [batch_size, num_experts]
            load: a Tensor with shape [num_experts]


forward

            torch.Tensor: The calculated auxiliary loss.
        """
        if self.aux_loss == 'mi':
            denominator = self.count_layers
            p_e = self.p_e / denominator
            H_e = -(p_e * (p_e + eps).log()).sum()
            neg_H_e_given_x = self.neg_H_e_given_x / denominator
            miloss = -(neg_H_e_given_x + H_e)
            loss = miloss
        else:
            switchloss =  self.num_experts * (
                F.normalize(self.acc_probs, p=1, dim=0) *
                F.normalize(self.acc_freq, p=1, dim=0)
            ).sum()
            zloss = self.acc_lsesq / self.acc_count
            loss = switchloss + 0.1 * zloss

        self.init_aux_statistics()
        return loss

    def forward(self, x, skip_mask=None):
        """
        Compute the top-k gating for the input.

        See paper: https://arxiv.org/abs/1701.06538.

        Args:
            x (torch.Tensor): Input tensor with shape [batch_size, input_size].
            skip_mask (torch.Tensor): Skip mask tensor (binary) with the same shape as `x`.
            x: input Tensor with shape [batch_size, input_size]
            train: a boolean - we only add noise at training time.
            noise_epsilon: a float

        Returns:
            torch.Tensor: Top-k indices.
            torch.Tensor: Top-k gating values.
            torch.Tensor: Probability values for each expert.
            gates: a Tensor with shape [batch_size, num_experts]
            load: a Tensor with shape [num_experts]
        """

        if self.gate_type in ['linear', 'mlp']:
            logits = self.w_gate(x)
        elif self.gate_type == 'gmm':
            z = self.w_gate(x)
            logits = log_gmm_posterior(F.normalize(z, p=2, dim=-1), F.normalize(self.expert_centroids, p=2, dim=-1)) * self.temperature.exp()

        probs = torch.softmax(logits, dim=1)
        if skip_mask is not None:
            probs = torch.masked_fill(probs, (skip_mask == 0), 0)
            logits = torch.masked_fill(logits, (skip_mask == 0), 0)

        if self.training and (self.sample_topk > 0):
            _, top_km1_indices = probs.topk(self.top_k - self.sample_topk, dim=1)
            masked_probs = probs + 1e-6
            masked_probs[torch.arange(probs.size(0)).unsqueeze(
                1), top_km1_indices] = 0
            k_indices = torch.multinomial(masked_probs, self.sample_topk)
            top_k_indices = torch.cat([top_km1_indices, k_indices], dim=-1)
            top_k_gates = torch.gather(probs, 1, top_k_indices)
        else:
            top_k_gates, top_k_indices = probs.topk(self.top_k, dim=1)

        # if self.top_k > 1:
        #     top_k_gates = top_k_gates / (top_k_gates.sum(dim=1, keepdim=True) + 1e-6)

        # gate = torch.zeros_like(top_k_gates)
        # gate[:, 0] = 1
        # top_k_gates = (gate - top_k_gates).detach() + top_k_gates

        zeros = torch.zeros_like(probs)
        gates = zeros.scatter(1, top_k_indices, top_k_gates)
        self.update_aux_statistics(probs, logits, gates, skip_mask)
        if not self.acc_aux_loss:
            self.loss = self.get_aux_loss_and_clear()
        else:
            self.loss = 0

        return top_k_indices, top_k_gates, probs

        # batch_gates, batch_index, expert_size, gates, index_sorted_experts = \
        #     compute_gating(self.top_k, probs, top_k_gates, top_k_indices)

        # return batch_gates, batch_index, expert_size.tolist(), gates, index_sorted_experts


moduleformer.utils.moe

import math
from typing import List

import torch
import torch.nn as nn
import torch.nn.functional as F

from .parallel_experts import ParallelExperts
from .gate import top_k_gating, compute_gating

class MoE(nn.Module):
    """
    A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.

    Args:
        input_size: integer - size of the input
        head_size: integer - size of the expert's hidden layer
        num_experts: an integer - number of experts
        top_k: an integer - how many experts to use for each batch element
        bias: a boolean - whether to include bias in linear layers
        activation: an activation function to apply to expert's outputs
        acc_aux_loss: a boolean - whether to accumulate auxiliary loss
        hidden_size: an integer - hidden size of the experts
        gating_dropout: a float - dropout rate for gating network
        sample_topk: an integer - how many experts to sample during training
        gating_size: an integer - size of the gating network
        aux_loss: a string - type of auxiliary loss ('mi' or 'sparse')
        gate_type: a string - type of gating mechanism ('mlp' or 'topk')
    """

    def __init__(
        self,
        input_size,
        head_size,
        num_experts,
        top_k,
        bias=False,
        activation=None,
        acc_aux_loss=False,
        hidden_size=None,
        gating_dropout=0.0,
        sample_topk=0,
        gating_size=256,
        aux_loss='mi',
        gate_type='mlp',
        ):
        super(MoE, self).__init__()

        self.num_experts = num_experts
        self.input_size = input_size
        self.head_size = head_size
        self.bias = bias
        self.experts = ParallelExperts(num_experts, input_size, head_size, bias)
        if hidden_size is None:
            hidden_size = head_size
        self.output_experts = ParallelExperts(num_experts, hidden_size, input_size, bias)
        self.top_k = min(top_k, self.num_experts)
        self.activation = activation

        self.gate = top_k_gating(
            input_size=input_size,
            num_experts=num_experts,
            top_k=top_k,
            acc_aux_loss=acc_aux_loss,
            dropout=gating_dropout,
            sample_topk=sample_topk,
            hidden_size=gating_size,
            aux_loss=aux_loss,
            gate_type=gate_type,
            )

    def extra_repr(self):
        return 'k={}'.format(
            self.top_k)

    def get_aux_loss_and_clear(self):
        """
        Get the accumulated auxiliary loss and clear it.

        Returns:
            float: Accumulated auxiliary loss.
        """

        return self.gate.get_aux_loss_and_clear()

    def compute_gate(self, moe_inp, skip_mask=None):
        """
        Compute gating for the mixture of experts.

        Args:
            moe_inp (Tensor): Input tensor.
            skip_mask (Tensor): Skip mask tensor.

        Returns:
            float: Gating loss.
        """

        top_k_indices, top_k_gates, probs = self.gate(moe_inp, skip_mask=skip_mask)
        self.batch_gates, self.batch_index, expert_size, self.index_sorted_experts =\
            compute_gating(self.top_k, probs, top_k_gates, top_k_indices)
        self.expert_size = expert_size.tolist()
        return self.gate.loss

    def forward(self, x, skip_mask=None, sample_topk=0, multiply_by_gates=True):
        """
        Forward pass of the mixture of experts layer.

        Args:
            x (Tensor): Input tensor.
            skip_mask (Tensor): Skip mask tensor.
            sample_topk (int): Number of experts to sample during training.
            multiply_by_gates (bool): Whether to multiply outputs by gating values.

        Returns:
            Tensor: Output tensor.
            float: Gating loss.
        """
        bsz, length, emb_size = x.size()
        if skip_mask is not None:
            assert x.size()[:-1] == skip_mask.size(), \
                    "Skip mask should be same shape as `x`"
            skip_mask = skip_mask.flatten()[:, None]
        x = x.reshape(-1, emb_size)
        loss = self.compute_gate(x, skip_mask)

        expert_inputs = x[self.batch_index]
        h = self.experts(expert_inputs, self.expert_size)
        h = self.activation(h)
        expert_outputs = self.output_experts(h, self.expert_size)

        if multiply_by_gates:
            expert_outputs = expert_outputs * self.batch_gates[:, None]

        zeros = torch.zeros(
            (bsz * length, self.input_size),
            dtype=expert_outputs.dtype, device=expert_outputs.device)
        y = zeros.index_add(0, self.batch_index, expert_outputs)
        y = y.view(bsz, length, self.input_size)
        # assert torch.allclose(y, y_)
        return y, loss

    def map(self, x, skip_mask=None, sample_topk=0, return_indices=False):
        """

        Args:
            x: tensor shape [batch_size, input_size]
            train: a boolean scalar.
            loss_coef: a scalar - multiplier on load-balancing losses

        Returns:
            y: a tensor with shape [batch_size, output_size].
            extra_training_loss: a scalar.  This should be added into the overall
            training loss of the model.  The backpropagation of this loss
            encourages all experts to be approximately equally used across a batch.
        """
        """
        Map input through the mixture of experts layer.

        Args:
            x (Tensor): Input tensor.
            skip_mask (Tensor): Skip mask tensor.
            sample_topk (int): Number of experts to sample during training.
            return_indices (bool): Whether to return expert indices.

        Returns:
            Tensor: Output tensor.
            float: Gating loss.
        """
        if skip_mask is not None:
            assert x.size()[:-1] == skip_mask.size(), \
                    "Skip mask should be same shape as `x`"
        bsz, length, emb_size = x.size()
        x = x.reshape(-1, emb_size)
        if skip_mask is not None:
            skip_mask = skip_mask.view(-1, 1)
        loss = self.compute_gate(x, skip_mask)

        expert_inputs = x[self.batch_index]
        expert_outputs = self.experts(expert_inputs, self.expert_size)

        zeros = torch.zeros((bsz * length * self.top_k, self.head_size),
            dtype=expert_outputs.dtype, device=expert_outputs.device)
        y = zeros.index_add(0, self.index_sorted_experts, expert_outputs)
        y = y.view(bsz, length, self.top_k, -1)
        return y, loss

    def reduce(self, x, multiply_by_gates=True):
        """
        Reduce the mapped output.

        Args:
            x (Tensor): Mapped output tensor.
            multiply_by_gates (bool): Whether to multiply outputs by gating values.

        Returns:
            Tensor: Reduced output tensor.
        """

        bsz, length, k, emb_size = x.size()
        x = x.reshape(-1, emb_size)

        expert_inputs = x[self.index_sorted_experts]
        expert_outputs = self.output_experts(expert_inputs, self.expert_size)

        if multiply_by_gates:
            expert_outputs = expert_outputs * self.batch_gates[:, None]

        zeros = torch.zeros((bsz * length, self.input_size),
            dtype=expert_outputs.dtype, device=expert_outputs.device)
        y = zeros.index_add(0, self.batch_index, expert_outputs)
        y = y.view(bsz, length, self.input_size)
        return y


    """
    A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.

    Args:
        input_size: integer - size of the input
        head_size: integer - size of the expert's hidden layer
        num_experts: an integer - number of experts
        top_k: an integer - how many experts to use for each batch element
        bias: a boolean - whether to include bias in linear layers
        activation: an activation function to apply to expert's outputs
        acc_aux_loss: a boolean - whether to accumulate auxiliary loss
        hidden_size: an integer - hidden size of the experts
        gating_dropout: a float - dropout rate for gating network
        sample_topk: an integer - how many experts to sample during training
        gating_size: an integer - size of the gating network
        aux_loss: a string - type of auxiliary loss ('mi' or 'sparse')
        gate_type: a string - type of gating mechanism ('mlp' or 'topk')
    """

    def __init__(
        self,
        input_size,
        head_size,
        num_experts,
        top_k,
        bias=False,
        activation=None,
        acc_aux_loss=False,
        hidden_size=None,
        gating_dropout=0.0,
        sample_topk=0,
        gating_size=256,
        aux_loss='mi',
        gate_type='mlp',
        ):
        super(MoE, self).__init__()

        self.num_experts = num_experts
        self.input_size = input_size
        self.head_size = head_size
        self.bias = bias
        self.experts = ParallelExperts(num_experts, input_size, head_size, bias)
        if hidden_size is None:
            hidden_size = head_size
        self.output_experts = ParallelExperts(num_experts, hidden_size, input_size, bias)
        self.top_k = min(top_k, self.num_experts)
        self.activation = activation

        self.gate = top_k_gating(
            input_size=input_size,
            num_experts=num_experts,
            top_k=top_k,
            acc_aux_loss=acc_aux_loss,
            dropout=gating_dropout,
            sample_topk=sample_topk,
            hidden_size=gating_size,
            aux_loss=aux_loss,
            gate_type=gate_type,
            )

    def extra_repr(self):
        return 'k={}'.format(
            self.top_k)

    def get_aux_loss_and_clear(self):
        """
        Get the accumulated auxiliary loss and clear it.

        Returns:
            float: Accumulated auxiliary loss.
        """

        return self.gate.get_aux_loss_and_clear()

    def compute_gate(self, moe_inp, skip_mask=None):
        """
        Compute gating for the mixture of experts.

        Args:


        self.bias = bias
        self.experts = ParallelExperts(num_experts, input_size, head_size, bias)
        if hidden_size is None:
            hidden_size = head_size
        self.output_experts = ParallelExperts(num_experts, hidden_size, input_size, bias)
        self.top_k = min(top_k, self.num_experts)
        self.activation = activation

        self.gate = top_k_gating(
            input_size=input_size,
            num_experts=num_experts,
            top_k=top_k,
            acc_aux_loss=acc_aux_loss,
            dropout=gating_dropout,
            sample_topk=sample_topk,
            hidden_size=gating_size,
            aux_loss=aux_loss,
            gate_type=gate_type,
            )

    def extra_repr(self):
        return 'k={}'.format(
            self.top_k)

    def get_aux_loss_and_clear(self):
        """
        Get the accumulated auxiliary loss and clear it.

        Returns:
            float: Accumulated auxiliary loss.
        """

        return self.gate.get_aux_loss_and_clear()

    def compute_gate(self, moe_inp, skip_mask=None):
        """
        Compute gating for the mixture of experts.

        Args:
            moe_inp (Tensor): Input tensor.
            skip_mask (Tensor): Skip mask tensor.

        Returns:


        self.output_experts = ParallelExperts(num_experts, hidden_size, input_size, bias)
        self.top_k = min(top_k, self.num_experts)
        self.activation = activation

        self.gate = top_k_gating(
            input_size=input_size,
            num_experts=num_experts,
            top_k=top_k,
            acc_aux_loss=acc_aux_loss,
            dropout=gating_dropout,
            sample_topk=sample_topk,
            hidden_size=gating_size,
            aux_loss=aux_loss,
            gate_type=gate_type,
            )

    def extra_repr(self):
        return 'k={}'.format(
            self.top_k)

    def get_aux_loss_and_clear(self):
        """
        Get the accumulated auxiliary loss and clear it.

        Returns:
            float: Accumulated auxiliary loss.
        """

        return self.gate.get_aux_loss_and_clear()

    def compute_gate(self, moe_inp, skip_mask=None):
        """
        Compute gating for the mixture of experts.

        Args:
            moe_inp (Tensor): Input tensor.
            skip_mask (Tensor): Skip mask tensor.

        Returns:
            float: Gating loss.
        """

        top_k_indices, top_k_gates, probs = self.gate(moe_inp, skip_mask=skip_mask)
        self.batch_gates, self.batch_index, expert_size, self.index_sorted_experts =\
            compute_gating(self.top_k, probs, top_k_gates, top_k_indices)
        self.expert_size = expert_size.tolist()
        return self.gate.loss

    def forward(self, x, skip_mask=None, sample_topk=0, multiply_by_gates=True):


            sample_topk=sample_topk,
            hidden_size=gating_size,
            aux_loss=aux_loss,
            gate_type=gate_type,
            )

    def extra_repr(self):
        return 'k={}'.format(
            self.top_k)

    def get_aux_loss_and_clear(self):
        """
        Get the accumulated auxiliary loss and clear it.

        Returns:
            float: Accumulated auxiliary loss.
        """

        return self.gate.get_aux_loss_and_clear()

    def compute_gate(self, moe_inp, skip_mask=None):
        """
        Compute gating for the mixture of experts.

        Args:
            moe_inp (Tensor): Input tensor.
            skip_mask (Tensor): Skip mask tensor.

        Returns:
            float: Gating loss.
        """

        top_k_indices, top_k_gates, probs = self.gate(moe_inp, skip_mask=skip_mask)
        self.batch_gates, self.batch_index, expert_size, self.index_sorted_experts =\
            compute_gating(self.top_k, probs, top_k_gates, top_k_indices)
        self.expert_size = expert_size.tolist()
        return self.gate.loss

    def forward(self, x, skip_mask=None, sample_topk=0, multiply_by_gates=True):
        """
        Forward pass of the mixture of experts layer.

        Args:
            x (Tensor): Input tensor.
            skip_mask (Tensor): Skip mask tensor.
            sample_topk (int): Number of experts to sample during training.
            multiply_by_gates (bool): Whether to multiply outputs by gating values.

        Returns:
            Tensor: Output tensor.
            float: Gating loss.
        """
        bsz, length, emb_size = x.size()
        if skip_mask is not None:
            assert x.size()[:-1] == skip_mask.size(), \
                    "Skip mask should be same shape as `x`"
            skip_mask = skip_mask.flatten()[:, None]


forward

        return self.gate.get_aux_loss_and_clear()

    def compute_gate(self, moe_inp, skip_mask=None):
        """
        Compute gating for the mixture of experts.

        Args:
            moe_inp (Tensor): Input tensor.
            skip_mask (Tensor): Skip mask tensor.

        Returns:
            float: Gating loss.
        """

        top_k_indices, top_k_gates, probs = self.gate(moe_inp, skip_mask=skip_mask)
        self.batch_gates, self.batch_index, expert_size, self.index_sorted_experts =\
            compute_gating(self.top_k, probs, top_k_gates, top_k_indices)
        self.expert_size = expert_size.tolist()
        return self.gate.loss

    def forward(self, x, skip_mask=None, sample_topk=0, multiply_by_gates=True):
        """
        Forward pass of the mixture of experts layer.

        Args:
            x (Tensor): Input tensor.
            skip_mask (Tensor): Skip mask tensor.
            sample_topk (int): Number of experts to sample during training.
            multiply_by_gates (bool): Whether to multiply outputs by gating values.

        Returns:
            Tensor: Output tensor.
            float: Gating loss.
        """
        bsz, length, emb_size = x.size()
        if skip_mask is not None:
            assert x.size()[:-1] == skip_mask.size(), \
                    "Skip mask should be same shape as `x`"
            skip_mask = skip_mask.flatten()[:, None]
        x = x.reshape(-1, emb_size)
        loss = self.compute_gate(x, skip_mask)

        expert_inputs = x[self.batch_index]
        h = self.experts(expert_inputs, self.expert_size)
        h = self.activation(h)
        expert_outputs = self.output_experts(h, self.expert_size)

        if multiply_by_gates:
            expert_outputs = expert_outputs * self.batch_gates[:, None]

        zeros = torch.zeros(
            (bsz * length, self.input_size),
            dtype=expert_outputs.dtype, device=expert_outputs.device)
        y = zeros.index_add(0, self.batch_index, expert_outputs)
        y = y.view(bsz, length, self.input_size)
        # assert torch.allclose(y, y_)
        return y, loss

    def map(self, x, skip_mask=None, sample_topk=0, return_indices=False):
        """

        Args:
            x: tensor shape [batch_size, input_size]
            train: a boolean scalar.
            loss_coef: a scalar - multiplier on load-balancing losses

        Returns:
            y: a tensor with shape [batch_size, output_size].
            extra_training_loss: a scalar.  This should be added into the overall
            training loss of the model.  The backpropagation of this loss
            encourages all experts to be approximately equally used across a batch.
        """
        """
        Map input through the mixture of experts layer.

        Args:
            x (Tensor): Input tensor.


map

            skip_mask = skip_mask.flatten()[:, None]
        x = x.reshape(-1, emb_size)
        loss = self.compute_gate(x, skip_mask)

        expert_inputs = x[self.batch_index]
        h = self.experts(expert_inputs, self.expert_size)
        h = self.activation(h)
        expert_outputs = self.output_experts(h, self.expert_size)

        if multiply_by_gates:
            expert_outputs = expert_outputs * self.batch_gates[:, None]

        zeros = torch.zeros(
            (bsz * length, self.input_size),
            dtype=expert_outputs.dtype, device=expert_outputs.device)
        y = zeros.index_add(0, self.batch_index, expert_outputs)
        y = y.view(bsz, length, self.input_size)
        # assert torch.allclose(y, y_)
        return y, loss

    def map(self, x, skip_mask=None, sample_topk=0, return_indices=False):
        """

        Args:
            x: tensor shape [batch_size, input_size]
            train: a boolean scalar.
            loss_coef: a scalar - multiplier on load-balancing losses

        Returns:
            y: a tensor with shape [batch_size, output_size].
            extra_training_loss: a scalar.  This should be added into the overall
            training loss of the model.  The backpropagation of this loss
            encourages all experts to be approximately equally used across a batch.
        """
        """
        Map input through the mixture of experts layer.

        Args:
            x (Tensor): Input tensor.
            skip_mask (Tensor): Skip mask tensor.
            sample_topk (int): Number of experts to sample during training.
            return_indices (bool): Whether to return expert indices.

        Returns:
            Tensor: Output tensor.
            float: Gating loss.
        """
        if skip_mask is not None:
            assert x.size()[:-1] == skip_mask.size(), \
                    "Skip mask should be same shape as `x`"
        bsz, length, emb_size = x.size()
        x = x.reshape(-1, emb_size)
        if skip_mask is not None:
            skip_mask = skip_mask.view(-1, 1)
        loss = self.compute_gate(x, skip_mask)

        expert_inputs = x[self.batch_index]
        expert_outputs = self.experts(expert_inputs, self.expert_size)

        zeros = torch.zeros((bsz * length * self.top_k, self.head_size),
            dtype=expert_outputs.dtype, device=expert_outputs.device)
        y = zeros.index_add(0, self.index_sorted_experts, expert_outputs)
        y = y.view(bsz, length, self.top_k, -1)
        return y, loss

    def reduce(self, x, multiply_by_gates=True):
        """
        Reduce the mapped output.

        Args:
            x (Tensor): Mapped output tensor.
            multiply_by_gates (bool): Whether to multiply outputs by gating values.

        Returns:
            Tensor: Reduced output tensor.
        """

        bsz, length, k, emb_size = x.size()
        x = x.reshape(-1, emb_size)

        expert_inputs = x[self.index_sorted_experts]
        expert_outputs = self.output_experts(expert_inputs, self.expert_size)

        if multiply_by_gates:


reduce

            float: Gating loss.
        """
        if skip_mask is not None:
            assert x.size()[:-1] == skip_mask.size(), \
                    "Skip mask should be same shape as `x`"
        bsz, length, emb_size = x.size()
        x = x.reshape(-1, emb_size)
        if skip_mask is not None:
            skip_mask = skip_mask.view(-1, 1)
        loss = self.compute_gate(x, skip_mask)

        expert_inputs = x[self.batch_index]
        expert_outputs = self.experts(expert_inputs, self.expert_size)

        zeros = torch.zeros((bsz * length * self.top_k, self.head_size),
            dtype=expert_outputs.dtype, device=expert_outputs.device)
        y = zeros.index_add(0, self.index_sorted_experts, expert_outputs)
        y = y.view(bsz, length, self.top_k, -1)
        return y, loss

    def reduce(self, x, multiply_by_gates=True):
        """
        Reduce the mapped output.

        Args:
            x (Tensor): Mapped output tensor.
            multiply_by_gates (bool): Whether to multiply outputs by gating values.

        Returns:
            Tensor: Reduced output tensor.
        """

        bsz, length, k, emb_size = x.size()
        x = x.reshape(-1, emb_size)

        expert_inputs = x[self.index_sorted_experts]
        expert_outputs = self.output_experts(expert_inputs, self.expert_size)

        if multiply_by_gates:
            expert_outputs = expert_outputs * self.batch_gates[:, None]

        zeros = torch.zeros((bsz * length, self.input_size),
            dtype=expert_outputs.dtype, device=expert_outputs.device)
        y = zeros.index_add(0, self.batch_index, expert_outputs)
        y = y.view(bsz, length, self.input_size)
        return y


import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.cuda.amp import custom_fwd, custom_bwd
from typing import Any, Dict, List, Optional
from torch import Tensor

class ParallelLinear(torch.autograd.Function):
    """
    A custom autograd function for Parallel Linear operation.
    """

    @staticmethod
    @custom_fwd
    def forward(ctx, input, expert_size_list, weight, bias=None):
        """
        Forward pass of the ParallelLinear operation.

        Args:
            ctx: Context object.
            input (Tensor): Input tensor.
            expert_size_list (List[int]): List of expert sizes.
            weight (Tensor): Weight tensor.
            bias (Optional[Tensor]): Bias tensor.

        Returns:
            Tensor: Output tensor.
        """
        # expert_size_list: List[int] = expert_size.tolist()
        output = ParallelLinear.forward_scriptable(input, expert_size_list, weight, bias)
        # assert torch.allclose(ParallelLinear._forward_scriptable(input, expert_size, weight, bias),  output)
        ctx.save_for_backward(input, weight, bias)
        ctx.expert_size_list = expert_size_list
        return output

    @staticmethod
    @torch.jit.script
    def forward_scriptable(input: Tensor, expert_size_list: List[int],
                           weight: Tensor, bias: Optional[Tensor]):
        """
        Scriptable forward pass of the ParallelLinear operation.

        Args:
            input (Tensor): Input tensor.
            expert_size_list (List[int]): List of expert sizes.
            weight (Tensor): Weight tensor.
            bias (Optional[Tensor]): Bias tensor.

        Returns:
            Tensor: Output tensor.
        """
        output_buf: Tensor = torch.empty((input.size(0), weight.size(2)),
                                         device=input.device, dtype=input.dtype)
        num_linears = weight.size(0)

        input_list = input.split(expert_size_list, dim=0)
        output_buf_list = output_buf.split(expert_size_list)

        for i in range(num_linears):
            torch.mm(input_list[i], weight[i], out=output_buf_list[i])

        if bias is not None:
            for i in range(num_linears):
                output_buf_list[i].add_(bias[i])

        output = output_buf
        return output

    @staticmethod
    @custom_bwd
    def backward(ctx, grad_out):
        """
        Backward pass of the ParallelLinear operation.

        Args:
            ctx: Context object.
            grad_out (Tensor): Gradient of the output.

        Returns:
            Tuple of Tensors: Gradients with respect to input, weight, and bias.
        """
        input, weight, bias = ctx.saved_tensors
        expert_size_list = ctx.expert_size_list
        return ParallelLinear.backward_scriptable(
            grad_out, input, expert_size_list,
            weight, bias
        )

    @staticmethod
    @torch.jit.script
    def backward_scriptable(grad_out: Tensor,
                 input: Tensor, expert_size_list: List[int],
                 weight: Tensor, bias: Optional[Tensor]):
        """
        Scriptable backward pass of the ParallelLinear operation.

        Args:
            grad_out (Tensor): Gradient of the output.
            input (Tensor): Input tensor.
            expert_size_list (List[int]): List of expert sizes.
            weight (Tensor): Weight tensor.
            bias (Optional[Tensor]): Bias tensor.

        Returns:
            Tuple of Tensors: Gradients with respect to input, weight, and bias.
        """
        num_linears = weight.size(0)
        input_list = input.t().split(expert_size_list, dim=1)
        grad_list = grad_out.split(expert_size_list, dim=0)

        d_input_buf = torch.empty_like(input)
        d_input_buf_list = d_input_buf.split(expert_size_list, dim=0)
        d_weight_buf = torch.empty_like(weight)

        weight_t = weight.permute(0, 2, 1)

        for i in range(num_linears):
            torch.mm(grad_list[i], weight_t[i], out=d_input_buf_list[i])
            torch.mm(input_list[i], grad_list[i], out=d_weight_buf[i])

        d_input = d_input_buf
        d_weight = d_weight_buf

        if bias is not None:
            d_bias_buf = torch.empty_like(bias)
            for i in range(num_linears):
                torch.sum(grad_list[i], dim=0, keepdim=False, out=d_bias_buf[i])
            d_bias = d_bias_buf
        else:
            d_bias = None

        return d_input, None, d_weight, d_bias

class ParallelExperts(nn.Module):
    def __init__(self, num_experts, input_size, output_size, bias=False) -> None:
        """
        Initialize the ParallelExperts module.

        Args:
            num_experts (int): Number of experts.
            input_size (int): Size of the input.
            output_size (int): Size of the output.
            bias (bool): Whether to include bias terms.
        """
        super().__init__()
        # self.input_experts = nn.ModuleList(
        #     [nn.Linear(input_size, output_size, bias=bias) for _ in range(num_experts)]
        # )
        self.weight = nn.Parameter(torch.empty(num_experts, input_size, output_size))
        if bias:
            self.bias = nn.Parameter(torch.zeros(num_experts, output_size))
        else:
            self.bias = None
        self.reset_parameters()
        self.num_experts = num_experts
        self.input_size = input_size
        self.output_size = output_size

    def extra_repr(self):
        return 'num_experts={}, input_size={}, output_size={}'.format(
            self.num_experts, self.input_size, self.output_size)

    def reset_parameters(self) -> None:
        """
        Reset the parameters of the model.
        """
        # std = math.sqrt(2.0 / float(self.weight.size(1) + self.weight.size(2)))
        # a = math.sqrt(3.0) * std
        nn.init.uniform_(self.weight, -1. / self.weight.size(1), 1. / self.weight.size(1))
        if self.bias is not None:
            fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight[0])
            bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0
            nn.init.uniform_(self.bias, -bound, bound)

    def forward(self, inputs, expert_size):
        """
        Forward pass of the ParallelExperts module.

        Args:
            inputs (Tensor): Input tensor.
            expert_size: Expert size information.

        Returns:
            Tensor: Output tensor.
        """
        results = ParallelLinear.apply(inputs, expert_size, self.weight, self.bias)
        # expert_size_list: List[int] = expert_size.tolist()
        # input_list = inputs.split(expert_size_list, dim=0)
        # output_list = []
        # for i in range(self.num_experts):
        #     output_list.append(self.input_experts[i](input_list[i]))
        # results = torch.cat(output_list, dim=0)
        return results