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
import math
import torch.nn as nn
import torch.nn.functional as F
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_constant_pad_nd_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
    tl.constexpr):
    xnumel = 576
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x1 = xindex // 6 % 6
    x0 = xindex % 6
    x2 = xindex // 36
    x4 = xindex
    tmp0 = -1 + x1
    tmp1 = tl.full([1], 0, tl.int64)
    tmp2 = tmp0 >= tmp1
    tmp3 = tl.full([1], 4, tl.int64)
    tmp4 = tmp0 < tmp3
    tmp5 = -1 + x0
    tmp6 = tmp5 >= tmp1
    tmp7 = tmp5 < tmp3
    tmp8 = tmp2 & tmp4
    tmp9 = tmp8 & tmp6
    tmp10 = tmp9 & tmp7
    tmp11 = tl.load(in_ptr0 + (-5 + x0 + 4 * x1 + 16 * x2), tmp10 & xmask,
        other=0.0)
    tl.store(out_ptr0 + x4, tmp11, xmask)


@triton.jit
def triton_poi_fused_convolution_relu_threshold_backward_1(in_out_ptr0,
    in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 64
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x3 = xindex
    x1 = xindex // 4 % 4
    tmp0 = tl.load(in_out_ptr0 + x3, xmask)
    tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tmp3 = tl.full([1], 0, tl.int32)
    tmp4 = triton_helpers.maximum(tmp3, tmp2)
    tmp5 = 0.0
    tmp6 = tmp4 <= tmp5
    tl.store(in_out_ptr0 + x3, tmp4, xmask)
    tl.store(out_ptr0 + x3, tmp6, xmask)


@triton.jit
def triton_poi_fused_convolution_relu_2(in_out_ptr0, in_ptr0, xnumel,
    XBLOCK: tl.constexpr):
    xnumel = 576
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x1 = xindex // 6 % 6
    x0 = xindex % 6
    x4 = xindex
    x2 = xindex // 36 % 4
    tmp19 = tl.load(in_out_ptr0 + x4, xmask)
    tmp20 = tl.load(in_ptr0 + x2, xmask, eviction_policy='evict_last')
    tmp0 = x1
    tmp1 = tl.full([1], 3, tl.int64)
    tmp2 = tmp0 >= tmp1
    tmp3 = x0
    tmp4 = tmp3 >= tmp1
    tmp5 = tmp4 & tmp2
    tmp6 = tl.load(in_out_ptr0 + x4, tmp5 & xmask, other=0.0)
    tmp7 = tl.load(in_ptr0 + x2, tmp5 & xmask, eviction_policy='evict_last',
        other=0.0)
    tmp8 = tmp6 + tmp7
    tmp9 = tl.full([1], 0, tl.int32)
    tmp10 = triton_helpers.maximum(tmp9, tmp8)
    tmp11 = tl.full(tmp10.shape, 0.0, tmp10.dtype)
    tmp12 = tl.where(tmp5, tmp10, tmp11)
    tmp13 = tl.load(in_out_ptr0 + x4, tmp2 & xmask, other=0.0)
    tmp14 = tl.load(in_ptr0 + x2, tmp2 & xmask, eviction_policy=
        'evict_last', other=0.0)
    tmp15 = tmp13 + tmp14
    tmp16 = tl.where(tmp4, tmp12, tmp15)
    tmp17 = tl.full(tmp16.shape, 0.0, tmp16.dtype)
    tmp18 = tl.where(tmp2, tmp16, tmp17)
    tmp21 = tmp19 + tmp20
    tmp22 = tl.where(tmp2, tmp18, tmp21)
    tl.store(in_out_ptr0 + x4, tmp22, xmask)


@triton.jit
def triton_poi_fused_threshold_backward_3(in_ptr0, out_ptr0, xnumel, XBLOCK:
    tl.constexpr):
    xnumel = 144
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 3
    x1 = xindex // 3 % 3
    x2 = xindex // 9
    x3 = xindex
    tmp0 = tl.load(in_ptr0 + (21 + x0 + 6 * x1 + 36 * x2), xmask)
    tmp1 = 0.0
    tmp2 = tmp0 <= tmp1
    tl.store(out_ptr0 + x3, tmp2, xmask)


def call(args):
    primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
    args.clear()
    assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(primals_2, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(primals_3, (4,), (1,))
    assert_size_stride(primals_4, (4, 4), (4, 1))
    assert_size_stride(primals_5, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(primals_6, (4,), (1,))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4, 6, 6), (144, 36, 6, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_constant_pad_nd_0[grid(576)](primals_1, buf0, 576,
            XBLOCK=256, num_warps=4, num_stages=1)
        del primals_1
        buf1 = extern_kernels.convolution(buf0, primals_2, stride=(2, 2),
            padding=(0, 0), dilation=(1, 1), transposed=False,
            output_padding=(0, 0), groups=1, bias=None)
        assert_size_stride(buf1, (4, 4, 2, 2), (16, 4, 2, 1))
        buf2 = buf1
        del buf1
        buf7 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.bool)
        triton_poi_fused_convolution_relu_threshold_backward_1[grid(64)](buf2,
            primals_3, buf7, 64, XBLOCK=64, num_warps=1, num_stages=1)
        del primals_3
        buf3 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
        extern_kernels.mm(primals_4, reinterpret_tensor(buf2, (4, 16), (16,
            1), 0), out=buf3)
        buf4 = extern_kernels.convolution(reinterpret_tensor(buf3, (4, 4, 2,
            2), (16, 4, 2, 1), 0), primals_5, stride=(2, 2), padding=(0, 0),
            dilation=(1, 1), transposed=True, output_padding=(0, 0), groups
            =1, bias=None)
        assert_size_stride(buf4, (4, 4, 6, 6), (144, 36, 6, 1))
        buf5 = buf4
        del buf4
        triton_poi_fused_convolution_relu_2[grid(576)](buf5, primals_6, 576,
            XBLOCK=128, num_warps=4, num_stages=1)
        del primals_6
        buf6 = empty_strided_cuda((4, 4, 3, 3), (36, 9, 3, 1), torch.bool)
        triton_poi_fused_threshold_backward_3[grid(144)](buf5, buf6, 144,
            XBLOCK=128, num_warps=4, num_stages=1)
    return reinterpret_tensor(buf5, (4, 4, 3, 3), (144, 36, 6, 1), 21
        ), reinterpret_tensor(buf2, (4, 16), (16, 1), 0
        ), buf3, primals_2, primals_5, buf0, reinterpret_tensor(buf3, (4, 4,
        2, 2), (16, 4, 2, 1), 0), buf6, reinterpret_tensor(primals_4, (4, 4
        ), (1, 4), 0), reinterpret_tensor(buf2, (16, 4), (1, 16), 0), buf7


class Conv2dSamePad(nn.Module):
    """
    Implement Tensorflow's 'SAME' padding mode in Conv2d.
    When an odd number, say `m`, of pixels are need to pad, Tensorflow will pad one more column at right or one more
    row at bottom. But Pytorch will pad `m+1` pixels, i.e., Pytorch always pads in both sides.
    So we can pad the tensor in the way of Tensorflow before call the Conv2d module.
    """

    def __init__(self, kernel_size, stride):
        super(Conv2dSamePad, self).__init__()
        self.kernel_size = kernel_size if type(kernel_size) in [list, tuple
            ] else [kernel_size, kernel_size]
        self.stride = stride if type(stride) in [list, tuple] else [stride,
            stride]

    def forward(self, x):
        in_height = x.size(2)
        in_width = x.size(3)
        out_height = math.ceil(float(in_height) / float(self.stride[0]))
        out_width = math.ceil(float(in_width) / float(self.stride[1]))
        pad_along_height = (out_height - 1) * self.stride[0
            ] + self.kernel_size[0] - in_height
        pad_along_width = (out_width - 1) * self.stride[1] + self.kernel_size[1
            ] - in_width
        pad_top = math.floor(pad_along_height / 2)
        pad_left = math.floor(pad_along_width / 2)
        pad_bottom = pad_along_height - pad_top
        pad_right = pad_along_width - pad_left
        return F.pad(x, [pad_left, pad_right, pad_top, pad_bottom],
            'constant', 0)


class ConvTranspose2dSamePad(nn.Module):
    """
    This module implements the "SAME" padding mode for ConvTranspose2d as in Tensorflow.
    A tensor with width w_in, feed it to ConvTranspose2d(ci, co, kernel, stride), the width of output tensor T_nopad:
        w_nopad = (w_in - 1) * stride + kernel
    If we use padding, i.e., ConvTranspose2d(ci, co, kernel, stride, padding, output_padding), the width of T_pad:
        w_pad = (w_in - 1) * stride + kernel - (2*padding - output_padding) = w_nopad - (2*padding - output_padding)
    Yes, in ConvTranspose2d, more padding, the resulting tensor is smaller, i.e., the padding is actually deleting row/col.
    If `pad`=(2*padding - output_padding) is odd, Pytorch deletes more columns in the left, i.e., the first ceil(pad/2) and
    last `pad - ceil(pad/2)` columns of T_nopad are deleted to get T_pad.
    In contrast, Tensorflow deletes more columns in the right, i.e., the first floor(pad/2) and last `pad - floor(pad/2)`
    columns are deleted.
    For the height, Pytorch deletes more rows at top, while Tensorflow at bottom.
    In practice, we usually want `w_pad = w_in * stride` or `w_pad = w_in * stride - 1`, i.e., the "SAME" padding mode
    in Tensorflow. To determine the value of `w_pad`, we should pass it to this function.
    So the number of columns to delete:
        pad = 2*padding - output_padding = w_nopad - w_pad
    If pad is even, we can directly set padding=pad/2 and output_padding=0 in ConvTranspose2d.
    If pad is odd, we can use ConvTranspose2d to get T_nopad, and then delete `pad` rows/columns by
    ourselves.
    This module should be called after the ConvTranspose2d module with shared kernel_size and stride values.
    """

    def __init__(self, output_size):
        super(ConvTranspose2dSamePad, self).__init__()
        self.output_size = output_size

    def forward(self, x):
        in_height = x.size(2)
        in_width = x.size(3)
        pad_height = in_height - self.output_size[0]
        pad_width = in_width - self.output_size[1]
        pad_top = pad_height // 2
        pad_bottom = pad_height - pad_top
        pad_left = pad_width // 2
        pad_right = pad_width - pad_left
        return x[:, :, pad_top:in_height - pad_bottom, pad_left:in_width -
            pad_right]


class ConvAE(nn.Module):

    def __init__(self, channels, kernels):
        """
        :param channels: a list containing all channels including the input image channel (1 for gray, 3 for RGB)
        :param kernels:  a list containing all kernel sizes, it should satisfy: len(kernels) = len(channels) - 1.
        """
        super(ConvAE, self).__init__()
        assert isinstance(channels, list) and isinstance(kernels, list)
        self.encoder = nn.Sequential()
        for i in range(1, len(channels)):
            self.encoder.add_module('pad%d' % i, Conv2dSamePad(kernels[i - 
                1], 2))
            self.encoder.add_module('conv%d' % i, nn.Conv2d(channels[i - 1],
                channels[i], kernel_size=kernels[i - 1], stride=2))
            self.encoder.add_module('relu%d' % i, nn.ReLU(True))
        self.decoder = nn.Sequential()
        channels = list(reversed(channels))
        kernels = list(reversed(kernels))
        sizes = [[12, 11], [24, 21], [48, 42]]
        for i in range(len(channels) - 1):
            self.decoder.add_module('deconv%d' % (i + 1), nn.
                ConvTranspose2d(channels[i], channels[i + 1], kernel_size=
                kernels[i], stride=2))
            self.decoder.add_module('padd%d' % i, ConvTranspose2dSamePad(
                sizes[i]))
            self.decoder.add_module('relud%d' % i, nn.ReLU(True))

    def forward(self, x):
        h = self.encoder(x)
        y = self.decoder(h)
        return y


class SelfExpression(nn.Module):

    def __init__(self, n):
        super(SelfExpression, self).__init__()
        self.Coefficient = nn.Parameter(0.0001 * torch.ones(n, n, dtype=
            torch.float32), requires_grad=True)

    def forward(self, x):
        y = torch.matmul(self.Coefficient, x)
        return y


class DSCNetNew(nn.Module):

    def __init__(self, channels, kernels, num_sample):
        super(DSCNetNew, self).__init__()
        self.n = num_sample
        self.ae = ConvAE(channels, kernels)
        self.self_expression = SelfExpression(self.n)

    def loss_fn(self, x, x_recon, z, z_recon, weight_coef, weight_selfExp):
        loss_ae = 0.5 * F.mse_loss(x_recon, x, reduction='sum')
        loss_coef = torch.sum(torch.pow(self.self_expression.Coefficient, 2))
        loss_selfExp = 0.5 * F.mse_loss(z_recon, z, reduction='sum')
        loss = (loss_ae + weight_coef * loss_coef + weight_selfExp *
            loss_selfExp)
        loss /= x.size(0)
        return loss

    def smoothLoss(self, z):
        Z = torch.pow(z.unsqueeze(1) - z.unsqueeze(0), 2).sum(-1)
        C = torch.abs(self.self_expression.Coefficient)
        C = 0.5 * (C + torch.transpose(C, 0, 1))
        C = C.fill_diagonal_(0)
        loss_smooth = (Z * C).sum() / z.shape[0]
        return loss_smooth

    def forward(self, input_0):
        primals_1 = self.ae.encoder.conv1.weight
        primals_3 = self.ae.encoder.conv1.bias
        primals_2 = self.ae.decoder.deconv1.weight
        primals_6 = self.ae.decoder.deconv1.bias
        primals_4 = self.self_expression.Coefficient
        primals_5 = input_0
        output = call([primals_1, primals_2, primals_3, primals_4,
            primals_5, primals_6])
        return output[0], output[1], output[2]


Measured latency_ms: 0.036279