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.triton_helpers import math as tl_math
import torch.nn as nn
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_per_fused_div_mul_norm_sigmoid_0(in_out_ptr0, in_ptr0, in_ptr1,
    out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr):
    xnumel = 4
    RBLOCK: tl.constexpr = 64
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    rindex = tl.arange(0, RBLOCK)[None, :]
    tl.full([XBLOCK, RBLOCK], True, tl.int1)
    r1 = rindex
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
    tmp7 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
    tmp1 = tl_math.abs(tmp0)
    tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
    tmp4 = tl.where(xmask, tmp2, 0)
    tmp5 = tl.sum(tmp4, 1)[:, None]
    tmp6 = tmp0 / tmp5
    tmp8 = tl.sigmoid(tmp7)
    tmp9 = tmp6 * tmp8
    tl.debug_barrier()
    tl.store(in_out_ptr0 + x0, tmp5, xmask)
    tl.store(out_ptr0 + (r1 + 64 * x0), tmp9, xmask)


@triton.jit
def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
    .constexpr):
    xnumel = 1296
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x3 = xindex
    x1 = xindex // 81 % 4
    tmp0 = tl.load(in_out_ptr0 + x3, xmask)
    tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tl.store(in_out_ptr0 + x3, tmp2, xmask)


def call(args):
    primals_1, primals_2, primals_3, primals_4 = args
    args.clear()
    assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(primals_2, (4, 1, 1, 1), (1, 1, 1, 1))
    assert_size_stride(primals_3, (4,), (1,))
    assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4,), (1,), torch.float32)
        buf1 = buf0
        del buf0
        buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        get_raw_stream(0)
        triton_per_fused_div_mul_norm_sigmoid_0[grid(4)](buf1, primals_1,
            primals_2, buf2, 4, 64, XBLOCK=1, num_warps=2, num_stages=1)
        buf3 = extern_kernels.convolution(primals_4, buf2, stride=(1, 1),
            padding=(4, 4), dilation=(1, 1), transposed=False,
            output_padding=(0, 0), groups=1, bias=None)
        assert_size_stride(buf3, (4, 4, 9, 9), (324, 81, 9, 1))
        buf4 = buf3
        del buf3
        triton_poi_fused_convolution_1[grid(1296)](buf4, primals_3, 1296,
            XBLOCK=128, num_warps=4, num_stages=1)
        del primals_3
    return buf4, primals_1, primals_2, primals_4, reinterpret_tensor(buf1,
        (4, 1, 1, 1), (1, 1, 1, 1), 0), buf2


def _max_except_dim(input, dim):
    maxed = input
    for axis in range(input.ndimension() - 1, dim, -1):
        maxed, _ = maxed.max(axis, keepdim=True)
    for axis in range(dim - 1, -1, -1):
        maxed, _ = maxed.max(axis, keepdim=True)
    return maxed


def _norm_except_dim(w, norm_type, dim):
    if norm_type == 1 or norm_type == 2:
        return torch.norm_except_dim(w, norm_type, dim)
    elif norm_type == float('inf'):
        return _max_except_dim(w, dim)


def operator_norm_settings(domain, codomain):
    if domain == 1 and codomain == 1:
        max_across_input_dims = True
        norm_type = 1
    elif domain == 1 and codomain == 2:
        max_across_input_dims = True
        norm_type = 2
    elif domain == 1 and codomain == float('inf'):
        max_across_input_dims = True
        norm_type = float('inf')
    elif domain == 2 and codomain == float('inf'):
        max_across_input_dims = False
        norm_type = 2
    elif domain == float('inf') and codomain == float('inf'):
        max_across_input_dims = False
        norm_type = 1
    else:
        raise ValueError('Unknown combination of domain "{}" and codomain "{}"'
            .format(domain, codomain))
    return max_across_input_dims, norm_type


def _logit(p):
    p = torch.max(torch.ones(1) * 0.1, torch.min(torch.ones(1) * 0.9, p))
    return torch.log(p + 1e-10) + torch.log(1 - p + 1e-10)


class LipNormConv2dNew(nn.Conv2d):
    """Lipschitz constant defined using operator norms."""

    def __init__(self, in_channels, out_channels, kernel_size, stride,
        padding, bias=True, coeff=0.97, domain=float('inf'), codomain=float
        ('inf'), local_constraint=True, **unused_kwargs):
        del unused_kwargs
        super(LipNormConv2dNew, self).__init__(in_channels, out_channels,
            kernel_size, stride, padding, bias)
        self.coeff = coeff
        self.domain = domain
        self.codomain = codomain
        self.local_constraint = local_constraint
        max_across_input_dims, self.norm_type = operator_norm_settings(self
            .domain, self.codomain)
        self.max_across_dim = 1 if max_across_input_dims else 0
        with torch.no_grad():
            w_scale = _norm_except_dim(self.weight, self.norm_type, dim=
                self.max_across_dim)
            if not self.local_constraint:
                w_scale = w_scale.max()
            self.scale = nn.Parameter(_logit(w_scale / self.coeff))

    def compute_weight(self):
        w_scale = _norm_except_dim(self.weight, self.norm_type, dim=self.
            max_across_dim)
        if not self.local_constraint:
            w_scale = w_scale.max()
        return self.weight / w_scale * torch.sigmoid(self.scale)

    def extra_repr(self):
        s = super(LipNormConv2dNew, self).extra_repr()
        return s + ', coeff={}, domain={}, codomain={}, local={}'.format(self
            .coeff, self.domain, self.codomain, self.local_constraint)

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


Measured latency_ms: 0.013933