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 libdevice
import torch.nn as nn
from torch.nn import 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_div_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex
    x1 = xindex // 4
    tmp0 = tl.load(in_ptr0 + x2, xmask)
    tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
    tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp9 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp2 = tmp1 * tmp1
    tmp4 = tmp3 * tmp3
    tmp5 = tmp2 + tmp4
    tmp7 = tmp6 * tmp6
    tmp8 = tmp5 + tmp7
    tmp10 = tmp9 * tmp9
    tmp11 = tmp8 + tmp10
    tmp12 = libdevice.sqrt(tmp11)
    tmp13 = 1e-12
    tmp14 = triton_helpers.maximum(tmp12, tmp13)
    tmp15 = tmp0 / tmp14
    tl.store(out_ptr0 + x2, tmp15, xmask)


@triton.jit
def triton_poi_fused_rsub_1(in_out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.load(in_out_ptr0 + x0, xmask)
    tmp1 = 1.0
    tmp2 = tmp1 - tmp0
    tl.store(in_out_ptr0 + x0, tmp2, xmask)


def call(args):
    arg0_1, arg1_1 = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4), (4, 1))
    assert_size_stride(arg1_1, (4, 4), (4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_div_0[grid(16)](arg0_1, buf0, 16, XBLOCK=16,
            num_warps=1, num_stages=1)
        del arg0_1
        buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        triton_poi_fused_div_0[grid(16)](arg1_1, buf1, 16, XBLOCK=16,
            num_warps=1, num_stages=1)
        del arg1_1
        buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        extern_kernels.mm(buf0, reinterpret_tensor(buf1, (4, 4), (1, 4), 0),
            out=buf2)
        del buf0
        del buf1
        buf3 = buf2
        del buf2
        triton_poi_fused_rsub_1[grid(16)](buf3, 16, XBLOCK=16, num_warps=1,
            num_stages=1)
    return buf3,


class OptimalTransport(nn.Module):

    @staticmethod
    def distance(batch1, batch2, dist_metric='cosine'):
        if dist_metric == 'cosine':
            batch1 = F.normalize(batch1, p=2, dim=1)
            batch2 = F.normalize(batch2, p=2, dim=1)
            dist_mat = 1 - torch.mm(batch1, batch2.t())
        elif dist_metric == 'euclidean':
            m, n = batch1.size(0), batch2.size(0)
            dist_mat = torch.pow(batch1, 2).sum(dim=1, keepdim=True).expand(m,
                n) + torch.pow(batch2, 2).sum(dim=1, keepdim=True).expand(n, m
                ).t()
            dist_mat.addmm_(1, -2, batch1, batch2.t())
        elif dist_metric == 'fast_euclidean':
            batch1 = batch1.unsqueeze(-2)
            batch2 = batch2.unsqueeze(-3)
            dist_mat = torch.sum(torch.abs(batch1 - batch2) ** 2, -1)
        else:
            raise ValueError(
                'Unknown cost function: {}. Expected to be one of [cosine | euclidean]'
                .format(dist_metric))
        return dist_mat


class SinkhornDivergenceNew(OptimalTransport):
    thre = 0.001

    def __init__(self, dist_metric='cosine', eps=0.01, max_iter=5,
        bp_to_sinkhorn=False):
        super().__init__()
        self.dist_metric = dist_metric
        self.eps = eps
        self.max_iter = max_iter
        self.bp_to_sinkhorn = bp_to_sinkhorn

    def transport_cost(self, x, y, return_pi=False):
        C = self.distance(x, y, dist_metric=self.dist_metric)
        pi = self.sinkhorn_iterate(C, self.eps, self.max_iter, self.thre)
        if not self.bp_to_sinkhorn:
            pi = pi.detach()
        cost = torch.sum(pi * C)
        if return_pi:
            return cost, pi
        return cost

    @staticmethod
    def sinkhorn_iterate(C, eps, max_iter, thre):
        nx, ny = C.shape
        mu = torch.ones(nx, dtype=C.dtype, device=C.device) * (1.0 / nx)
        nu = torch.ones(ny, dtype=C.dtype, device=C.device) * (1.0 / ny)
        u = torch.zeros_like(mu)
        v = torch.zeros_like(nu)

        def M(_C, _u, _v):
            """Modified cost for logarithmic updates.
            Eq: M_{ij} = (-c_{ij} + u_i + v_j) / epsilon
            """
            return (-_C + _u.unsqueeze(-1) + _v.unsqueeze(-2)) / eps
        real_iter = 0
        for i in range(max_iter):
            u0 = u
            u = eps * (torch.log(mu + 1e-08) - torch.logsumexp(M(C, u, v),
                dim=1)) + u
            v = eps * (torch.log(nu + 1e-08) - torch.logsumexp(M(C, u, v).
                permute(1, 0), dim=1)) + v
            err = (u - u0).abs().sum()
            real_iter += 1
            if err.item() < thre:
                break
        return torch.exp(M(C, u, v))

    def forward(self, input_0, input_1):
        arg0_1 = input_0
        arg1_1 = input_1
        output = call([arg0_1, arg1_1])
        return output[0]


Measured latency_ms: 0.033715