# Copyright (c) MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#     http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import torch
import torch.nn as nn

from monai.utils import optional_import

Rearrange, _ = optional_import("einops.layers.torch", name="Rearrange")


class SABlock(nn.Module):
    """
    A self-attention block, based on: "Dosovitskiy et al.,
    An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale <https://arxiv.org/abs/2010.11929>"
    """

    def __init__(self, hidden_size: int, num_heads: int, dropout_rate: float = 0.0) -> None:
        """
        Args:
            hidden_size: dimension of hidden layer.
            num_heads: number of attention heads.
            dropout_rate: faction of the input units to drop.

        """

        super().__init__()

        if not (0 <= dropout_rate <= 1):
            raise ValueError("dropout_rate should be between 0 and 1.")

        if hidden_size % num_heads != 0:
            raise ValueError("hidden size should be divisible by num_heads.")

        self.num_heads = num_heads
        self.out_proj = nn.Linear(hidden_size, hidden_size)
        self.qkv = nn.Linear(hidden_size, hidden_size * 3, bias=False)
        self.input_rearrange = Rearrange("b h (qkv l d) -> qkv b l h d", qkv=3, l=num_heads)
        self.out_rearrange = Rearrange("b h l d -> b l (h d)")
        self.drop_output = nn.Dropout(dropout_rate)
        self.drop_weights = nn.Dropout(dropout_rate)
        self.head_dim = hidden_size // num_heads
        self.scale = self.head_dim**-0.5

    def forward(self, x):
        output = self.input_rearrange(self.qkv(x))
        q, k, v = output[0], output[1], output[2]
        att_mat = (torch.einsum("blxd,blyd->blxy", q, k) * self.scale).softmax(dim=-1)
        att_mat = self.drop_weights(att_mat)
        x = torch.einsum("bhxy,bhyd->bhxd", att_mat, v)
        x = self.out_rearrange(x)
        x = self.out_proj(x)
        x = self.drop_output(x)
        return x

[((17, 15, 17, 71), 'monai.utils.optional_import', 'optional_import', (), '', False, 'from monai.utils import optional_import\n'), ((44, 24, 44, 59), 'torch.nn.Linear', 'nn.Linear', ({(44, 34, 44, 45): 'hidden_size', (44, 47, 44, 58): 'hidden_size'}, {}), '(hidden_size, hidden_size)', True, 'import torch.nn as nn\n'), ((45, 19, 45, 70), 'torch.nn.Linear', 'nn.Linear', (), '', True, 'import torch.nn as nn\n'), ((48, 27, 48, 51), 'torch.nn.Dropout', 'nn.Dropout', ({(48, 38, 48, 50): 'dropout_rate'}, {}), '(dropout_rate)', True, 'import torch.nn as nn\n'), ((49, 28, 49, 52), 'torch.nn.Dropout', 'nn.Dropout', ({(49, 39, 49, 51): 'dropout_rate'}, {}), '(dropout_rate)', True, 'import torch.nn as nn\n'), ((58, 12, 58, 55), 'torch.einsum', 'torch.einsum', ({(58, 25, 58, 42): '"""bhxy,bhyd->bhxd"""', (58, 44, 58, 51): 'att_mat', (58, 53, 58, 54): 'v'}, {}), "('bhxy,bhyd->bhxd', att_mat, v)", False, 'import torch\n'), ((56, 19, 56, 56), 'torch.einsum', 'torch.einsum', ({(56, 32, 56, 49): '"""blxd,blyd->blxy"""', (56, 51, 56, 52): 'q', (56, 54, 56, 55): 'k'}, {}), "('blxd,blyd->blxy', q, k)", False, 'import torch\n')]