import torch
import numpy as np
from torch import nn
from torch.nn import init


class SimplifiedScaledDotProductAttention(nn.Module):
    """
    Scaled dot-product attention
    """

    def __init__(self, d_model, h, dropout=0.1):
        """
        :param d_model: Output dimensionality of the model
        :param d_k: Dimensionality of queries and keys
        :param d_v: Dimensionality of values
        :param h: Number of heads
        """
        super(SimplifiedScaledDotProductAttention, self).__init__()
        self.d_model = d_model
        self.d_k = d_model // h
        self.d_v = d_model // h
        self.h = h
        self.fc_o = nn.Linear(h * self.d_v, d_model)
        self.dropout = nn.Dropout(dropout)
        self.init_weights()

    def init_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                init.kaiming_normal_(m.weight, mode='fan_out')
                if m.bias is not None:
                    init.constant_(m.bias, 0)
            elif isinstance(m, nn.BatchNorm2d):
                init.constant_(m.weight, 1)
                init.constant_(m.bias, 0)
            elif isinstance(m, nn.Linear):
                init.normal_(m.weight, std=0.001)
                if m.bias is not None:
                    init.constant_(m.bias, 0)

    def forward(self, queries, keys, values, attention_mask=None,
        attention_weights=None):
        """
        Computes
        :param queries: Queries (b_s, nq, d_model)
        :param keys: Keys (b_s, nk, d_model)
        :param values: Values (b_s, nk, d_model)
        :param attention_mask: Mask over attention values (b_s, h, nq, nk). True indicates masking.
        :param attention_weights: Multiplicative weights for attention values (b_s, h, nq, nk).
        :return:
        """
        b_s, nq = queries.shape[:2]
        nk = keys.shape[1]
        q = queries.view(b_s, nq, self.h, self.d_k).permute(0, 2, 1, 3)
        k = keys.view(b_s, nk, self.h, self.d_k).permute(0, 2, 3, 1)
        v = values.view(b_s, nk, self.h, self.d_v).permute(0, 2, 1, 3)
        att = torch.matmul(q, k) / np.sqrt(self.d_k)
        if attention_weights is not None:
            att = att * attention_weights
        if attention_mask is not None:
            att = att.masked_fill(attention_mask, -np.inf)
        att = torch.softmax(att, -1)
        att = self.dropout(att)
        out = torch.matmul(att, v).permute(0, 2, 1, 3).contiguous().view(b_s,
            nq, self.h * self.d_v)
        out = self.fc_o(out)
        return out


class ChannelAttentionModule(nn.Module):

    def __init__(self, d_model=512, kernel_size=3, H=7, W=7):
        super().__init__()
        self.cnn = nn.Conv2d(d_model, d_model, kernel_size=kernel_size,
            padding=(kernel_size - 1) // 2)
        self.pa = SimplifiedScaledDotProductAttention(H * W, h=1)

    def forward(self, x):
        bs, c, _h, _w = x.shape
        y = self.cnn(x)
        y = y.view(bs, c, -1)
        y = self.pa(y, y, y)
        return y


def get_inputs():
    return [torch.rand([4, 512, 1, 49])]


def get_init_inputs():
    return [[], {}]

import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import math as tl_math
import numpy as np
from torch import nn
from torch.nn import init
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor


@triton.jit
def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
    constexpr, XBLOCK: tl.constexpr):
    xnumel = 49
    yoffset = tl.program_id(1) * YBLOCK
    yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
    tl.full([XBLOCK, YBLOCK], True, tl.int1)
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    x2 = xindex
    y3 = yindex
    y0 = yindex % 512
    y1 = yindex // 512
    tmp0 = tl.load(in_ptr0 + (x2 + 49 * y3), xmask, eviction_policy=
        'evict_last')
    tl.store(out_ptr0 + (y0 + 512 * x2 + 25088 * y1), tmp0, xmask)


@triton.jit
def triton_poi_fused_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
    constexpr, XBLOCK: tl.constexpr):
    xnumel = 9
    yoffset = (tl.program_id(1) + tl.program_id(2) * tl.num_programs(1)
        ) * YBLOCK
    yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
    tl.full([XBLOCK, YBLOCK], True, tl.int1)
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    x2 = xindex
    y3 = yindex
    y0 = yindex % 512
    y1 = yindex // 512
    tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last'
        )
    tl.store(out_ptr0 + (y0 + 512 * x2 + 4608 * y1), tmp0, xmask)


@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
    .constexpr):
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    tl.full([XBLOCK], True, tl.int1)
    x2 = xindex
    x0 = xindex % 512
    tmp0 = tl.load(in_out_ptr0 + x2, None)
    tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tl.store(in_out_ptr0 + x2, tmp2, None)


@triton.jit
def triton_per_fused__softmax_sqrt_3(in_ptr0, out_ptr2, xnumel, rnumel):
    XBLOCK: tl.constexpr = 1
    RBLOCK: tl.constexpr = 512
    xoffset = tl.program_id(0) * XBLOCK
    xindex = tl.full([1], xoffset, tl.int32)
    tl.full([RBLOCK], True, tl.int1)
    rindex = tl.arange(0, RBLOCK)[:]
    tl.full([RBLOCK], True, tl.int1)
    r1 = rindex
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + (r1 + 512 * x0), None)
    tmp1 = tl.full([1], 7.0, tl.float64)
    tmp2 = tl.full([1], 0.0, tl.float64)
    tmp3 = tmp1 >= tmp2
    tmp4 = 1.0
    tmp5 = -1.0
    tmp6 = tl.where(tmp3, tmp4, tmp5)
    tmp7 = tmp0 * tmp6
    tmp8 = tl.broadcast_to(tmp7, [RBLOCK])
    tmp10 = triton_helpers.promote_to_tensor(triton_helpers.max2(tmp8, 0))
    tmp11 = tmp7 - tmp10
    tmp12 = tmp6.to(tl.float64)
    tmp13 = tmp12 * tmp1
    tmp14 = tmp13.to(tl.float32)
    tmp15 = tmp11 / tmp14
    tmp16 = tl_math.exp(tmp15)
    tmp17 = tl.broadcast_to(tmp16, [RBLOCK])
    tmp19 = triton_helpers.promote_to_tensor(tl.sum(tmp17, 0))
    tmp20 = tmp16 / tmp19
    tl.store(out_ptr2 + (r1 + 512 * x0), tmp20, None)


def call(args):
    primals_1, primals_2, primals_3, primals_4, primals_5 = args
    args.clear()
    assert_size_stride(primals_1, (4, 512, 1, 49), (25088, 49, 49, 1))
    assert_size_stride(primals_2, (512, 512, 3, 3), (4608, 9, 3, 1))
    assert_size_stride(primals_3, (512,), (1,))
    assert_size_stride(primals_4, (49, 49), (49, 1))
    assert_size_stride(primals_5, (49,), (1,))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 512, 1, 49), (25088, 1, 25088, 512),
            torch.float32)
        get_raw_stream(0)
        triton_poi_fused_0[grid(2048, 49)](primals_1, buf0, 2048, 49,
            XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1)
        del primals_1
        buf1 = empty_strided_cuda((512, 512, 3, 3), (4608, 1, 1536, 512),
            torch.float32)
        triton_poi_fused_1[grid(262144, 9)](primals_2, buf1, 262144, 9,
            XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1)
        del primals_2
        buf2 = extern_kernels.convolution(buf0, buf1, stride=(1, 1),
            padding=(1, 1), dilation=(1, 1), transposed=False,
            output_padding=(0, 0), groups=1, bias=None)
        assert_size_stride(buf2, (4, 512, 1, 49), (25088, 1, 25088, 512))
        buf3 = buf2
        del buf2
        triton_poi_fused_convolution_2[grid(100352)](buf3, primals_3, 
            100352, XBLOCK=1024, num_warps=4, num_stages=1)
        del primals_3
        buf4 = empty_strided_cuda((4, 512, 512), (262144, 512, 1), torch.
            float32)
        extern_kernels.bmm(reinterpret_tensor(buf3, (4, 512, 49), (25088, 1,
            512), 0), reinterpret_tensor(buf3, (4, 49, 512), (25088, 512, 1
            ), 0), out=buf4)
        buf7 = empty_strided_cuda((4, 1, 512, 512), (262144, 1, 512, 1),
            torch.float32)
        triton_per_fused__softmax_sqrt_3[grid(2048)](buf4, buf7, 2048, 512,
            num_warps=4, num_stages=1)
        del buf4
        buf8 = empty_strided_cuda((4, 512, 49), (25088, 49, 1), torch.float32)
        extern_kernels.bmm(reinterpret_tensor(buf7, (4, 512, 512), (262144,
            512, 1), 0), reinterpret_tensor(buf3, (4, 512, 49), (25088, 1, 
            512), 0), out=buf8)
        buf9 = empty_strided_cuda((2048, 49), (49, 1), torch.float32)
        extern_kernels.addmm(primals_5, reinterpret_tensor(buf8, (2048, 49),
            (49, 1), 0), reinterpret_tensor(primals_4, (49, 49), (1, 49), 0
            ), alpha=1, beta=1, out=buf9)
        del primals_5
    return reinterpret_tensor(buf9, (4, 512, 49), (25088, 49, 1), 0
        ), buf0, buf1, buf3, buf7, reinterpret_tensor(buf8, (2048, 49), (49,
        1), 0), primals_4


class SimplifiedScaledDotProductAttention(nn.Module):
    """
    Scaled dot-product attention
    """

    def __init__(self, d_model, h, dropout=0.1):
        """
        :param d_model: Output dimensionality of the model
        :param d_k: Dimensionality of queries and keys
        :param d_v: Dimensionality of values
        :param h: Number of heads
        """
        super(SimplifiedScaledDotProductAttention, self).__init__()
        self.d_model = d_model
        self.d_k = d_model // h
        self.d_v = d_model // h
        self.h = h
        self.fc_o = nn.Linear(h * self.d_v, d_model)
        self.dropout = nn.Dropout(dropout)
        self.init_weights()

    def init_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                init.kaiming_normal_(m.weight, mode='fan_out')
                if m.bias is not None:
                    init.constant_(m.bias, 0)
            elif isinstance(m, nn.BatchNorm2d):
                init.constant_(m.weight, 1)
                init.constant_(m.bias, 0)
            elif isinstance(m, nn.Linear):
                init.normal_(m.weight, std=0.001)
                if m.bias is not None:
                    init.constant_(m.bias, 0)

    def forward(self, queries, keys, values, attention_mask=None,
        attention_weights=None):
        """
        Computes
        :param queries: Queries (b_s, nq, d_model)
        :param keys: Keys (b_s, nk, d_model)
        :param values: Values (b_s, nk, d_model)
        :param attention_mask: Mask over attention values (b_s, h, nq, nk). True indicates masking.
        :param attention_weights: Multiplicative weights for attention values (b_s, h, nq, nk).
        :return:
        """
        b_s, nq = queries.shape[:2]
        nk = keys.shape[1]
        q = queries.view(b_s, nq, self.h, self.d_k).permute(0, 2, 1, 3)
        k = keys.view(b_s, nk, self.h, self.d_k).permute(0, 2, 3, 1)
        v = values.view(b_s, nk, self.h, self.d_v).permute(0, 2, 1, 3)
        att = torch.matmul(q, k) / np.sqrt(self.d_k)
        if attention_weights is not None:
            att = att * attention_weights
        if attention_mask is not None:
            att = att.masked_fill(attention_mask, -np.inf)
        att = torch.softmax(att, -1)
        att = self.dropout(att)
        out = torch.matmul(att, v).permute(0, 2, 1, 3).contiguous().view(b_s,
            nq, self.h * self.d_v)
        out = self.fc_o(out)
        return out


class ChannelAttentionModuleNew(nn.Module):

    def __init__(self, d_model=512, kernel_size=3, H=7, W=7):
        super().__init__()
        self.cnn = nn.Conv2d(d_model, d_model, kernel_size=kernel_size,
            padding=(kernel_size - 1) // 2)
        self.pa = SimplifiedScaledDotProductAttention(H * W, h=1)

    def forward(self, input_0):
        primals_2 = self.cnn.weight
        primals_3 = self.cnn.bias
        primals_4 = self.pa.fc_o.weight
        primals_5 = self.pa.fc_o.bias
        primals_1 = input_0
        output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
        return output[0]
