entry_point
stringlengths
1
65
original_triton_python_code
stringlengths
208
619k
optimised_triton_code
stringlengths
1.15k
275k
repo_name
stringlengths
7
115
module_name
stringlengths
1
65
synthetic
bool
1 class
uuid
int64
0
18.5k
licenses
listlengths
1
6
stars
int64
0
19.8k
sha
stringlengths
40
40
repo_link
stringlengths
72
180
TransposeGatedConv2d
import torch import torch.nn as nn from torch.nn import functional as F from torch.nn import Parameter def l2normalize(v, eps=1e-12): return v / (v.norm() + eps) class SpectralNorm(nn.Module): def __init__(self, module, name='weight', power_iterations=1): super(SpectralNorm, self).__init__() self.module = module self.name = name self.power_iterations = power_iterations if not self._made_params(): self._make_params() def _update_u_v(self): u = getattr(self.module, self.name + '_u') v = getattr(self.module, self.name + '_v') w = getattr(self.module, self.name + '_bar') height = w.data.shape[0] for _ in range(self.power_iterations): v.data = l2normalize(torch.mm(torch.t(w.view(height, -1).data), u.data.view(-1, 1)).squeeze(1)) u.data = l2normalize(torch.mm(w.view(height, -1).data, v.data. view(-1, 1)).squeeze(1)) sigma = u.data * w.view(height, -1).data.mm(v.data.view(-1, 1) ).squeeze(1) sigma = sigma.sum() setattr(self.module, self.name, w / sigma.expand_as(w)) def _made_params(self): try: getattr(self.module, self.name + '_u') getattr(self.module, self.name + '_v') getattr(self.module, self.name + '_bar') return True except AttributeError: return False def _make_params(self): w = getattr(self.module, self.name) height = w.data.shape[0] width = w.view(height, -1).data.shape[1] u = Parameter(w.data.new(height).normal_(0, 1), requires_grad=False) v = Parameter(w.data.new(width).normal_(0, 1), requires_grad=False) u.data = l2normalize(u.data) v.data = l2normalize(v.data) w_bar = Parameter(w.data) del self.module._parameters[self.name] self.module.register_parameter(self.name + '_u', u) self.module.register_parameter(self.name + '_v', v) self.module.register_parameter(self.name + '_bar', w_bar) def forward(self, *args): self._update_u_v() return self.module.forward(*args) class GatedConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, activation='elu', sn=False): super(GatedConv2d, self).__init__() self.pad = nn.ZeroPad2d(padding) if activation == 'relu': self.activation = nn.ReLU(inplace=True) elif activation == 'lrelu': self.activation = nn.LeakyReLU(0.2, inplace=True) elif activation == 'elu': self.activation = nn.ELU() elif activation == 'selu': self.activation = nn.SELU(inplace=True) elif activation == 'tanh': self.activation = nn.Tanh() elif activation == 'sigmoid': self.activation = nn.Sigmoid() elif activation == 'none': self.activation = None else: assert 0, 'Unsupported activation: {}'.format(activation) if sn: self.conv2d = SpectralNorm(nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=0, dilation=dilation)) self.mask_conv2d = SpectralNorm(nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=0, dilation= dilation)) else: self.conv2d = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=0, dilation=dilation) self.mask_conv2d = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=0, dilation=dilation) self.sigmoid = torch.nn.Sigmoid() def forward(self, x): x = self.pad(x) conv = self.conv2d(x) if self.activation: conv = self.activation(conv) mask = self.mask_conv2d(x) gated_mask = self.sigmoid(mask) x = conv * gated_mask return x class TransposeGatedConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, activation='lrelu', sn=True, scale_factor=2): super(TransposeGatedConv2d, self).__init__() self.scale_factor = scale_factor self.gated_conv2d = GatedConv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, activation, sn) def forward(self, x): x = F.interpolate(x, scale_factor=self.scale_factor) x = self.gated_conv2d(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4}]
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 libdevice import torch.nn as nn from torch.nn import Parameter 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__unsafe_index_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 1024 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 8 % 8 x0 = xindex % 8 x2 = xindex // 64 x4 = xindex tmp0 = x1 tmp1 = tmp0.to(tl.float32) tmp2 = 0.5 tmp3 = tmp1 * tmp2 tmp4 = tmp3.to(tl.int32) tmp5 = x0 tmp6 = tmp5.to(tl.float32) tmp7 = tmp6 * tmp2 tmp8 = tmp7.to(tl.int32) tmp9 = tl.load(in_ptr0 + (tmp8 + 4 * tmp4 + 16 * x2), xmask, eviction_policy='evict_last') tl.store(out_ptr0 + x4, tmp9, xmask) @triton.jit def triton_per_fused_add_div_linalg_vector_norm_1(in_ptr0, out_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 64 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tmp0 * tmp0 tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp4 = tl.sum(tmp2, 1)[:, None] tmp5 = libdevice.sqrt(tmp4) tmp6 = 1e-12 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tl.store(out_ptr1 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp8, None) @triton.jit def triton_per_fused_add_div_linalg_vector_norm_mul_sum_2(in_ptr0, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 4 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tmp0 * tmp0 tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp4 = tl.sum(tmp2, 1)[:, None] tmp5 = libdevice.sqrt(tmp4) tmp6 = 1e-12 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tmp9 = tmp8 * tmp0 tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK]) tmp12 = tl.sum(tmp10, 1)[:, None] tl.store(out_ptr2 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp8, None) tl.store(out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp12, None) @triton.jit def triton_poi_fused_div_3(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = tl.load(in_ptr1 + 0) tmp2 = tl.broadcast_to(tmp1, [XBLOCK]) tmp3 = tmp0 / tmp2 tl.store(out_ptr0 + x0, tmp3, xmask) @triton.jit def triton_poi_fused_convolution_leaky_relu_mul_sigmoid_4(in_out_ptr0, in_out_ptr1, in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 400 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 25 % 4 tmp0 = tl.load(in_out_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_out_ptr1 + x3, xmask) tmp4 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp5 = tmp3 + tmp4 tmp6 = 0.0 tmp7 = tmp2 > tmp6 tmp8 = 0.2 tmp9 = tmp2 * tmp8 tmp10 = tl.where(tmp7, tmp2, tmp9) tmp11 = tl.sigmoid(tmp5) tmp12 = tmp10 * tmp11 tl.store(in_out_ptr0 + x3, tmp2, xmask) tl.store(in_out_ptr1 + x3, tmp5, xmask) tl.store(out_ptr0 + x3, tmp12, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9) = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (64,), (1,)) assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (4,), (1,)) assert_size_stride(primals_7, (64,), (1,)) assert_size_stride(primals_8, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_9, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 8, 8), (256, 64, 8, 1), torch.float32) get_raw_stream(0) triton_poi_fused__unsafe_index_0[grid(1024)](primals_1, buf0, 1024, XBLOCK=256, num_warps=4, num_stages=1) del primals_1 buf1 = empty_strided_cuda((64, 1), (1, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_4, (64, 4), (1, 64), 0 ), reinterpret_tensor(primals_2, (4, 1), (1, 1), 0), out=buf1) buf3 = empty_strided_cuda((64,), (1,), torch.float32) triton_per_fused_add_div_linalg_vector_norm_1[grid(1)](buf1, buf3, 1, 64, XBLOCK=1, num_warps=2, num_stages=1) buf4 = empty_strided_cuda((4, 1), (1, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_4, (4, 64), (64, 1), 0 ), reinterpret_tensor(buf3, (64, 1), (1, 0), 0), out=buf4) buf6 = empty_strided_cuda((), (), torch.float32) buf20 = empty_strided_cuda((4,), (1,), torch.float32) triton_per_fused_add_div_linalg_vector_norm_mul_sum_2[grid(1)](buf4, buf6, buf20, 1, 4, XBLOCK=1, num_warps=2, num_stages=1) buf7 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_div_3[grid(256)](primals_4, buf6, buf7, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_4 buf8 = extern_kernels.convolution(buf0, buf7, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf8, (4, 4, 5, 5), (100, 25, 5, 1)) buf10 = empty_strided_cuda((64, 1), (1, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_8, (64, 4), (1, 64), 0 ), reinterpret_tensor(primals_6, (4, 1), (1, 1), 0), out=buf10) buf12 = empty_strided_cuda((64,), (1,), torch.float32) triton_per_fused_add_div_linalg_vector_norm_1[grid(1)](buf10, buf12, 1, 64, XBLOCK=1, num_warps=2, num_stages=1) buf13 = empty_strided_cuda((4, 1), (1, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_8, (4, 64), (64, 1), 0 ), reinterpret_tensor(buf12, (64, 1), (1, 0), 0), out=buf13) buf15 = empty_strided_cuda((), (), torch.float32) buf27 = empty_strided_cuda((4,), (1,), torch.float32) triton_per_fused_add_div_linalg_vector_norm_mul_sum_2[grid(1)](buf13, buf15, buf27, 1, 4, XBLOCK=1, num_warps=2, num_stages=1) buf16 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_div_3[grid(256)](primals_8, buf15, buf16, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_8 buf17 = extern_kernels.convolution(buf0, buf16, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf17, (4, 4, 5, 5), (100, 25, 5, 1)) buf9 = buf8 del buf8 buf18 = buf17 del buf17 buf19 = empty_strided_cuda((4, 4, 5, 5), (100, 25, 5, 1), torch.float32 ) triton_poi_fused_convolution_leaky_relu_mul_sigmoid_4[grid(400)](buf9, buf18, primals_5, primals_9, buf19, 400, XBLOCK=128, num_warps= 4, num_stages=1) del primals_5 del primals_9 buf21 = torch.ops.aten.set_.source_Tensor(primals_2, buf20) assert_size_stride(buf21, (4,), (1,)) del buf1 del primals_2 buf24 = torch.ops.aten.set_.source_Tensor(primals_3, buf3) assert_size_stride(buf24, (64,), (1,)) del buf4 del primals_3 buf28 = torch.ops.aten.set_.source_Tensor(primals_6, buf27) assert_size_stride(buf28, (4,), (1,)) del buf10 del primals_6 buf31 = torch.ops.aten.set_.source_Tensor(primals_7, buf12) assert_size_stride(buf31, (64,), (1,)) del buf13 del primals_7 return buf19, buf7, buf16, buf0, buf6, buf7, buf9, buf15, buf16, buf18 def l2normalize(v, eps=1e-12): return v / (v.norm() + eps) class SpectralNorm(nn.Module): def __init__(self, module, name='weight', power_iterations=1): super(SpectralNorm, self).__init__() self.module = module self.name = name self.power_iterations = power_iterations if not self._made_params(): self._make_params() def _update_u_v(self): u = getattr(self.module, self.name + '_u') v = getattr(self.module, self.name + '_v') w = getattr(self.module, self.name + '_bar') height = w.data.shape[0] for _ in range(self.power_iterations): v.data = l2normalize(torch.mm(torch.t(w.view(height, -1).data), u.data.view(-1, 1)).squeeze(1)) u.data = l2normalize(torch.mm(w.view(height, -1).data, v.data. view(-1, 1)).squeeze(1)) sigma = u.data * w.view(height, -1).data.mm(v.data.view(-1, 1) ).squeeze(1) sigma = sigma.sum() setattr(self.module, self.name, w / sigma.expand_as(w)) def _made_params(self): try: getattr(self.module, self.name + '_u') getattr(self.module, self.name + '_v') getattr(self.module, self.name + '_bar') return True except AttributeError: return False def _make_params(self): w = getattr(self.module, self.name) height = w.data.shape[0] width = w.view(height, -1).data.shape[1] u = Parameter(w.data.new(height).normal_(0, 1), requires_grad=False) v = Parameter(w.data.new(width).normal_(0, 1), requires_grad=False) u.data = l2normalize(u.data) v.data = l2normalize(v.data) w_bar = Parameter(w.data) del self.module._parameters[self.name] self.module.register_parameter(self.name + '_u', u) self.module.register_parameter(self.name + '_v', v) self.module.register_parameter(self.name + '_bar', w_bar) def forward(self, *args): self._update_u_v() return self.module.forward(*args) class GatedConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, activation='elu', sn=False): super(GatedConv2d, self).__init__() self.pad = nn.ZeroPad2d(padding) if activation == 'relu': self.activation = nn.ReLU(inplace=True) elif activation == 'lrelu': self.activation = nn.LeakyReLU(0.2, inplace=True) elif activation == 'elu': self.activation = nn.ELU() elif activation == 'selu': self.activation = nn.SELU(inplace=True) elif activation == 'tanh': self.activation = nn.Tanh() elif activation == 'sigmoid': self.activation = nn.Sigmoid() elif activation == 'none': self.activation = None else: assert 0, 'Unsupported activation: {}'.format(activation) if sn: self.conv2d = SpectralNorm(nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=0, dilation=dilation)) self.mask_conv2d = SpectralNorm(nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=0, dilation= dilation)) else: self.conv2d = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=0, dilation=dilation) self.mask_conv2d = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding=0, dilation=dilation) self.sigmoid = torch.nn.Sigmoid() def forward(self, x): x = self.pad(x) conv = self.conv2d(x) if self.activation: conv = self.activation(conv) mask = self.mask_conv2d(x) gated_mask = self.sigmoid(mask) x = conv * gated_mask return x class TransposeGatedConv2dNew(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, activation='lrelu', sn=True, scale_factor=2): super(TransposeGatedConv2dNew, self).__init__() self.scale_factor = scale_factor self.gated_conv2d = GatedConv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, activation, sn) def forward(self, input_0): primals_2 = self.gated_conv2d.conv2d.module.bias primals_5 = self.gated_conv2d.conv2d.module.weight_u primals_3 = self.gated_conv2d.conv2d.module.weight_v primals_1 = self.gated_conv2d.conv2d.module.weight_bar primals_6 = self.gated_conv2d.mask_conv2d.module.bias primals_9 = self.gated_conv2d.mask_conv2d.module.weight_u primals_7 = self.gated_conv2d.mask_conv2d.module.weight_v primals_4 = self.gated_conv2d.mask_conv2d.module.weight_bar primals_8 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9]) return output[0]
delldu/DeepFillv2
TransposeGatedConv2d
false
6,565
[ "MIT" ]
1
a564b9589c1b42bcdddd3d7601f4059c4594a439
https://github.com/delldu/DeepFillv2/tree/a564b9589c1b42bcdddd3d7601f4059c4594a439
WSDiceLoss
import torch import torch.utils.data import torch.nn as nn import torch.nn.parallel class WSDiceLoss(nn.Module): def __init__(self, smooth=100.0, power=2.0, v2=0.85, v1=0.15): super().__init__() self.smooth = smooth self.power = power self.v2 = v2 self.v1 = v1 def dice_loss(self, pred, target): iflat = pred.reshape(pred.shape[0], -1) tflat = target.reshape(pred.shape[0], -1) wt = tflat * (self.v2 - self.v1) + self.v1 g_pred = wt * (2 * iflat - 1) g = wt * (2 * tflat - 1) intersection = (g_pred * g).sum(-1) loss = 1 - (2.0 * intersection + self.smooth) / ((g_pred ** self. power).sum(-1) + (g ** self.power).sum(-1) + self.smooth) return loss.mean() def forward(self, pred, target, weight_mask=None): loss = self.dice_loss(pred, target) return loss def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 import torch.utils.data import torch.nn as nn import torch.nn.parallel assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_add_mul_pow_sub_sum_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1, out_ptr2, 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) tmp5 = tl.load(in_ptr1 + (r1 + 64 * x0), xmask, other=0.0) tmp1 = 0.7 tmp2 = tmp0 * tmp1 tmp3 = 0.15 tmp4 = tmp2 + tmp3 tmp6 = 2.0 tmp7 = tmp5 * tmp6 tmp8 = 1.0 tmp9 = tmp7 - tmp8 tmp10 = tmp4 * tmp9 tmp11 = tmp0 * tmp6 tmp12 = tmp11 - tmp8 tmp13 = tmp4 * tmp12 tmp14 = tmp10 * tmp13 tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK]) tmp17 = tl.where(xmask, tmp15, 0) tmp18 = tl.sum(tmp17, 1)[:, None] tmp19 = tmp10 * tmp10 tmp20 = tl.broadcast_to(tmp19, [XBLOCK, RBLOCK]) tmp22 = tl.where(xmask, tmp20, 0) tmp23 = tl.sum(tmp22, 1)[:, None] tmp24 = tmp13 * tmp13 tmp25 = tl.broadcast_to(tmp24, [XBLOCK, RBLOCK]) tmp27 = tl.where(xmask, tmp25, 0) tmp28 = tl.sum(tmp27, 1)[:, None] tl.store(out_ptr0 + x0, tmp18, xmask) tl.store(out_ptr1 + x0, tmp23, xmask) tl.store(out_ptr2 + x0, tmp28, xmask) @triton.jit def triton_per_fused_add_div_mean_mul_rsub_1(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 4 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp5 = tl.load(in_ptr1 + r0, None) tmp6 = tl.load(in_ptr2 + r0, None) tmp1 = 2.0 tmp2 = tmp0 * tmp1 tmp3 = 100.0 tmp4 = tmp2 + tmp3 tmp7 = tmp5 + tmp6 tmp8 = tmp7 + tmp3 tmp9 = tmp4 / tmp8 tmp10 = 1.0 tmp11 = tmp10 - tmp9 tmp12 = tl.broadcast_to(tmp11, [XBLOCK, RBLOCK]) tmp14 = tl.sum(tmp12, 1)[:, None] tmp15 = 4.0 tmp16 = tmp14 / tmp15 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp16, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (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 = empty_strided_cuda((4,), (1,), torch.float32) buf2 = empty_strided_cuda((4,), (1,), torch.float32) get_raw_stream(0) triton_per_fused_add_mul_pow_sub_sum_0[grid(4)](arg1_1, arg0_1, buf0, buf1, buf2, 4, 64, XBLOCK=1, num_warps=2, num_stages=1) del arg0_1 del arg1_1 buf3 = empty_strided_cuda((), (), torch.float32) buf4 = buf3 del buf3 triton_per_fused_add_div_mean_mul_rsub_1[grid(1)](buf4, buf0, buf1, buf2, 1, 4, XBLOCK=1, num_warps=2, num_stages=1) del buf0 del buf1 del buf2 return buf4, class WSDiceLossNew(nn.Module): def __init__(self, smooth=100.0, power=2.0, v2=0.85, v1=0.15): super().__init__() self.smooth = smooth self.power = power self.v2 = v2 self.v1 = v1 def dice_loss(self, pred, target): iflat = pred.reshape(pred.shape[0], -1) tflat = target.reshape(pred.shape[0], -1) wt = tflat * (self.v2 - self.v1) + self.v1 g_pred = wt * (2 * iflat - 1) g = wt * (2 * tflat - 1) intersection = (g_pred * g).sum(-1) loss = 1 - (2.0 * intersection + self.smooth) / ((g_pred ** self. power).sum(-1) + (g ** self.power).sum(-1) + self.smooth) return loss.mean() def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
devaansh100/pytorch_connectomics
WSDiceLoss
false
6,566
[ "MIT" ]
1
b1e4b16b0480546ea806d14876208080815ed964
https://github.com/devaansh100/pytorch_connectomics/tree/b1e4b16b0480546ea806d14876208080815ed964
QuantizableHSigmoid
import torch import torch.nn as nn import torch.quantization class QuantizableHSigmoid(nn.Module): """Hard Sigmoid for quantization.""" def __init__(self, inplace: 'bool'=True) ->None: """Initialize.""" super(QuantizableHSigmoid, self).__init__() self.relu6 = nn.ReLU6(inplace=inplace) self.add_scalar = nn.quantized.FloatFunctional() self.mul_scalar = nn.quantized.FloatFunctional() def forward(self, x: 'torch.Tensor') ->torch.Tensor: """Forward.""" x = self.add_scalar.add_scalar(x, 3.0) x = self.relu6(x) x = self.mul_scalar.mul_scalar(x, 1 / 6) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 torch.nn as nn import torch.quantization assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_add_hardtanh_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 3.0 tmp2 = tmp0 + tmp1 tmp3 = 0.0 tmp4 = triton_helpers.maximum(tmp2, tmp3) tmp5 = 6.0 tmp6 = triton_helpers.minimum(tmp4, tmp5) tmp7 = 0.16666666666666666 tmp8 = tmp6 * tmp7 tl.store(out_ptr0 + x0, tmp8, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_hardtanh_mul_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 return buf0, class QuantizableHSigmoidNew(nn.Module): """Hard Sigmoid for quantization.""" def __init__(self, inplace: 'bool'=True) ->None: """Initialize.""" super(QuantizableHSigmoidNew, self).__init__() self.relu6 = nn.ReLU6(inplace=inplace) self.add_scalar = nn.quantized.FloatFunctional() self.mul_scalar = nn.quantized.FloatFunctional() def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
dhlee347/model_compression
QuantizableHSigmoid
false
6,567
[ "MIT" ]
1
274b85ff56d81f0b7cf6907cbc1bd10e16cdb956
https://github.com/dhlee347/model_compression/tree/274b85ff56d81f0b7cf6907cbc1bd10e16cdb956
HSigmoid
import torch import torch.nn as nn import torch.quantization class HSigmoid(nn.Module): """Hard Sigmoid.""" def __init__(self, inplace: 'bool'=True) ->None: """Initialize.""" super(HSigmoid, self).__init__() self.relu6 = nn.ReLU6(inplace=inplace) def forward(self, x: 'torch.Tensor') ->torch.Tensor: """Forward.""" x = self.relu6(x + 3) / 6 return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 torch.nn as nn import torch.quantization assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_add_div_hardtanh_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 3.0 tmp2 = tmp0 + tmp1 tmp3 = 0.0 tmp4 = triton_helpers.maximum(tmp2, tmp3) tmp5 = 6.0 tmp6 = triton_helpers.minimum(tmp4, tmp5) tmp7 = 0.16666666666666666 tmp8 = tmp6 * tmp7 tl.store(out_ptr0 + x0, tmp8, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_div_hardtanh_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 return buf0, class HSigmoidNew(nn.Module): """Hard Sigmoid.""" def __init__(self, inplace: 'bool'=True) ->None: """Initialize.""" super(HSigmoidNew, self).__init__() self.relu6 = nn.ReLU6(inplace=inplace) def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
dhlee347/model_compression
HSigmoid
false
6,568
[ "MIT" ]
1
274b85ff56d81f0b7cf6907cbc1bd10e16cdb956
https://github.com/dhlee347/model_compression/tree/274b85ff56d81f0b7cf6907cbc1bd10e16cdb956
WeightedCE
import torch from typing import Optional from typing import List import torch.utils.data import torch.nn as nn import torch.nn.functional as F import torch.nn.parallel class WeightedCE(nn.Module): """Mask weighted multi-class cross-entropy (CE) loss. """ def __init__(self, class_weight: 'Optional[List[float]]'=None): super().__init__() self.class_weight = None if class_weight is not None: self.class_weight = torch.tensor(class_weight) def forward(self, pred, target, weight_mask=None): if self.class_weight is not None: self.class_weight = self.class_weight loss = F.cross_entropy(pred, target, weight=self.class_weight, reduction='none') if weight_mask is not None: loss = loss * weight_mask return loss.mean() def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 from typing import Optional from typing import List import torch.utils.data import torch.nn as nn import torch.nn.parallel assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x0 = xindex % 16 x2 = xindex // 64 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp0 - tmp7 tl.store(out_ptr0 + x3, tmp8, xmask) @triton.jit def triton_per_fused__log_softmax_mean_mul_neg_sum_1(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 64 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex % 16 r1 = rindex // 16 tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None) tmp2 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None) tmp5 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None) tmp8 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None) tmp13 = tl.load(in_ptr1 + (r0 + 64 * r1), None) tmp16 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None) tmp20 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None) tmp24 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None) tmp1 = tl_math.exp(tmp0) tmp3 = tl_math.exp(tmp2) tmp4 = tmp1 + tmp3 tmp6 = tl_math.exp(tmp5) tmp7 = tmp4 + tmp6 tmp9 = tl_math.exp(tmp8) tmp10 = tmp7 + tmp9 tmp11 = tl_math.log(tmp10) tmp12 = tmp0 - tmp11 tmp14 = tmp12 * tmp13 tmp15 = tmp2 - tmp11 tmp17 = tmp15 * tmp16 tmp18 = tmp14 + tmp17 tmp19 = tmp5 - tmp11 tmp21 = tmp19 * tmp20 tmp22 = tmp18 + tmp21 tmp23 = tmp8 - tmp11 tmp25 = tmp23 * tmp24 tmp26 = tmp22 + tmp25 tmp27 = -tmp26 tmp28 = tl.broadcast_to(tmp27, [XBLOCK, RBLOCK]) tmp30 = tl.sum(tmp28, 1)[:, None] tmp31 = 64.0 tmp32 = tmp30 / tmp31 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp32, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused__log_softmax_0[grid(256)](arg1_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg1_1 buf1 = empty_strided_cuda((), (), torch.float32) buf2 = buf1 del buf1 triton_per_fused__log_softmax_mean_mul_neg_sum_1[grid(1)](buf2, buf0, arg0_1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1) del arg0_1 del buf0 return buf2, class WeightedCENew(nn.Module): """Mask weighted multi-class cross-entropy (CE) loss. """ def __init__(self, class_weight: 'Optional[List[float]]'=None): super().__init__() self.class_weight = None if class_weight is not None: self.class_weight = torch.tensor(class_weight) def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
devaansh100/pytorch_connectomics
WeightedCE
false
6,569
[ "MIT" ]
1
b1e4b16b0480546ea806d14876208080815ed964
https://github.com/devaansh100/pytorch_connectomics/tree/b1e4b16b0480546ea806d14876208080815ed964
QuantizableHSwish
import torch import torch.nn as nn import torch.quantization class QuantizableHSigmoid(nn.Module): """Hard Sigmoid for quantization.""" def __init__(self, inplace: 'bool'=True) ->None: """Initialize.""" super(QuantizableHSigmoid, self).__init__() self.relu6 = nn.ReLU6(inplace=inplace) self.add_scalar = nn.quantized.FloatFunctional() self.mul_scalar = nn.quantized.FloatFunctional() def forward(self, x: 'torch.Tensor') ->torch.Tensor: """Forward.""" x = self.add_scalar.add_scalar(x, 3.0) x = self.relu6(x) x = self.mul_scalar.mul_scalar(x, 1 / 6) return x class QuantizableHSwish(nn.Module): """Hard Swish for quantization.""" def __init__(self, inplace: 'bool'=True) ->None: """Initialize.""" super(QuantizableHSwish, self).__init__() self.hsig = QuantizableHSigmoid(inplace=inplace) self.mul = nn.quantized.FloatFunctional() def forward(self, x: 'torch.Tensor') ->torch.Tensor: """Forward.""" return self.mul.mul(x, self.hsig(x)) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 torch.nn as nn import torch.quantization assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_add_hardtanh_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 3.0 tmp2 = tmp0 + tmp1 tmp3 = 0.0 tmp4 = triton_helpers.maximum(tmp2, tmp3) tmp5 = 6.0 tmp6 = triton_helpers.minimum(tmp4, tmp5) tmp7 = 0.16666666666666666 tmp8 = tmp6 * tmp7 tmp9 = tmp0 * tmp8 tl.store(out_ptr0 + x0, tmp9, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_hardtanh_mul_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 return buf0, class QuantizableHSigmoid(nn.Module): """Hard Sigmoid for quantization.""" def __init__(self, inplace: 'bool'=True) ->None: """Initialize.""" super(QuantizableHSigmoid, self).__init__() self.relu6 = nn.ReLU6(inplace=inplace) self.add_scalar = nn.quantized.FloatFunctional() self.mul_scalar = nn.quantized.FloatFunctional() def forward(self, x: 'torch.Tensor') ->torch.Tensor: """Forward.""" x = self.add_scalar.add_scalar(x, 3.0) x = self.relu6(x) x = self.mul_scalar.mul_scalar(x, 1 / 6) return x class QuantizableHSwishNew(nn.Module): """Hard Swish for quantization.""" def __init__(self, inplace: 'bool'=True) ->None: """Initialize.""" super(QuantizableHSwishNew, self).__init__() self.hsig = QuantizableHSigmoid(inplace=inplace) self.mul = nn.quantized.FloatFunctional() def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
dhlee347/model_compression
QuantizableHSwish
false
6,570
[ "MIT" ]
1
274b85ff56d81f0b7cf6907cbc1bd10e16cdb956
https://github.com/dhlee347/model_compression/tree/274b85ff56d81f0b7cf6907cbc1bd10e16cdb956
SEModule
import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict import torch.utils.data def make_divisible(v, divisor, min_val=None): """ This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py :param v: :param divisor: :param min_val: :return: """ if min_val is None: min_val = divisor new_v = max(min_val, int(v + divisor / 2) // divisor * divisor) if new_v < 0.9 * v: new_v += divisor return new_v class Hsigmoid(nn.Module): def __init__(self, inplace=True): super(Hsigmoid, self).__init__() self.inplace = inplace def forward(self, x): return F.relu6(x + 3.0, inplace=self.inplace) / 6.0 class SEModule(nn.Module): def __init__(self, channel, reduction=0.25): super(SEModule, self).__init__() self.channel = channel self.reduction = reduction num_mid = make_divisible(int(self.channel * self.reduction), divisor=8) self.fc = nn.Sequential(OrderedDict([('reduce', nn.Conv2d(self. channel, num_mid, 1, 1, 0, bias=True)), ('relu', nn.ReLU( inplace=True)), ('expand', nn.Conv2d(num_mid, self.channel, 1, 1, 0, bias=True)), ('h_sigmoid', Hsigmoid(inplace=True))])) def forward(self, x): y = x.mean(3, keepdim=True).mean(2, keepdim=True) y = self.fc(y) return x * y def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'channel': 4}]
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 torch.nn as nn import torch.nn.functional as F from collections import OrderedDict import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_mean_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 x0 = xindex tmp0 = tl.load(in_ptr0 + 16 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp3 = tl.load(in_ptr0 + (2 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp5 = tl.load(in_ptr0 + (3 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp9 = tl.load(in_ptr0 + (4 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp10 = tl.load(in_ptr0 + (5 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp12 = tl.load(in_ptr0 + (6 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp14 = tl.load(in_ptr0 + (7 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp18 = tl.load(in_ptr0 + (8 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp19 = tl.load(in_ptr0 + (9 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp21 = tl.load(in_ptr0 + (10 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp23 = tl.load(in_ptr0 + (11 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp27 = tl.load(in_ptr0 + (12 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp28 = tl.load(in_ptr0 + (13 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp30 = tl.load(in_ptr0 + (14 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp32 = tl.load(in_ptr0 + (15 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp6 = tmp4 + tmp5 tmp7 = 4.0 tmp8 = tmp6 / tmp7 tmp11 = tmp9 + tmp10 tmp13 = tmp11 + tmp12 tmp15 = tmp13 + tmp14 tmp16 = tmp15 / tmp7 tmp17 = tmp8 + tmp16 tmp20 = tmp18 + tmp19 tmp22 = tmp20 + tmp21 tmp24 = tmp22 + tmp23 tmp25 = tmp24 / tmp7 tmp26 = tmp17 + tmp25 tmp29 = tmp27 + tmp28 tmp31 = tmp29 + tmp30 tmp33 = tmp31 + tmp32 tmp34 = tmp33 / tmp7 tmp35 = tmp26 + tmp34 tmp36 = tmp35 / tmp7 tl.store(out_ptr0 + x0, tmp36, xmask) @triton.jit def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 32 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 8 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, xmask) @triton.jit def triton_poi_fused_add_convolution_div_hardtanh_mul_2(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x4 = xindex // 16 x1 = xindex // 16 % 4 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr1 + x4, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp4 = 3.0 tmp5 = tmp3 + tmp4 tmp6 = 0.0 tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = 6.0 tmp9 = triton_helpers.minimum(tmp7, tmp8) tmp10 = 0.16666666666666666 tmp11 = tmp9 * tmp10 tmp12 = tmp0 * tmp11 tl.store(out_ptr0 + x3, tmp12, xmask) @triton.jit def triton_poi_fused_add_convolution_hardtanh_backward_3(in_ptr0, in_ptr1, 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 x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 3.0 tmp4 = tmp2 + tmp3 tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tmp7 = 6.0 tmp8 = tmp4 >= tmp7 tmp9 = tmp6 | tmp8 tl.store(out_ptr0 + x2, tmp9, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (8, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_3, (8,), (1,)) assert_size_stride(primals_4, (4, 8, 1, 1), (8, 1, 1, 1)) assert_size_stride(primals_5, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.float32) get_raw_stream(0) triton_poi_fused_mean_0[grid(16)](primals_1, buf0, 16, XBLOCK=16, num_warps=1, num_stages=1) buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf1, (4, 8, 1, 1), (8, 1, 1, 1)) buf2 = buf1 del buf1 triton_poi_fused_convolution_relu_1[grid(32)](buf2, primals_3, 32, XBLOCK=32, num_warps=1, num_stages=1) del primals_3 buf3 = extern_kernels.convolution(buf2, primals_4, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf3, (4, 4, 1, 1), (4, 1, 1, 1)) buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_add_convolution_div_hardtanh_mul_2[grid(256)]( primals_1, buf3, primals_5, buf4, 256, XBLOCK=256, num_warps=4, num_stages=1) buf5 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.bool) triton_poi_fused_add_convolution_hardtanh_backward_3[grid(16)](buf3, primals_5, buf5, 16, XBLOCK=16, num_warps=1, num_stages=1) del buf3 del primals_5 return buf4, primals_1, primals_2, primals_4, buf0, buf2, buf5 def make_divisible(v, divisor, min_val=None): """ This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py :param v: :param divisor: :param min_val: :return: """ if min_val is None: min_val = divisor new_v = max(min_val, int(v + divisor / 2) // divisor * divisor) if new_v < 0.9 * v: new_v += divisor return new_v class Hsigmoid(nn.Module): def __init__(self, inplace=True): super(Hsigmoid, self).__init__() self.inplace = inplace def forward(self, x): return F.relu6(x + 3.0, inplace=self.inplace) / 6.0 class SEModuleNew(nn.Module): def __init__(self, channel, reduction=0.25): super(SEModuleNew, self).__init__() self.channel = channel self.reduction = reduction num_mid = make_divisible(int(self.channel * self.reduction), divisor=8) self.fc = nn.Sequential(OrderedDict([('reduce', nn.Conv2d(self. channel, num_mid, 1, 1, 0, bias=True)), ('relu', nn.ReLU( inplace=True)), ('expand', nn.Conv2d(num_mid, self.channel, 1, 1, 0, bias=True)), ('h_sigmoid', Hsigmoid(inplace=True))])) def forward(self, input_0): primals_2 = self.fc.reduce.weight primals_3 = self.fc.reduce.bias primals_4 = self.fc.expand.weight primals_5 = self.fc.expand.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
dercaft/XNAS
SEModule
false
6,571
[ "MIT" ]
1
d6d0fde0d4475210a41607181939188b177e44b1
https://github.com/dercaft/XNAS/tree/d6d0fde0d4475210a41607181939188b177e44b1
BinaryReg
import torch import torch.nn as nn import torch.utils.data class BinaryReg(nn.Module): """Regularization for encouraging the outputs to be binary. """ def __init__(self, alpha=1.0): super().__init__() self.alpha = alpha def forward(self, pred): diff = pred - 0.5 diff = torch.clamp(torch.abs(diff), min=0.01) loss = 1.0 / diff.sum() return self.alpha * loss def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 torch.nn as nn import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_abs_clamp_mul_reciprocal_sub_sum_0(in_out_ptr0, in_ptr0, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = 0.5 tmp2 = tmp0 - tmp1 tmp3 = tl_math.abs(tmp2) tmp4 = 0.01 tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp6 = tl.broadcast_to(tmp5, [RBLOCK]) tmp8 = triton_helpers.promote_to_tensor(tl.sum(tmp6, 0)) tmp9 = tl.full([1], 1, tl.int32) tmp10 = tmp9 / tmp8 tmp11 = 1.0 tmp12 = tmp10 * tmp11 tmp13 = tmp12 * tmp11 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp13, None) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf1 = buf0 del buf0 get_raw_stream(0) triton_per_fused_abs_clamp_mul_reciprocal_sub_sum_0[grid(1)](buf1, arg0_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 return buf1, class BinaryRegNew(nn.Module): """Regularization for encouraging the outputs to be binary. """ def __init__(self, alpha=1.0): super().__init__() self.alpha = alpha def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
divyam-goel/pytorch_connectomics
BinaryReg
false
6,572
[ "MIT" ]
1
a2c70a7cc60fd84d67be6f225c123ff11daadb83
https://github.com/divyam-goel/pytorch_connectomics/tree/a2c70a7cc60fd84d67be6f225c123ff11daadb83
Attention
import torch from torch import nn as nn from torch.nn import functional as F class Attention(nn.Module): def __init__(self, hidden_size): super().__init__() self.decoder_proj = nn.Linear(hidden_size, hidden_size) self.encoder_proj = nn.Linear(hidden_size, hidden_size) nn.init.xavier_uniform_(self.decoder_proj.weight) nn.init.xavier_uniform_(self.encoder_proj.weight) def forward(self, decoder_hidden, encoder_outputs, encoder_masks=None): query = self.decoder_proj(decoder_hidden) key = self.encoder_proj(encoder_outputs) energy = torch.sum(torch.mul(key, query.unsqueeze(1)), dim=-1) if encoder_masks is not None: energy.masked_fill_(~encoder_masks, -1 * 10000000.0) attn_dists = F.softmax(energy, dim=-1) context_vecs = torch.sum(torch.mul(encoder_outputs, attn_dists. unsqueeze(2)), dim=1) return context_vecs, attn_dists def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'hidden_size': 4}]
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 from torch import 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_poi_fused_mul_sum_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex % 64 x0 = xindex % 16 x2 = xindex // 64 x4 = xindex tmp0 = tl.load(in_ptr0 + 4 * x3, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + (4 * x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp3 = tl.load(in_ptr0 + (1 + 4 * x3), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr1 + (1 + 4 * x0 + 64 * x2), xmask, eviction_policy ='evict_last') tmp7 = tl.load(in_ptr0 + (2 + 4 * x3), xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr1 + (2 + 4 * x0 + 64 * x2), xmask, eviction_policy ='evict_last') tmp11 = tl.load(in_ptr0 + (3 + 4 * x3), xmask, eviction_policy='evict_last' ) tmp12 = tl.load(in_ptr1 + (3 + 4 * x0 + 64 * x2), xmask, eviction_policy='evict_last') tmp2 = tmp0 * tmp1 tmp5 = tmp3 * tmp4 tmp6 = tmp2 + tmp5 tmp9 = tmp7 * tmp8 tmp10 = tmp6 + tmp9 tmp13 = tmp11 * tmp12 tmp14 = tmp10 + tmp13 tl.store(out_ptr0 + x4, tmp14, xmask) @triton.jit def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 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') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp0 - tmp7 tmp9 = tl_math.exp(tmp8) tl.store(out_ptr0 + x2, tmp9, xmask) @triton.jit def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 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') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) @triton.jit def triton_poi_fused_mul_sum_3(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex % 64 x0 = xindex % 16 x2 = xindex // 64 x4 = xindex tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + (x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp3 = tl.load(in_ptr0 + (64 + x3), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr1 + (16 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp7 = tl.load(in_ptr0 + (128 + x3), xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr1 + (32 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp11 = tl.load(in_ptr0 + (192 + x3), xmask, eviction_policy='evict_last') tmp12 = tl.load(in_ptr1 + (48 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp2 = tmp0 * tmp1 tmp5 = tmp3 * tmp4 tmp6 = tmp2 + tmp5 tmp9 = tmp7 * tmp8 tmp10 = tmp6 + tmp9 tmp13 = tmp11 * tmp12 tmp14 = tmp10 + tmp13 tl.store(out_ptr0 + x4, tmp14, 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, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0 ), alpha=1, beta=1, out=buf0) del primals_1 del primals_2 buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_5, reinterpret_tensor(primals_6, (64, 4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0 ), alpha=1, beta=1, out=buf1) del primals_4 del primals_5 buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_mul_sum_0[grid(256)](buf1, buf0, buf2, 256, XBLOCK =256, num_warps=4, num_stages=1) buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused__softmax_1[grid(256)](buf2, buf3, 256, XBLOCK=128, num_warps=4, num_stages=1) buf4 = buf2 del buf2 triton_poi_fused__softmax_2[grid(256)](buf3, buf4, 256, XBLOCK=256, num_warps=4, num_stages=1) buf5 = buf3 del buf3 triton_poi_fused_mul_sum_3[grid(256)](primals_6, buf4, buf5, 256, XBLOCK=256, num_warps=4, num_stages=1) return buf5, buf4, primals_6, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), buf0, buf1, buf4 class AttentionNew(nn.Module): def __init__(self, hidden_size): super().__init__() self.decoder_proj = nn.Linear(hidden_size, hidden_size) self.encoder_proj = nn.Linear(hidden_size, hidden_size) nn.init.xavier_uniform_(self.decoder_proj.weight) nn.init.xavier_uniform_(self.encoder_proj.weight) def forward(self, input_0, input_1): primals_1 = self.decoder_proj.weight primals_2 = self.decoder_proj.bias primals_4 = self.encoder_proj.weight primals_5 = self.encoder_proj.bias primals_3 = input_0 primals_6 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6]) return output[0], output[1]
devjwsong/dialogue-error-correction-pytorch
Attention
false
6,573
[ "MIT" ]
1
ee0fa1f27eb995893a5943181a1fd0099a9e9202
https://github.com/devjwsong/dialogue-error-correction-pytorch/tree/ee0fa1f27eb995893a5943181a1fd0099a9e9202
MMTMBi
import torch import torch.nn as nn from typing import Sequence class MMTMBi(nn.Module): """ bi moludal fusion """ def __init__(self, dim_tab, dim_img, ratio=4): """ Parameters ---------- dim_tab: feature dimension of tabular data dim_img: feature dimension of MIL image modal ratio """ super(MMTMBi, self).__init__() dim = dim_tab + dim_img dim_out = int(2 * dim / ratio) self.fc_squeeze = nn.Linear(dim, dim_out) self.fc_tab = nn.Linear(dim_out, dim_tab) self.fc_img = nn.Linear(dim_out, dim_img) self.relu = nn.ReLU() self.sigmoid = nn.Sigmoid() def forward(self, tab_feat, img_feat) ->Sequence[torch.Tensor]: """ Parameters ---------- tab_feat: b * c skeleton: b * c Returns 表格数据加权结果 WSI 全局特征加权结果 WSI 全局特征加权权重 ------- """ squeeze = torch.cat([tab_feat, img_feat], dim=1) excitation = self.fc_squeeze(squeeze) excitation = self.relu(excitation) tab_out = self.fc_tab(excitation) img_out = self.fc_img(excitation) tab_out = self.sigmoid(tab_out) img_out = self.sigmoid(img_out) return tab_feat * tab_out, img_feat * img_out, img_out def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'dim_tab': 4, 'dim_img': 4}]
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 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_poi_fused_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 32 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 8 x1 = xindex // 8 x2 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy= 'evict_last', other=0.0) tmp6 = tmp0 >= tmp3 tl.full([1], 8, tl.int64) tmp9 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp6 & xmask, eviction_policy='evict_last', other=0.0) tmp10 = tl.where(tmp4, tmp5, tmp9) tl.store(out_ptr0 + x2, tmp10, xmask) @triton.jit def triton_poi_fused_relu_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, xmask) @triton.jit def triton_poi_fused_mul_sigmoid_2(in_out_ptr0, in_ptr0, in_ptr1, 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 x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr1 + x2, xmask) tmp2 = tmp0 + tmp1 tmp3 = tl.sigmoid(tmp2) tmp5 = tmp4 * tmp3 tl.store(in_out_ptr0 + x2, tmp3, xmask) tl.store(out_ptr0 + x2, tmp5, xmask) @triton.jit def triton_poi_fused_mul_sigmoid_3(in_ptr0, in_ptr1, 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_ptr0 + x0, xmask) tmp1 = tl.load(in_ptr1 + x0, xmask) tmp2 = tl.sigmoid(tmp1) tmp3 = tmp0 * tmp2 tl.store(out_ptr0 + x0, tmp3, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8) = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4, 4), (4, 1)) assert_size_stride(primals_3, (4, 8), (8, 1)) assert_size_stride(primals_4, (4,), (1,)) assert_size_stride(primals_5, (4, 4), (4, 1)) assert_size_stride(primals_6, (4,), (1,)) assert_size_stride(primals_7, (4, 4), (4, 1)) assert_size_stride(primals_8, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 8), (8, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(32)](primals_1, primals_2, buf0, 32, XBLOCK=32, num_warps=1, num_stages=1) buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf0, reinterpret_tensor(primals_3, (8, 4), (1, 8 ), 0), out=buf1) del primals_3 buf2 = buf1 del buf1 triton_poi_fused_relu_1[grid(16)](buf2, primals_4, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_4 buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_6, buf2, reinterpret_tensor(primals_5, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf3) del primals_6 buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf2, reinterpret_tensor(primals_7, (4, 4), (1, 4 ), 0), out=buf4) buf5 = buf4 del buf4 buf7 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_mul_sigmoid_2[grid(16)](buf5, primals_8, primals_2, buf7, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_8 buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_mul_sigmoid_3[grid(16)](primals_1, buf3, buf6, 16, XBLOCK=16, num_warps=1, num_stages=1) return (buf6, buf7, buf5, primals_1, primals_2, buf0, buf2, buf3, buf5, primals_7, primals_5) class MMTMBiNew(nn.Module): """ bi moludal fusion """ def __init__(self, dim_tab, dim_img, ratio=4): """ Parameters ---------- dim_tab: feature dimension of tabular data dim_img: feature dimension of MIL image modal ratio """ super(MMTMBiNew, self).__init__() dim = dim_tab + dim_img dim_out = int(2 * dim / ratio) self.fc_squeeze = nn.Linear(dim, dim_out) self.fc_tab = nn.Linear(dim_out, dim_tab) self.fc_img = nn.Linear(dim_out, dim_img) self.relu = nn.ReLU() self.sigmoid = nn.Sigmoid() def forward(self, input_0, input_1): primals_3 = self.fc_squeeze.weight primals_4 = self.fc_squeeze.bias primals_1 = self.fc_tab.weight primals_6 = self.fc_tab.bias primals_2 = self.fc_img.weight primals_8 = self.fc_img.bias primals_5 = input_0 primals_7 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8]) return output[0], output[1], output[2]
ditannan/Multi-modal-Multi-instance-Learning
MMTMBi
false
6,575
[ "Apache-2.0" ]
1
06aada1ff85784d5ed50aa528c506947c892d584
https://github.com/ditannan/Multi-modal-Multi-instance-Learning/tree/06aada1ff85784d5ed50aa528c506947c892d584
JaccardLoss
import torch import torch.nn as nn import torch.utils.data class JaccardLoss(nn.Module): """Jaccard loss. """ def __init__(self, size_average=True, reduce=True, smooth=1.0): super(JaccardLoss, self).__init__() self.smooth = smooth self.reduce = reduce def jaccard_loss(self, pred, target): loss = 0.0 for index in range(pred.size()[0]): iflat = pred[index].view(-1) tflat = target[index].view(-1) intersection = (iflat * tflat).sum() loss += 1 - (intersection + self.smooth) / (iflat.sum() + tflat .sum() - intersection + self.smooth) return loss / float(pred.size()[0]) def jaccard_loss_batch(self, pred, target): iflat = pred.view(-1) tflat = target.view(-1) intersection = (iflat * tflat).sum() loss = 1 - (intersection + self.smooth) / (iflat.sum() + tflat.sum( ) - intersection + self.smooth) return loss def forward(self, pred, target): if not target.size() == pred.size(): raise ValueError( 'Target size ({}) must be the same as pred size ({})'. format(target.size(), pred.size())) if self.reduce: loss = self.jaccard_loss(pred, target) else: loss = self.jaccard_loss_batch(pred, target) return loss def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 import torch.nn as nn import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_add_div_mul_rsub_sub_sum_0(in_out_ptr1, in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 64 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tl.load(in_ptr1 + r0, None) tmp12 = tl.load(in_ptr0 + (64 + r0), None) tmp13 = tl.load(in_ptr1 + (64 + r0), None) tmp24 = tl.load(in_ptr0 + (192 + r0), None) tmp25 = tl.load(in_ptr1 + (192 + r0), None) tmp36 = tl.load(in_ptr0 + (128 + r0), None) tmp37 = tl.load(in_ptr1 + (128 + r0), None) tmp2 = tmp0 * tmp1 tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK]) tmp5 = tl.sum(tmp3, 1)[:, None] tmp6 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp8 = tl.sum(tmp6, 1)[:, None] tmp9 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp11 = tl.sum(tmp9, 1)[:, None] tmp14 = tmp12 * tmp13 tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK]) tmp17 = tl.sum(tmp15, 1)[:, None] tmp18 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK]) tmp20 = tl.sum(tmp18, 1)[:, None] tmp21 = tl.broadcast_to(tmp13, [XBLOCK, RBLOCK]) tmp23 = tl.sum(tmp21, 1)[:, None] tmp26 = tmp24 * tmp25 tmp27 = tl.broadcast_to(tmp26, [XBLOCK, RBLOCK]) tmp29 = tl.sum(tmp27, 1)[:, None] tmp30 = tl.broadcast_to(tmp24, [XBLOCK, RBLOCK]) tmp32 = tl.sum(tmp30, 1)[:, None] tmp33 = tl.broadcast_to(tmp25, [XBLOCK, RBLOCK]) tmp35 = tl.sum(tmp33, 1)[:, None] tmp38 = tmp36 * tmp37 tmp39 = tl.broadcast_to(tmp38, [XBLOCK, RBLOCK]) tmp41 = tl.sum(tmp39, 1)[:, None] tmp42 = tl.broadcast_to(tmp36, [XBLOCK, RBLOCK]) tmp44 = tl.sum(tmp42, 1)[:, None] tmp45 = tl.broadcast_to(tmp37, [XBLOCK, RBLOCK]) tmp47 = tl.sum(tmp45, 1)[:, None] tmp48 = 1.0 tmp49 = tmp5 + tmp48 tmp50 = tmp8 + tmp11 tmp51 = tmp50 - tmp5 tmp52 = tmp51 + tmp48 tmp53 = tmp49 / tmp52 tmp54 = tmp48 - tmp53 tmp55 = 0.0 tmp56 = tmp54 + tmp55 tmp57 = tmp17 + tmp48 tmp58 = tmp20 + tmp23 tmp59 = tmp58 - tmp17 tmp60 = tmp59 + tmp48 tmp61 = tmp57 / tmp60 tmp62 = tmp48 - tmp61 tmp63 = tmp56 + tmp62 tmp64 = tmp41 + tmp48 tmp65 = tmp44 + tmp47 tmp66 = tmp65 - tmp41 tmp67 = tmp66 + tmp48 tmp68 = tmp64 / tmp67 tmp69 = tmp48 - tmp68 tmp70 = tmp63 + tmp69 tmp71 = tmp29 + tmp48 tmp72 = tmp32 + tmp35 tmp73 = tmp72 - tmp29 tmp74 = tmp73 + tmp48 tmp75 = tmp71 / tmp74 tmp76 = tmp48 - tmp75 tmp77 = tmp70 + tmp76 tmp78 = 0.25 tmp79 = tmp77 * tmp78 tl.debug_barrier() tl.store(in_out_ptr1 + tl.full([XBLOCK, 1], 0, tl.int32), tmp79, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf10 = empty_strided_cuda((), (), torch.float32) buf13 = buf10 del buf10 get_raw_stream(0) triton_per_fused_add_div_mul_rsub_sub_sum_0[grid(1)](buf13, arg1_1, arg0_1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1) del arg0_1 del arg1_1 return buf13, class JaccardLossNew(nn.Module): """Jaccard loss. """ def __init__(self, size_average=True, reduce=True, smooth=1.0): super(JaccardLossNew, self).__init__() self.smooth = smooth self.reduce = reduce def jaccard_loss(self, pred, target): loss = 0.0 for index in range(pred.size()[0]): iflat = pred[index].view(-1) tflat = target[index].view(-1) intersection = (iflat * tflat).sum() loss += 1 - (intersection + self.smooth) / (iflat.sum() + tflat .sum() - intersection + self.smooth) return loss / float(pred.size()[0]) def jaccard_loss_batch(self, pred, target): iflat = pred.view(-1) tflat = target.view(-1) intersection = (iflat * tflat).sum() loss = 1 - (intersection + self.smooth) / (iflat.sum() + tflat.sum( ) - intersection + self.smooth) return loss def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
divyam-goel/pytorch_connectomics
JaccardLoss
false
6,576
[ "MIT" ]
1
a2c70a7cc60fd84d67be6f225c123ff11daadb83
https://github.com/divyam-goel/pytorch_connectomics/tree/a2c70a7cc60fd84d67be6f225c123ff11daadb83
MMTMTri
import torch import torch.nn as nn from typing import Sequence class MMTMTri(nn.Module): """ tri-modal fusion """ def __init__(self, dim_img, ratio=4): """ Parameters ---------- dim_tab: feature dimension of tabular data dim_img: feature dimension of MIL model ratio """ super(MMTMTri, self).__init__() dim = dim_img * 3 dim_out = int(2 * dim / ratio) self.fc_squeeze = nn.Linear(dim, dim_out) self.fc_img_scale1 = nn.Linear(dim_out, dim_img) self.fc_img_scale2 = nn.Linear(dim_out, dim_img) self.fc_img_scale3 = nn.Linear(dim_out, dim_img) self.relu = nn.ReLU() self.sigmoid = nn.Sigmoid() def forward(self, img_feat_scale1, img_feat_scale2, img_feat_scale3 ) ->Sequence[torch.Tensor]: """ Parameters ---------- tab_feat: b * c skeleton: b * c Returns ------- """ squeeze = torch.cat([img_feat_scale1, img_feat_scale2, img_feat_scale3], dim=1) excitation = self.fc_squeeze(squeeze) excitation = self.relu(excitation) img_out_scale1 = self.fc_img_scale1(excitation) img_out_scale2 = self.fc_img_scale2(excitation) img_out_scale3 = self.fc_img_scale3(excitation) img_out_scale1 = self.sigmoid(img_out_scale1) img_out_scale2 = self.sigmoid(img_out_scale2) img_out_scale3 = self.sigmoid(img_out_scale3) return (img_feat_scale1 * img_out_scale1, img_out_scale1, img_feat_scale2 * img_out_scale2, img_out_scale2, img_feat_scale2 * img_out_scale3, img_out_scale3) def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'dim_img': 4}]
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 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_poi_fused_cat_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 48 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 12 x1 = xindex // 12 x2 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy= 'evict_last', other=0.0) tmp6 = tmp0 >= tmp3 tmp7 = tl.full([1], 8, tl.int64) tmp8 = tmp0 < tmp7 tmp9 = tmp6 & tmp8 tmp10 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp9 & xmask, eviction_policy='evict_last', other=0.0) tmp11 = tmp0 >= tmp7 tl.full([1], 12, tl.int64) tmp14 = tl.load(in_ptr2 + (4 * x1 + (-8 + x0)), tmp11 & xmask, eviction_policy='evict_last', other=0.0) tmp15 = tl.where(tmp9, tmp10, tmp14) tmp16 = tl.where(tmp4, tmp5, tmp15) tl.store(out_ptr0 + x2, tmp16, xmask) @triton.jit def triton_poi_fused_relu_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 24 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 6 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, xmask) @triton.jit def triton_poi_fused_mul_sigmoid_2(in_out_ptr0, in_ptr0, in_ptr1, 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 x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr1 + x2, xmask) tmp2 = tmp0 + tmp1 tmp3 = tl.sigmoid(tmp2) tmp5 = tmp4 * tmp3 tl.store(in_out_ptr0 + x2, tmp3, xmask) tl.store(out_ptr0 + x2, tmp5, xmask) @triton.jit def triton_poi_fused_mul_sigmoid_3(in_out_ptr0, in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp4 = tl.load(in_out_ptr1 + x2, xmask) tmp5 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr2 + x2, xmask) tmp2 = tmp0 + tmp1 tmp3 = tl.sigmoid(tmp2) tmp6 = tmp4 + tmp5 tmp7 = tl.sigmoid(tmp6) tmp9 = tmp8 * tmp7 tmp10 = tmp8 * tmp3 tl.store(in_out_ptr0 + x2, tmp3, xmask) tl.store(in_out_ptr1 + x2, tmp7, xmask) tl.store(out_ptr0 + x2, tmp9, xmask) tl.store(out_ptr1 + x2, tmp10, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11) = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4, 4), (4, 1)) assert_size_stride(primals_3, (4, 4), (4, 1)) assert_size_stride(primals_4, (6, 12), (12, 1)) assert_size_stride(primals_5, (6,), (1,)) assert_size_stride(primals_6, (4, 6), (6, 1)) assert_size_stride(primals_7, (4,), (1,)) assert_size_stride(primals_8, (4, 6), (6, 1)) assert_size_stride(primals_9, (4,), (1,)) assert_size_stride(primals_10, (4, 6), (6, 1)) assert_size_stride(primals_11, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 12), (12, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(48)](primals_1, primals_2, primals_3, buf0, 48, XBLOCK=64, num_warps=1, num_stages=1) del primals_3 buf1 = empty_strided_cuda((4, 6), (6, 1), torch.float32) extern_kernels.mm(buf0, reinterpret_tensor(primals_4, (12, 6), (1, 12), 0), out=buf1) del primals_4 buf2 = buf1 del buf1 triton_poi_fused_relu_1[grid(24)](buf2, primals_5, 24, XBLOCK=32, num_warps=1, num_stages=1) del primals_5 buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf2, reinterpret_tensor(primals_6, (6, 4), (1, 6 ), 0), out=buf3) buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf2, reinterpret_tensor(primals_8, (6, 4), (1, 6 ), 0), out=buf4) buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf2, reinterpret_tensor(primals_10, (6, 4), (1, 6), 0), out=buf5) buf6 = buf3 del buf3 buf9 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_mul_sigmoid_2[grid(16)](buf6, primals_7, primals_1, buf9, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_7 buf8 = buf5 del buf5 buf7 = buf4 del buf4 buf10 = empty_strided_cuda((4, 4), (4, 1), torch.float32) buf11 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_mul_sigmoid_3[grid(16)](buf8, buf7, primals_11, primals_9, primals_2, buf10, buf11, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_11 del primals_9 return (buf9, buf6, buf10, buf7, buf11, buf8, primals_1, primals_2, buf0, buf2, buf6, buf7, buf8, primals_10, primals_8, primals_6) class MMTMTriNew(nn.Module): """ tri-modal fusion """ def __init__(self, dim_img, ratio=4): """ Parameters ---------- dim_tab: feature dimension of tabular data dim_img: feature dimension of MIL model ratio """ super(MMTMTriNew, self).__init__() dim = dim_img * 3 dim_out = int(2 * dim / ratio) self.fc_squeeze = nn.Linear(dim, dim_out) self.fc_img_scale1 = nn.Linear(dim_out, dim_img) self.fc_img_scale2 = nn.Linear(dim_out, dim_img) self.fc_img_scale3 = nn.Linear(dim_out, dim_img) self.relu = nn.ReLU() self.sigmoid = nn.Sigmoid() def forward(self, input_0, input_1, input_2): primals_4 = self.fc_squeeze.weight primals_5 = self.fc_squeeze.bias primals_6 = self.fc_img_scale1.weight primals_7 = self.fc_img_scale1.bias primals_8 = self.fc_img_scale2.weight primals_9 = self.fc_img_scale2.bias primals_10 = self.fc_img_scale3.weight primals_11 = self.fc_img_scale3.bias primals_1 = input_0 primals_2 = input_1 primals_3 = input_2 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11]) return output[0], output[1], output[2], output[3], output[4], output[5]
ditannan/Multi-modal-Multi-instance-Learning
MMTMTri
false
6,577
[ "Apache-2.0" ]
1
06aada1ff85784d5ed50aa528c506947c892d584
https://github.com/ditannan/Multi-modal-Multi-instance-Learning/tree/06aada1ff85784d5ed50aa528c506947c892d584
Sine
import torch import torch.nn as nn import torch.nn.functional import torch.nn.parallel import torch.utils.data.distributed class Sine(nn.Module): """ Applies the sine function element-wise. `"Implicit Neural Representations with Periodic Activation Functions" <https://arxiv.org/pdf/2006.09661.pdf>`_ Examples: >>> m = Sine() >>> x = torch.randn(2) >>> output = m(x) """ @staticmethod def forward(x: 'torch.Tensor') ->torch.Tensor: out = torch.sin(30 * x) return out def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 import torch.nn.functional import torch.nn.parallel import torch.utils.data.distributed assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_mul_sin_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 30.0 tmp2 = tmp0 * tmp1 tmp3 = tl_math.sin(tmp2) tl.store(out_ptr0 + x0, tmp3, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_mul_sin_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 return buf0, class SineNew(nn.Module): """ Applies the sine function element-wise. `"Implicit Neural Representations with Periodic Activation Functions" <https://arxiv.org/pdf/2006.09661.pdf>`_ Examples: >>> m = Sine() >>> x = torch.randn(2) >>> output = m(x) """ def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
doansangg/CGAN-PyTorch
Sine
false
6,578
[ "Apache-2.0" ]
1
941f5bd75102bed7f2eccd7feb9af8e6134af0e4
https://github.com/doansangg/CGAN-PyTorch/tree/941f5bd75102bed7f2eccd7feb9af8e6134af0e4
SimpleCNN
import torch import torch.nn as nn import torch.nn.functional as F class SimpleCNN(nn.Module): def __init__(self, num_channels, num_classes): super(SimpleCNN, self).__init__() C = num_channels self.conv1 = nn.Conv2d(in_channels=C, out_channels=C * 8, kernel_size=3, stride=2, padding=1) self.conv2 = nn.Conv2d(in_channels=C * 8, out_channels=C * 32, kernel_size=3, stride=2, padding=1) self.conv3 = nn.Conv2d(in_channels=C * 32, out_channels=C * 128, kernel_size=3, stride=2, padding=1) self.avgpool = nn.AdaptiveAvgPool2d(1) self.dropout1 = nn.Dropout2d(0.25) self.fc1 = nn.Linear(C * 128, 128) self.dropout2 = nn.Dropout2d(0.5) self.fc2 = nn.Linear(128, num_classes) def forward(self, x): x = self.conv1(x) x = F.relu(x) x = self.conv2(x) x = F.relu(x) x = self.conv3(x) x = self.avgpool(x) x = torch.flatten(x, 1) x = F.relu(x) x = self.dropout1(x) x = self.fc1(x) x = F.relu(x) x = self.dropout2(x) x = self.fc2(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'num_channels': 4, 'num_classes': 4}]
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 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_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 128 xnumel = 9 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y3 = yindex y0 = yindex % 4 y1 = yindex // 4 tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask & ymask, eviction_policy= 'evict_last') tl.store(out_ptr0 + (y0 + 4 * x2 + 36 * y1), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 16 xnumel = 16 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y3 = yindex y0 = yindex % 4 y1 = yindex // 4 tmp0 = tl.load(in_ptr0 + (x2 + 16 * y3), xmask & ymask) tl.store(out_ptr0 + (y0 + 4 * x2 + 64 * y1), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_2(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): xnumel = 9 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 % 32 y1 = yindex // 32 tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last' ) tl.store(out_ptr0 + (y0 + 32 * x2 + 288 * y1), tmp0, xmask) @triton.jit def triton_poi_fused_3(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 % 128 y1 = yindex // 128 tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last' ) tl.store(out_ptr0 + (y0 + 128 * x2 + 1152 * y1), tmp0, xmask) @triton.jit def triton_poi_fused_convolution_relu_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 512 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 32 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, xmask) @triton.jit def triton_poi_fused_convolution_relu_5(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 512 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 128 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, xmask) @triton.jit def triton_poi_fused_relu_6(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 tmp3 = 1.0 tmp4 = tmp2 / tmp3 tmp5 = tl.full([1], 0, tl.int32) tmp6 = triton_helpers.maximum(tmp5, tmp4) tl.store(in_out_ptr0 + x2, tmp6, None) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11) = args args.clear() assert_size_stride(primals_1, (32, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_2, (32,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (128, 32, 3, 3), (288, 9, 3, 1)) assert_size_stride(primals_5, (128,), (1,)) assert_size_stride(primals_6, (512, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_7, (512,), (1,)) assert_size_stride(primals_8, (128, 512), (512, 1)) assert_size_stride(primals_9, (128,), (1,)) assert_size_stride(primals_10, (4, 128), (128, 1)) assert_size_stride(primals_11, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((32, 4, 3, 3), (36, 1, 12, 4), torch.float32) get_raw_stream(0) triton_poi_fused_0[grid(128, 9)](primals_1, buf0, 128, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_1 buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 1, 16, 4), torch.float32) triton_poi_fused_1[grid(16, 16)](primals_3, buf1, 16, 16, XBLOCK=16, YBLOCK=16, num_warps=4, num_stages=1) del primals_3 buf2 = empty_strided_cuda((128, 32, 3, 3), (288, 1, 96, 32), torch. float32) triton_poi_fused_2[grid(4096, 9)](primals_4, buf2, 4096, 9, XBLOCK= 16, YBLOCK=64, num_warps=4, num_stages=1) del primals_4 buf3 = empty_strided_cuda((512, 128, 3, 3), (1152, 1, 384, 128), torch.float32) triton_poi_fused_3[grid(65536, 9)](primals_6, buf3, 65536, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_6 buf4 = extern_kernels.convolution(buf1, buf0, stride=(2, 2), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf4, (4, 32, 2, 2), (128, 1, 64, 32)) buf5 = buf4 del buf4 triton_poi_fused_convolution_relu_4[grid(512)](buf5, primals_2, 512, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 buf6 = extern_kernels.convolution(buf5, buf2, stride=(2, 2), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf6, (4, 128, 1, 1), (128, 1, 128, 128)) buf7 = buf6 del buf6 triton_poi_fused_convolution_relu_5[grid(512)](buf7, primals_5, 512, XBLOCK=256, num_warps=4, num_stages=1) del primals_5 buf8 = extern_kernels.convolution(buf7, buf3, stride=(2, 2), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf8, (4, 512, 1, 1), (512, 1, 512, 512)) buf9 = reinterpret_tensor(buf8, (4, 512), (512, 1), 0) del buf8 triton_poi_fused_relu_6[grid(2048)](buf9, primals_7, 2048, XBLOCK= 256, num_warps=4, num_stages=1) del primals_7 buf10 = empty_strided_cuda((4, 128), (128, 1), torch.float32) extern_kernels.mm(buf9, reinterpret_tensor(primals_8, (512, 128), ( 1, 512), 0), out=buf10) buf11 = buf10 del buf10 triton_poi_fused_convolution_relu_5[grid(512)](buf11, primals_9, 512, XBLOCK=256, num_warps=4, num_stages=1) del primals_9 buf12 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_11, buf11, reinterpret_tensor( primals_10, (128, 4), (1, 128), 0), alpha=1, beta=1, out=buf12) del primals_11 return (buf12, buf0, buf1, buf2, buf3, buf5, buf7, buf9, buf11, primals_10, primals_8) class SimpleCNNNew(nn.Module): def __init__(self, num_channels, num_classes): super(SimpleCNNNew, self).__init__() C = num_channels self.conv1 = nn.Conv2d(in_channels=C, out_channels=C * 8, kernel_size=3, stride=2, padding=1) self.conv2 = nn.Conv2d(in_channels=C * 8, out_channels=C * 32, kernel_size=3, stride=2, padding=1) self.conv3 = nn.Conv2d(in_channels=C * 32, out_channels=C * 128, kernel_size=3, stride=2, padding=1) self.avgpool = nn.AdaptiveAvgPool2d(1) self.dropout1 = nn.Dropout2d(0.25) self.fc1 = nn.Linear(C * 128, 128) self.dropout2 = nn.Dropout2d(0.5) self.fc2 = nn.Linear(128, num_classes) def forward(self, input_0): primals_1 = self.conv1.weight primals_2 = self.conv1.bias primals_4 = self.conv2.weight primals_5 = self.conv2.bias primals_6 = self.conv3.weight primals_7 = self.conv3.bias primals_8 = self.fc1.weight primals_9 = self.fc1.bias primals_10 = self.fc2.weight primals_11 = self.fc2.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11]) return output[0]
diogo149/doo
SimpleCNN
false
6,579
[ "MIT" ]
1
d83a1715fb9d4e5eac9f5d3d384a45cfc26fec2f
https://github.com/diogo149/doo/tree/d83a1715fb9d4e5eac9f5d3d384a45cfc26fec2f
HSigmoid
import torch import torch.nn as nn import torch.nn.functional import torch.nn.parallel import torch.utils.data.distributed class HSigmoid(nn.Module): """ Applies the Hard-Sigmoid function element-wise. `"Searching for MobileNetV3" <https://arxiv.org/pdf/1905.02244.pdf>`_ Examples: >>> m = Mish() >>> x = torch.randn(2) >>> output = m(x) """ @staticmethod def forward(x: 'torch.Tensor') ->torch.Tensor: out = torch.nn.functional.relu6(x + 3, inplace=True) / 6.0 return out def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 torch.nn as nn import torch.nn.functional import torch.nn.parallel import torch.utils.data.distributed assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_add_div_hardtanh_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 3.0 tmp2 = tmp0 + tmp1 tmp3 = 0.0 tmp4 = triton_helpers.maximum(tmp2, tmp3) tmp5 = 6.0 tmp6 = triton_helpers.minimum(tmp4, tmp5) tmp7 = 0.16666666666666666 tmp8 = tmp6 * tmp7 tl.store(out_ptr0 + x0, tmp8, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_div_hardtanh_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 return buf0, class HSigmoidNew(nn.Module): """ Applies the Hard-Sigmoid function element-wise. `"Searching for MobileNetV3" <https://arxiv.org/pdf/1905.02244.pdf>`_ Examples: >>> m = Mish() >>> x = torch.randn(2) >>> output = m(x) """ def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
doansangg/CGAN-PyTorch
HSigmoid
false
6,580
[ "Apache-2.0" ]
1
941f5bd75102bed7f2eccd7feb9af8e6134af0e4
https://github.com/doansangg/CGAN-PyTorch/tree/941f5bd75102bed7f2eccd7feb9af8e6134af0e4
MyInstanceNorm2d
import torch from torch import nn class AffineChannelwise(nn.Module): def __init__(self, num_channels): super().__init__() self.num_channels = num_channels self.register_parameter('weight', nn.Parameter(torch.ones( num_channels))) self.register_parameter('bias', nn.Parameter(torch.zeros(num_channels)) ) def forward(self, x): param_shape = [1] * len(x.shape) param_shape[1] = self.num_channels return x * self.weight.reshape(*param_shape) + self.bias.reshape(* param_shape) class MyInstanceNorm2d(nn.Module): def __init__(self, num_features, momentum=0.9, eps=1e-05, affine=False, track_running_stats=False): super().__init__() self.momentum = momentum self.eps = eps if affine: self.affine = AffineChannelwise(num_features) else: self.affine = None self.track_running_stats = track_running_stats if track_running_stats: self.register_buffer('running_mean', torch.zeros(num_features)) self.register_buffer('running_var', torch.ones(num_features)) else: self.register_parameter('running_mean', None) self.register_parameter('running_var', None) def forward(self, x): assert len(x.shape) == 4 b, c, h, w = x.shape if self.training or not self.track_running_stats: mu = x.mean(dim=(2, 3)) sigma = x.var(dim=(2, 3), unbiased=False) else: mu, sigma = self.running_mean, self.running_var b = 1 if self.training and self.track_running_stats: sigma_unbiased = sigma * (h * w / (h * w - 1)) self.running_mean = self.running_mean * (1 - self.momentum ) + mu.mean(dim=0) * self.momentum self.running_var = self.running_var * (1 - self.momentum ) + sigma_unbiased.mean(dim=0) * self.momentum mu = mu.reshape(b, c, 1, 1) sigma = sigma.reshape(b, c, 1, 1) result = (x - mu) / torch.sqrt(sigma + self.eps) if self.affine is not None: result = self.affine(result) return result def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'num_features': 4}]
import torch 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 libdevice from torch import nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_add_div_mean_sqrt_sub_var_0(in_ptr0, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 16 RBLOCK: tl.constexpr = 16 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 + 16 * x0), xmask, other=0.0) tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp3 = tl.where(xmask, tmp1, 0) tmp4 = tl.sum(tmp3, 1)[:, None] tmp6 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp8 = tl.where(xmask, tmp6, 0) tmp9 = tl.sum(tmp8, 1)[:, None] tmp10 = tl.full([XBLOCK, 1], 16, tl.int32) tmp11 = tmp10.to(tl.float32) tmp12 = tmp9 / tmp11 tmp13 = tmp1 - tmp12 tmp14 = tmp13 * tmp13 tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK]) tmp17 = tl.where(xmask, tmp15, 0) tmp18 = tl.sum(tmp17, 1)[:, None] tmp19 = 16.0 tmp20 = tmp4 / tmp19 tmp21 = tmp0 - tmp20 tmp22 = tmp18 / tmp19 tmp23 = 1e-05 tmp24 = tmp22 + tmp23 tmp25 = libdevice.sqrt(tmp24) tmp26 = tmp21 / tmp25 tl.store(out_ptr2 + (r1 + 16 * x0), tmp26, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_per_fused_add_div_mean_sqrt_sub_var_0[grid(16)](arg0_1, buf4, 16, 16, XBLOCK=1, num_warps=2, num_stages=1) del arg0_1 return buf4, class AffineChannelwise(nn.Module): def __init__(self, num_channels): super().__init__() self.num_channels = num_channels self.register_parameter('weight', nn.Parameter(torch.ones( num_channels))) self.register_parameter('bias', nn.Parameter(torch.zeros(num_channels)) ) def forward(self, x): param_shape = [1] * len(x.shape) param_shape[1] = self.num_channels return x * self.weight.reshape(*param_shape) + self.bias.reshape(* param_shape) class MyInstanceNorm2dNew(nn.Module): def __init__(self, num_features, momentum=0.9, eps=1e-05, affine=False, track_running_stats=False): super().__init__() self.momentum = momentum self.eps = eps if affine: self.affine = AffineChannelwise(num_features) else: self.affine = None self.track_running_stats = track_running_stats if track_running_stats: self.register_buffer('running_mean', torch.zeros(num_features)) self.register_buffer('running_var', torch.ones(num_features)) else: self.register_parameter('running_mean', None) self.register_parameter('running_var', None) def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
dniku/dl-norms
MyInstanceNorm2d
false
6,581
[ "MIT" ]
1
0f1eef942bd318ac988ec7dfa9caea300d17e82a
https://github.com/dniku/dl-norms/tree/0f1eef942bd318ac988ec7dfa9caea300d17e82a
TSAFusion
import torch import torch.nn as nn from torch.nn import init as init from torchvision.models import vgg as vgg from torch import autograd as autograd class TSAFusion(nn.Module): """Temporal Spatial Attention (TSA) fusion module. Temporal: Calculate the correlation between center frame and neighboring frames; Spatial: It has 3 pyramid levels, the attention is similar to SFT. (SFT: Recovering realistic texture in image super-resolution by deep spatial feature transform.) Args: num_feat (int): Channel number of middle features. Default: 64. num_frame (int): Number of frames. Default: 5. center_frame_idx (int): The index of center frame. Default: 2. """ def __init__(self, num_feat=64, num_frame=5, center_frame_idx=2): super(TSAFusion, self).__init__() self.center_frame_idx = center_frame_idx self.temporal_attn1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) self.temporal_attn2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) self.feat_fusion = nn.Conv2d(num_frame * num_feat, num_feat, 1, 1) self.max_pool = nn.MaxPool2d(3, stride=2, padding=1) self.avg_pool = nn.AvgPool2d(3, stride=2, padding=1) self.spatial_attn1 = nn.Conv2d(num_frame * num_feat, num_feat, 1) self.spatial_attn2 = nn.Conv2d(num_feat * 2, num_feat, 1) self.spatial_attn3 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) self.spatial_attn4 = nn.Conv2d(num_feat, num_feat, 1) self.spatial_attn5 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) self.spatial_attn_l1 = nn.Conv2d(num_feat, num_feat, 1) self.spatial_attn_l2 = nn.Conv2d(num_feat * 2, num_feat, 3, 1, 1) self.spatial_attn_l3 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) self.spatial_attn_add1 = nn.Conv2d(num_feat, num_feat, 1) self.spatial_attn_add2 = nn.Conv2d(num_feat, num_feat, 1) self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True) self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False) def forward(self, aligned_feat): """ Args: aligned_feat (Tensor): Aligned features with shape (b, t, c, h, w). Returns: Tensor: Features after TSA with the shape (b, c, h, w). """ b, t, c, h, w = aligned_feat.size() embedding_ref = self.temporal_attn1(aligned_feat[:, self. center_frame_idx, :, :, :].clone()) embedding = self.temporal_attn2(aligned_feat.view(-1, c, h, w)) embedding = embedding.view(b, t, -1, h, w) corr_l = [] for i in range(t): emb_neighbor = embedding[:, i, :, :, :] corr = torch.sum(emb_neighbor * embedding_ref, 1) corr_l.append(corr.unsqueeze(1)) corr_prob = torch.sigmoid(torch.cat(corr_l, dim=1)) corr_prob = corr_prob.unsqueeze(2).expand(b, t, c, h, w) corr_prob = corr_prob.contiguous().view(b, -1, h, w) aligned_feat = aligned_feat.view(b, -1, h, w) * corr_prob feat = self.lrelu(self.feat_fusion(aligned_feat)) attn = self.lrelu(self.spatial_attn1(aligned_feat)) attn_max = self.max_pool(attn) attn_avg = self.avg_pool(attn) attn = self.lrelu(self.spatial_attn2(torch.cat([attn_max, attn_avg], dim=1))) attn_level = self.lrelu(self.spatial_attn_l1(attn)) attn_max = self.max_pool(attn_level) attn_avg = self.avg_pool(attn_level) attn_level = self.lrelu(self.spatial_attn_l2(torch.cat([attn_max, attn_avg], dim=1))) attn_level = self.lrelu(self.spatial_attn_l3(attn_level)) attn_level = self.upsample(attn_level) attn = self.lrelu(self.spatial_attn3(attn)) + attn_level attn = self.lrelu(self.spatial_attn4(attn)) attn = self.upsample(attn) attn = self.spatial_attn5(attn) attn_add = self.spatial_attn_add2(self.lrelu(self.spatial_attn_add1 (attn))) attn = torch.sigmoid(attn) feat = feat * attn * 2 + attn_add return feat def get_inputs(): return [torch.rand([4, 5, 64, 4, 4])] 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 import torch.nn as nn from torch.nn import init as init from torchvision.models import vgg as vgg from torch import autograd as autograd 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_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x0 = xindex % 1024 x1 = xindex // 1024 x2 = xindex tmp0 = tl.load(in_ptr0 + (2048 + x0 + 5120 * x1), None) tl.store(out_ptr0 + x2, tmp0, None) @triton.jit def triton_poi_fused_convolution_1(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) x3 = xindex x1 = xindex // 16 % 64 tmp0 = tl.load(in_out_ptr0 + x3, None) tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(in_out_ptr0 + x3, tmp2, None) @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) x3 = xindex x1 = xindex // 16 % 64 tmp0 = tl.load(in_out_ptr0 + x3, None) tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(in_out_ptr0 + x3, tmp2, None) @triton.jit def triton_per_fused_cat_mul_sum_3(in_ptr0, in_ptr1, out_ptr5, out_ptr6, out_ptr7, out_ptr8, out_ptr9, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 64 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) r2 = rindex x0 = xindex % 16 x1 = xindex // 16 tmp0 = tl.load(in_ptr0 + (x0 + 16 * r2 + 5120 * x1), xmask, other=0.0) tmp1 = tl.load(in_ptr1 + (x0 + 16 * r2 + 1024 * x1), xmask, other=0.0) tmp7 = tl.load(in_ptr0 + (1024 + x0 + 16 * r2 + 5120 * x1), xmask, other=0.0) tmp13 = tl.load(in_ptr0 + (2048 + x0 + 16 * r2 + 5120 * x1), xmask, other=0.0) tmp19 = tl.load(in_ptr0 + (3072 + x0 + 16 * r2 + 5120 * x1), xmask, other=0.0) tmp25 = tl.load(in_ptr0 + (4096 + x0 + 16 * r2 + 5120 * x1), xmask, other=0.0) tmp2 = tmp0 * tmp1 tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK]) tmp5 = tl.where(xmask, tmp3, 0) tmp6 = tl.sum(tmp5, 1)[:, None] tmp8 = tmp7 * tmp1 tmp9 = tl.broadcast_to(tmp8, [XBLOCK, RBLOCK]) tmp11 = tl.where(xmask, tmp9, 0) tmp12 = tl.sum(tmp11, 1)[:, None] tmp14 = tmp13 * tmp1 tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK]) tmp17 = tl.where(xmask, tmp15, 0) tmp18 = tl.sum(tmp17, 1)[:, None] tmp20 = tmp19 * tmp1 tmp21 = tl.broadcast_to(tmp20, [XBLOCK, RBLOCK]) tmp23 = tl.where(xmask, tmp21, 0) tmp24 = tl.sum(tmp23, 1)[:, None] tmp26 = tmp25 * tmp1 tmp27 = tl.broadcast_to(tmp26, [XBLOCK, RBLOCK]) tmp29 = tl.where(xmask, tmp27, 0) tmp30 = tl.sum(tmp29, 1)[:, None] tl.store(out_ptr5 + (x0 + 80 * x1), tmp6, xmask) tl.store(out_ptr6 + (x0 + 80 * x1), tmp12, xmask) tl.store(out_ptr7 + (x0 + 80 * x1), tmp18, xmask) tl.store(out_ptr8 + (x0 + 80 * x1), tmp24, xmask) tl.store(out_ptr9 + (x0 + 80 * x1), tmp30, xmask) @triton.jit def triton_poi_fused_mul_4(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl. constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x3 = xindex x0 = xindex % 16 x1 = xindex // 16 % 320 x2 = xindex // 5120 tmp0 = tl.load(in_ptr0 + x3, None) tmp1 = tl.load(in_ptr1 + (x0 + 16 * (x1 // 64) + 80 * x2), None) tmp2 = tl.sigmoid(tmp1) tmp3 = tmp0 * tmp2 tl.store(out_ptr0 + x3, tmp3, None) @triton.jit def triton_poi_fused_convolution_leaky_relu_5(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) x3 = xindex x1 = xindex // 16 % 64 tmp0 = tl.load(in_out_ptr0 + x3, None) tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 0.0 tmp4 = tmp2 > tmp3 tmp5 = 0.1 tmp6 = tmp2 * tmp5 tmp7 = tl.where(tmp4, tmp2, tmp6) tl.store(in_out_ptr0 + x3, tmp7, None) @triton.jit def triton_poi_fused_avg_pool2d_max_pool2d_with_indices_6(in_ptr0, out_ptr0, out_ptr1, out_ptr2, xnumel, XBLOCK: tl.constexpr): xnumel = 1024 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 2 % 2 x0 = xindex % 2 x5 = xindex // 2 x3 = xindex // 256 x6 = xindex % 256 x7 = xindex tmp0 = -1 + 2 * x1 tmp1 = tl.full([1], 0, tl.int64) tmp2 = tmp0 >= tmp1 tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tmp2 & tmp4 tmp6 = -1 + 2 * x0 tmp7 = tmp6 >= tmp1 tmp8 = tmp6 < tmp3 tmp9 = tmp7 & tmp8 tmp10 = tmp5 & tmp9 tmp11 = tl.load(in_ptr0 + (-5 + 2 * x0 + 8 * x5), tmp10 & xmask, eviction_policy='evict_last', other=float('-inf')) tmp12 = 2 * x0 tmp13 = tmp12 >= tmp1 tmp14 = tmp12 < tmp3 tmp15 = tmp13 & tmp14 tmp16 = tmp5 & tmp15 tmp17 = tl.load(in_ptr0 + (-4 + 2 * x0 + 8 * x5), tmp16 & xmask, eviction_policy='evict_last', other=float('-inf')) tmp18 = triton_helpers.maximum(tmp17, tmp11) tmp19 = 1 + 2 * x0 tmp20 = tmp19 >= tmp1 tmp21 = tmp19 < tmp3 tmp22 = tmp20 & tmp21 tmp23 = tmp5 & tmp22 tmp24 = tl.load(in_ptr0 + (-3 + 2 * x0 + 8 * x5), tmp23 & xmask, eviction_policy='evict_last', other=float('-inf')) tmp25 = triton_helpers.maximum(tmp24, tmp18) tmp26 = 2 * x1 tmp27 = tmp26 >= tmp1 tmp28 = tmp26 < tmp3 tmp29 = tmp27 & tmp28 tmp30 = tmp29 & tmp9 tmp31 = tl.load(in_ptr0 + (-1 + 2 * x0 + 8 * x5), tmp30 & xmask, eviction_policy='evict_last', other=float('-inf')) tmp32 = triton_helpers.maximum(tmp31, tmp25) tmp33 = tmp29 & tmp15 tmp34 = tl.load(in_ptr0 + (2 * x0 + 8 * x5), tmp33 & xmask, eviction_policy='evict_last', other=float('-inf')) tmp35 = triton_helpers.maximum(tmp34, tmp32) tmp36 = tmp29 & tmp22 tmp37 = tl.load(in_ptr0 + (1 + 2 * x0 + 8 * x5), tmp36 & xmask, eviction_policy='evict_last', other=float('-inf')) tmp38 = triton_helpers.maximum(tmp37, tmp35) tmp39 = 1 + 2 * x1 tmp40 = tmp39 >= tmp1 tmp41 = tmp39 < tmp3 tmp42 = tmp40 & tmp41 tmp43 = tmp42 & tmp9 tmp44 = tl.load(in_ptr0 + (3 + 2 * x0 + 8 * x5), tmp43 & xmask, eviction_policy='evict_last', other=float('-inf')) tmp45 = triton_helpers.maximum(tmp44, tmp38) tmp46 = tmp42 & tmp15 tmp47 = tl.load(in_ptr0 + (4 + 2 * x0 + 8 * x5), tmp46 & xmask, eviction_policy='evict_last', other=float('-inf')) tmp48 = triton_helpers.maximum(tmp47, tmp45) tmp49 = tmp42 & tmp22 tmp50 = tl.load(in_ptr0 + (5 + 2 * x0 + 8 * x5), tmp49 & xmask, eviction_policy='evict_last', other=float('-inf')) tmp51 = triton_helpers.maximum(tmp50, tmp48) tmp52 = tmp17 > tmp11 tmp53 = tl.full([1], 1, tl.int8) tmp54 = tl.full([1], 0, tl.int8) tmp55 = tl.where(tmp52, tmp53, tmp54) tmp56 = tmp24 > tmp18 tmp57 = tl.full([1], 2, tl.int8) tmp58 = tl.where(tmp56, tmp57, tmp55) tmp59 = tmp31 > tmp25 tmp60 = tl.full([1], 3, tl.int8) tmp61 = tl.where(tmp59, tmp60, tmp58) tmp62 = tmp34 > tmp32 tmp63 = tl.full([1], 4, tl.int8) tmp64 = tl.where(tmp62, tmp63, tmp61) tmp65 = tmp37 > tmp35 tmp66 = tl.full([1], 5, tl.int8) tmp67 = tl.where(tmp65, tmp66, tmp64) tmp68 = tmp44 > tmp38 tmp69 = tl.full([1], 6, tl.int8) tmp70 = tl.where(tmp68, tmp69, tmp67) tmp71 = tmp47 > tmp45 tmp72 = tl.full([1], 7, tl.int8) tmp73 = tl.where(tmp71, tmp72, tmp70) tmp74 = tmp50 > tmp48 tmp75 = tl.full([1], 8, tl.int8) tmp76 = tl.where(tmp74, tmp75, tmp73) tmp77 = tl.load(in_ptr0 + (-5 + 2 * x0 + 8 * x5), tmp10 & xmask, eviction_policy='evict_last', other=0.0) tmp78 = tl.load(in_ptr0 + (-4 + 2 * x0 + 8 * x5), tmp16 & xmask, eviction_policy='evict_last', other=0.0) tmp79 = tmp78 + tmp77 tmp80 = tl.load(in_ptr0 + (-3 + 2 * x0 + 8 * x5), tmp23 & xmask, eviction_policy='evict_last', other=0.0) tmp81 = tmp80 + tmp79 tmp82 = tl.load(in_ptr0 + (-1 + 2 * x0 + 8 * x5), tmp30 & xmask, eviction_policy='evict_last', other=0.0) tmp83 = tmp82 + tmp81 tmp84 = tl.load(in_ptr0 + (2 * x0 + 8 * x5), tmp33 & xmask, eviction_policy='evict_last', other=0.0) tmp85 = tmp84 + tmp83 tmp86 = tl.load(in_ptr0 + (1 + 2 * x0 + 8 * x5), tmp36 & xmask, eviction_policy='evict_last', other=0.0) tmp87 = tmp86 + tmp85 tmp88 = tl.load(in_ptr0 + (3 + 2 * x0 + 8 * x5), tmp43 & xmask, eviction_policy='evict_last', other=0.0) tmp89 = tmp88 + tmp87 tmp90 = tl.load(in_ptr0 + (4 + 2 * x0 + 8 * x5), tmp46 & xmask, eviction_policy='evict_last', other=0.0) tmp91 = tmp90 + tmp89 tmp92 = tl.load(in_ptr0 + (5 + 2 * x0 + 8 * x5), tmp49 & xmask, eviction_policy='evict_last', other=0.0) tmp93 = tmp92 + tmp91 tmp94 = 1 + -2 * x0 + -2 * x1 + (5 * (5 <= 2 + 2 * x0) + (2 + 2 * x0) * (2 + 2 * x0 < 5)) * (5 * (5 <= 2 + 2 * x1) + (2 + 2 * x1) * (2 + 2 * x1 < 5)) + -2 * x0 * (5 * (5 <= 2 + 2 * x1) + (2 + 2 * x1) * (2 + 2 * x1 < 5)) + -2 * x1 * (5 * (5 <= 2 + 2 * x0) + (2 + 2 * x0) * (2 + 2 * x0 < 5)) + 4 * x0 * x1 + (5 * (5 <= 2 + 2 * x0) + (2 + 2 * x0) * (2 + 2 * x0 < 5)) + (5 * (5 <= 2 + 2 * x1) + (2 + 2 * x1) * (2 + 2 * x1 < 5) ) tmp95 = tmp93 / tmp94 tl.store(out_ptr0 + (x6 + 512 * x3), tmp51, xmask) tl.store(out_ptr1 + x7, tmp76, xmask) tl.store(out_ptr2 + (x6 + 512 * x3), tmp95, xmask) @triton.jit def triton_poi_fused_convolution_leaky_relu_7(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 1024 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 4 % 64 tmp0 = tl.load(in_out_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 0.0 tmp4 = tmp2 > tmp3 tmp5 = 0.1 tmp6 = tmp2 * tmp5 tmp7 = tl.where(tmp4, tmp2, tmp6) tl.store(in_out_ptr0 + x3, tmp7, xmask) @triton.jit def triton_poi_fused_avg_pool2d_max_pool2d_with_indices_8(in_ptr0, out_ptr0, out_ptr1, out_ptr2, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 64 x1 = xindex // 64 tmp0 = tl.full([1], -1, tl.int64) tmp1 = tl.full([1], 0, tl.int64) tmp2 = tmp0 >= tmp1 tmp3 = tl.full([1], 2, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tmp2 & tmp4 tmp6 = tmp5 & tmp5 tmp7 = tl.load(in_ptr0 + (-3 + 4 * x2), tmp6 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp8 = tmp1 >= tmp1 tmp9 = tmp1 < tmp3 tmp10 = tmp8 & tmp9 tmp11 = tmp5 & tmp10 tmp12 = tl.load(in_ptr0 + (-2 + 4 * x2), tmp11 & xmask, eviction_policy ='evict_last', other=float('-inf')) tmp13 = triton_helpers.maximum(tmp12, tmp7) tmp14 = tl.full([1], 1, tl.int64) tmp15 = tmp14 >= tmp1 tmp16 = tmp14 < tmp3 tmp17 = tmp15 & tmp16 tmp18 = tmp5 & tmp17 tmp19 = tl.load(in_ptr0 + (-1 + 4 * x2), tmp18 & xmask, eviction_policy ='evict_last', other=float('-inf')) tmp20 = triton_helpers.maximum(tmp19, tmp13) tmp21 = tmp10 & tmp5 tmp22 = tl.load(in_ptr0 + (-1 + 4 * x2), tmp21 & xmask, eviction_policy ='evict_last', other=float('-inf')) tmp23 = triton_helpers.maximum(tmp22, tmp20) tmp24 = tmp10 & tmp10 tmp25 = tl.load(in_ptr0 + 4 * x2, tmp24 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp26 = triton_helpers.maximum(tmp25, tmp23) tmp27 = tmp10 & tmp17 tmp28 = tl.load(in_ptr0 + (1 + 4 * x2), tmp27 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp29 = triton_helpers.maximum(tmp28, tmp26) tmp30 = tmp17 & tmp5 tmp31 = tl.load(in_ptr0 + (1 + 4 * x2), tmp30 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp32 = triton_helpers.maximum(tmp31, tmp29) tmp33 = tmp17 & tmp10 tmp34 = tl.load(in_ptr0 + (2 + 4 * x2), tmp33 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp35 = triton_helpers.maximum(tmp34, tmp32) tmp36 = tmp17 & tmp17 tmp37 = tl.load(in_ptr0 + (3 + 4 * x2), tmp36 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp38 = triton_helpers.maximum(tmp37, tmp35) tmp39 = tmp12 > tmp7 tmp40 = tl.full([1], 1, tl.int8) tmp41 = tl.full([1], 0, tl.int8) tmp42 = tl.where(tmp39, tmp40, tmp41) tmp43 = tmp19 > tmp13 tmp44 = tl.full([1], 2, tl.int8) tmp45 = tl.where(tmp43, tmp44, tmp42) tmp46 = tmp22 > tmp20 tmp47 = tl.full([1], 3, tl.int8) tmp48 = tl.where(tmp46, tmp47, tmp45) tmp49 = tmp25 > tmp23 tmp50 = tl.full([1], 4, tl.int8) tmp51 = tl.where(tmp49, tmp50, tmp48) tmp52 = tmp28 > tmp26 tmp53 = tl.full([1], 5, tl.int8) tmp54 = tl.where(tmp52, tmp53, tmp51) tmp55 = tmp31 > tmp29 tmp56 = tl.full([1], 6, tl.int8) tmp57 = tl.where(tmp55, tmp56, tmp54) tmp58 = tmp34 > tmp32 tmp59 = tl.full([1], 7, tl.int8) tmp60 = tl.where(tmp58, tmp59, tmp57) tmp61 = tmp37 > tmp35 tmp62 = tl.full([1], 8, tl.int8) tmp63 = tl.where(tmp61, tmp62, tmp60) tmp64 = tl.load(in_ptr0 + (-3 + 4 * x2), tmp6 & xmask, eviction_policy= 'evict_last', other=0.0) tmp65 = tl.load(in_ptr0 + (-2 + 4 * x2), tmp11 & xmask, eviction_policy ='evict_last', other=0.0) tmp66 = tmp65 + tmp64 tmp67 = tl.load(in_ptr0 + (-1 + 4 * x2), tmp18 & xmask, eviction_policy ='evict_last', other=0.0) tmp68 = tmp67 + tmp66 tmp69 = tl.load(in_ptr0 + (-1 + 4 * x2), tmp21 & xmask, eviction_policy ='evict_last', other=0.0) tmp70 = tmp69 + tmp68 tmp71 = tl.load(in_ptr0 + 4 * x2, tmp24 & xmask, eviction_policy= 'evict_last', other=0.0) tmp72 = tmp71 + tmp70 tmp73 = tl.load(in_ptr0 + (1 + 4 * x2), tmp27 & xmask, eviction_policy= 'evict_last', other=0.0) tmp74 = tmp73 + tmp72 tmp75 = tl.load(in_ptr0 + (1 + 4 * x2), tmp30 & xmask, eviction_policy= 'evict_last', other=0.0) tmp76 = tmp75 + tmp74 tmp77 = tl.load(in_ptr0 + (2 + 4 * x2), tmp33 & xmask, eviction_policy= 'evict_last', other=0.0) tmp78 = tmp77 + tmp76 tmp79 = tl.load(in_ptr0 + (3 + 4 * x2), tmp36 & xmask, eviction_policy= 'evict_last', other=0.0) tmp80 = tmp79 + tmp78 tmp81 = tl.full([1], 9, tl.int32) tmp82 = tmp80 / tmp81 tl.store(out_ptr0 + (x0 + 128 * x1), tmp38, xmask) tl.store(out_ptr1 + x2, tmp63, xmask) tl.store(out_ptr2 + (x0 + 128 * x1), tmp82, xmask) @triton.jit def triton_poi_fused_convolution_leaky_relu_9(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 64 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 0.0 tmp4 = tmp2 > tmp3 tmp5 = 0.1 tmp6 = tmp2 * tmp5 tmp7 = tl.where(tmp4, tmp2, tmp6) tl.store(in_out_ptr0 + x2, tmp7, xmask) @triton.jit def triton_poi_fused__to_copy_10(out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 2 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = x0 tmp1 = tmp0.to(tl.float32) tmp2 = 0.5 tmp3 = tmp1 + tmp2 tmp4 = tmp3 * tmp2 tmp5 = tmp4 - tmp2 tmp6 = 0.0 tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp7.to(tl.int32) tl.store(out_ptr0 + x0, tmp8, xmask) @triton.jit def triton_poi_fused_add_clamp_11(out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 2 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = x0 tmp1 = tmp0.to(tl.float32) tmp2 = 0.5 tmp3 = tmp1 + tmp2 tmp4 = tmp3 * tmp2 tmp5 = tmp4 - tmp2 tmp6 = 0.0 tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp7.to(tl.int32) tmp9 = tl.full([1], 1, tl.int64) tmp10 = tmp8 + tmp9 tmp11 = tl.full([1], 0, tl.int64) tmp12 = triton_helpers.minimum(tmp10, tmp11) tl.store(out_ptr0 + x0, tmp12, xmask) @triton.jit def triton_poi_fused__to_copy_add_arange_clamp_mul_sub_12(out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 2 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = x0 tmp1 = tmp0.to(tl.float32) tmp2 = 0.5 tmp3 = tmp1 + tmp2 tmp4 = tmp3 * tmp2 tmp5 = tmp4 - tmp2 tmp6 = 0.0 tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp7.to(tl.int32) tmp9 = tmp8.to(tl.float32) tmp10 = tmp7 - tmp9 tmp11 = triton_helpers.maximum(tmp10, tmp6) tmp12 = 1.0 tmp13 = triton_helpers.minimum(tmp11, tmp12) tl.store(out_ptr0 + x0, tmp13, xmask) @triton.jit def triton_poi_fused__unsafe_index_add_convolution_leaky_relu_leaky_relu_backward_mul_sub_13( in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, in_ptr8, in_ptr9, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 1024 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 2 % 2 x0 = xindex % 2 x5 = xindex // 4 x2 = xindex // 4 % 64 x6 = xindex tmp0 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp9 = tl.load(in_ptr2 + x5, xmask, eviction_policy='evict_last') tmp10 = tl.load(in_ptr3 + x2, xmask, eviction_policy='evict_last') tmp17 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last') tmp22 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last') tmp25 = tl.load(in_ptr6 + x6, xmask) tmp26 = tl.load(in_ptr7 + x2, xmask, eviction_policy='evict_last') tmp31 = tl.load(in_ptr8 + x1, xmask, eviction_policy='evict_last') tmp36 = tl.load(in_ptr9 + x1, xmask, eviction_policy='evict_last') tmp1 = tl.full([XBLOCK], 1, tl.int32) tmp2 = tmp0 + tmp1 tmp3 = tmp0 < 0 tl.where(tmp3, tmp2, tmp0) tmp6 = tmp5 + tmp1 tmp7 = tmp5 < 0 tl.where(tmp7, tmp6, tmp5) tmp11 = tmp9 + tmp10 tmp12 = 0.0 tmp13 = tmp11 > tmp12 tmp14 = 0.1 tmp15 = tmp11 * tmp14 tmp16 = tl.where(tmp13, tmp11, tmp15) tmp18 = tmp17 + tmp1 tmp19 = tmp17 < 0 tl.where(tmp19, tmp18, tmp17) tmp21 = tmp16 - tmp16 tmp23 = tmp21 * tmp22 tmp24 = tmp16 + tmp23 tmp27 = tmp25 + tmp26 tmp28 = tmp27 > tmp12 tmp29 = tmp27 * tmp14 tmp30 = tl.where(tmp28, tmp27, tmp29) tmp32 = tmp31 + tmp1 tmp33 = tmp31 < 0 tl.where(tmp33, tmp32, tmp31) tmp35 = tmp24 - tmp24 tmp37 = tmp35 * tmp36 tmp38 = tmp24 + tmp37 tmp39 = tmp30 + tmp38 tmp40 = tmp30 > tmp12 tl.store(in_out_ptr0 + x6, tmp39, xmask) tl.store(out_ptr0 + x6, tmp40, xmask) @triton.jit def triton_poi_fused__to_copy_14(out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 4 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = x0 tmp1 = tmp0.to(tl.float32) tmp2 = 0.5 tmp3 = tmp1 + tmp2 tmp4 = tmp3 * tmp2 tmp5 = tmp4 - tmp2 tmp6 = 0.0 tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp7.to(tl.int32) tl.store(out_ptr0 + x0, tmp8, xmask) @triton.jit def triton_poi_fused_add_clamp_15(out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 4 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = x0 tmp1 = tmp0.to(tl.float32) tmp2 = 0.5 tmp3 = tmp1 + tmp2 tmp4 = tmp3 * tmp2 tmp5 = tmp4 - tmp2 tmp6 = 0.0 tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp7.to(tl.int32) tmp9 = tl.full([1], 1, tl.int64) tmp10 = tmp8 + tmp9 tmp11 = triton_helpers.minimum(tmp10, tmp9) tl.store(out_ptr0 + x0, tmp11, xmask) @triton.jit def triton_poi_fused__to_copy_add_arange_clamp_mul_sub_16(out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 4 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = x0 tmp1 = tmp0.to(tl.float32) tmp2 = 0.5 tmp3 = tmp1 + tmp2 tmp4 = tmp3 * tmp2 tmp5 = tmp4 - tmp2 tmp6 = 0.0 tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp7.to(tl.int32) tmp9 = tmp8.to(tl.float32) tmp10 = tmp7 - tmp9 tmp11 = triton_helpers.maximum(tmp10, tmp6) tmp12 = 1.0 tmp13 = triton_helpers.minimum(tmp11, tmp12) tl.store(out_ptr0 + x0, tmp13, xmask) @triton.jit def triton_poi_fused__unsafe_index_add_convolution_leaky_relu_mul_sub_17( in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x1 = xindex // 4 % 4 x0 = xindex % 4 x6 = xindex // 16 x2 = xindex // 16 % 64 x4 = xindex tmp0 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last') tmp5 = tl.load(in_ptr1 + x0, None, eviction_policy='evict_last') tmp10 = tl.load(in_ptr3 + x2, None, eviction_policy='evict_last') tmp17 = tl.load(in_ptr4 + x0, None, eviction_policy='evict_last') tmp27 = tl.load(in_ptr5 + x0, None, eviction_policy='evict_last') tmp30 = tl.load(in_ptr6 + x1, None, eviction_policy='evict_last') tmp48 = tl.load(in_ptr7 + x1, None, eviction_policy='evict_last') tmp1 = tl.full([XBLOCK], 2, tl.int32) tmp2 = tmp0 + tmp1 tmp3 = tmp0 < 0 tmp4 = tl.where(tmp3, tmp2, tmp0) tmp6 = tmp5 + tmp1 tmp7 = tmp5 < 0 tmp8 = tl.where(tmp7, tmp6, tmp5) tmp9 = tl.load(in_ptr2 + (tmp8 + 2 * tmp4 + 4 * x6), None, eviction_policy='evict_last') tmp11 = tmp9 + tmp10 tmp12 = 0.0 tmp13 = tmp11 > tmp12 tmp14 = 0.1 tmp15 = tmp11 * tmp14 tmp16 = tl.where(tmp13, tmp11, tmp15) tmp18 = tmp17 + tmp1 tmp19 = tmp17 < 0 tmp20 = tl.where(tmp19, tmp18, tmp17) tmp21 = tl.load(in_ptr2 + (tmp20 + 2 * tmp4 + 4 * x6), None, eviction_policy='evict_last') tmp22 = tmp21 + tmp10 tmp23 = tmp22 > tmp12 tmp24 = tmp22 * tmp14 tmp25 = tl.where(tmp23, tmp22, tmp24) tmp26 = tmp25 - tmp16 tmp28 = tmp26 * tmp27 tmp29 = tmp16 + tmp28 tmp31 = tmp30 + tmp1 tmp32 = tmp30 < 0 tmp33 = tl.where(tmp32, tmp31, tmp30) tmp34 = tl.load(in_ptr2 + (tmp8 + 2 * tmp33 + 4 * x6), None, eviction_policy='evict_last') tmp35 = tmp34 + tmp10 tmp36 = tmp35 > tmp12 tmp37 = tmp35 * tmp14 tmp38 = tl.where(tmp36, tmp35, tmp37) tmp39 = tl.load(in_ptr2 + (tmp20 + 2 * tmp33 + 4 * x6), None, eviction_policy='evict_last') tmp40 = tmp39 + tmp10 tmp41 = tmp40 > tmp12 tmp42 = tmp40 * tmp14 tmp43 = tl.where(tmp41, tmp40, tmp42) tmp44 = tmp43 - tmp38 tmp45 = tmp44 * tmp27 tmp46 = tmp38 + tmp45 tmp47 = tmp46 - tmp29 tmp49 = tmp47 * tmp48 tmp50 = tmp29 + tmp49 tl.store(in_out_ptr0 + x4, tmp50, None) @triton.jit def triton_poi_fused_add_convolution_leaky_relu_mul_sigmoid_18(in_out_ptr0, in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x3 = xindex x1 = xindex // 16 % 64 tmp0 = tl.load(in_out_ptr0 + x3, None) tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last') tmp8 = tl.load(in_ptr1 + x3, None) tmp13 = tl.load(in_out_ptr1 + x3, None) tmp14 = tl.load(in_ptr2 + x1, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 0.0 tmp4 = tmp2 > tmp3 tmp5 = 0.1 tmp6 = tmp2 * tmp5 tmp7 = tl.where(tmp4, tmp2, tmp6) tmp9 = tl.sigmoid(tmp8) tmp10 = tmp7 * tmp9 tmp11 = 2.0 tmp12 = tmp10 * tmp11 tmp15 = tmp13 + tmp14 tmp16 = tmp12 + tmp15 tl.store(in_out_ptr0 + x3, tmp2, None) tl.store(in_out_ptr1 + x3, tmp16, None) @triton.jit def triton_poi_fused_convolution_leaky_relu_leaky_relu_backward_19(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 1024 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 4 % 64 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 0.0 tmp4 = tmp2 > tmp3 tmp5 = 0.1 tmp6 = tmp2 * tmp5 tmp7 = tl.where(tmp4, tmp2, tmp6) tmp8 = tmp7 > tmp3 tl.store(out_ptr0 + x3, tmp8, xmask) @triton.jit def triton_poi_fused_convolution_leaky_relu_leaky_relu_backward_20(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 64 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 0.0 tmp4 = tmp2 > tmp3 tmp5 = 0.1 tmp6 = tmp2 * tmp5 tmp7 = tl.where(tmp4, tmp2, tmp6) tmp8 = tmp7 > tmp3 tl.store(out_ptr0 + x2, tmp8, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13, primals_14, primals_15, primals_16, primals_17, primals_18, primals_19, primals_20, primals_21, primals_22, primals_23, primals_24, primals_25, primals_26, primals_27) = args args.clear() assert_size_stride(primals_1, (4, 5, 64, 4, 4), (5120, 1024, 16, 4, 1)) assert_size_stride(primals_2, (64, 64, 3, 3), (576, 9, 3, 1)) assert_size_stride(primals_3, (64,), (1,)) assert_size_stride(primals_4, (64, 64, 3, 3), (576, 9, 3, 1)) assert_size_stride(primals_5, (64,), (1,)) assert_size_stride(primals_6, (64, 320, 1, 1), (320, 1, 1, 1)) assert_size_stride(primals_7, (64,), (1,)) assert_size_stride(primals_8, (64, 320, 1, 1), (320, 1, 1, 1)) assert_size_stride(primals_9, (64,), (1,)) assert_size_stride(primals_10, (64, 128, 1, 1), (128, 1, 1, 1)) assert_size_stride(primals_11, (64,), (1,)) assert_size_stride(primals_12, (64, 64, 1, 1), (64, 1, 1, 1)) assert_size_stride(primals_13, (64,), (1,)) assert_size_stride(primals_14, (64, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_15, (64,), (1,)) assert_size_stride(primals_16, (64, 64, 3, 3), (576, 9, 3, 1)) assert_size_stride(primals_17, (64,), (1,)) assert_size_stride(primals_18, (64, 64, 3, 3), (576, 9, 3, 1)) assert_size_stride(primals_19, (64,), (1,)) assert_size_stride(primals_20, (64, 64, 1, 1), (64, 1, 1, 1)) assert_size_stride(primals_21, (64,), (1,)) assert_size_stride(primals_22, (64, 64, 3, 3), (576, 9, 3, 1)) assert_size_stride(primals_23, (64,), (1,)) assert_size_stride(primals_24, (64, 64, 1, 1), (64, 1, 1, 1)) assert_size_stride(primals_25, (64,), (1,)) assert_size_stride(primals_26, (64, 64, 1, 1), (64, 1, 1, 1)) assert_size_stride(primals_27, (64,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 64, 4, 4), (1024, 16, 4, 1), torch. float32) get_raw_stream(0) triton_poi_fused_clone_0[grid(4096)](primals_1, buf0, 4096, XBLOCK= 128, num_warps=4, num_stages=1) buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf1, (4, 64, 4, 4), (1024, 16, 4, 1)) buf2 = buf1 del buf1 triton_poi_fused_convolution_1[grid(4096)](buf2, primals_3, 4096, XBLOCK=256, num_warps=4, num_stages=1) del primals_3 buf3 = extern_kernels.convolution(reinterpret_tensor(primals_1, (20, 64, 4, 4), (1024, 16, 4, 1), 0), primals_4, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf3, (20, 64, 4, 4), (1024, 16, 4, 1)) buf4 = buf3 del buf3 triton_poi_fused_convolution_2[grid(20480)](buf4, primals_5, 20480, XBLOCK=256, num_warps=4, num_stages=1) del primals_5 buf15 = empty_strided_cuda((4, 5, 4, 4), (80, 16, 4, 1), torch.float32) buf10 = reinterpret_tensor(buf15, (4, 1, 4, 4), (80, 16, 4, 1), 0) buf11 = reinterpret_tensor(buf15, (4, 1, 4, 4), (80, 16, 4, 1), 16) buf12 = reinterpret_tensor(buf15, (4, 1, 4, 4), (80, 16, 4, 1), 32) buf13 = reinterpret_tensor(buf15, (4, 1, 4, 4), (80, 16, 4, 1), 48) buf14 = reinterpret_tensor(buf15, (4, 1, 4, 4), (80, 16, 4, 1), 64) triton_per_fused_cat_mul_sum_3[grid(64)](buf4, buf2, buf10, buf11, buf12, buf13, buf14, 64, 64, XBLOCK=32, num_warps=8, num_stages=1) buf16 = empty_strided_cuda((4, 320, 4, 4), (5120, 16, 4, 1), torch. float32) triton_poi_fused_mul_4[grid(20480)](primals_1, buf15, buf16, 20480, XBLOCK=256, num_warps=4, num_stages=1) buf17 = extern_kernels.convolution(buf16, primals_6, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf17, (4, 64, 4, 4), (1024, 16, 4, 1)) buf19 = extern_kernels.convolution(buf16, primals_8, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf19, (4, 64, 4, 4), (1024, 16, 4, 1)) buf20 = buf19 del buf19 triton_poi_fused_convolution_leaky_relu_5[grid(4096)](buf20, primals_9, 4096, XBLOCK=256, num_warps=4, num_stages=1) del primals_9 buf24 = empty_strided_cuda((4, 128, 2, 2), (512, 4, 2, 1), torch. float32) buf21 = reinterpret_tensor(buf24, (4, 64, 2, 2), (512, 4, 2, 1), 0) buf22 = empty_strided_cuda((4, 64, 2, 2), (256, 4, 2, 1), torch.int8) buf23 = reinterpret_tensor(buf24, (4, 64, 2, 2), (512, 4, 2, 1), 256) triton_poi_fused_avg_pool2d_max_pool2d_with_indices_6[grid(1024)](buf20 , buf21, buf22, buf23, 1024, XBLOCK=128, num_warps=4, num_stages=1) buf25 = extern_kernels.convolution(buf24, primals_10, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf25, (4, 64, 2, 2), (256, 4, 2, 1)) buf26 = buf25 del buf25 triton_poi_fused_convolution_leaky_relu_7[grid(1024)](buf26, primals_11, 1024, XBLOCK=128, num_warps=4, num_stages=1) del primals_11 buf27 = extern_kernels.convolution(buf26, primals_12, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf27, (4, 64, 2, 2), (256, 4, 2, 1)) buf28 = buf27 del buf27 triton_poi_fused_convolution_leaky_relu_7[grid(1024)](buf28, primals_13, 1024, XBLOCK=128, num_warps=4, num_stages=1) del primals_13 buf32 = empty_strided_cuda((4, 128, 1, 1), (128, 1, 1, 1), torch. float32) buf29 = reinterpret_tensor(buf32, (4, 64, 1, 1), (128, 1, 1, 1), 0) buf30 = empty_strided_cuda((4, 64, 1, 1), (64, 1, 1, 1), torch.int8) buf31 = reinterpret_tensor(buf32, (4, 64, 1, 1), (128, 1, 1, 1), 64) triton_poi_fused_avg_pool2d_max_pool2d_with_indices_8[grid(256)](buf28, buf29, buf30, buf31, 256, XBLOCK=128, num_warps=4, num_stages=1) buf33 = extern_kernels.convolution(buf32, primals_14, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf33, (4, 64, 1, 1), (64, 1, 1, 1)) buf34 = buf33 del buf33 triton_poi_fused_convolution_leaky_relu_9[grid(256)](buf34, primals_15, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_15 buf35 = extern_kernels.convolution(buf34, primals_16, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf35, (4, 64, 1, 1), (64, 1, 1, 1)) buf36 = empty_strided_cuda((2, 1), (1, 1), torch.int64) triton_poi_fused__to_copy_10[grid(2)](buf36, 2, XBLOCK=2, num_warps =1, num_stages=1) buf37 = empty_strided_cuda((2, 1), (1, 1), torch.int64) triton_poi_fused_add_clamp_11[grid(2)](buf37, 2, XBLOCK=2, num_warps=1, num_stages=1) buf38 = empty_strided_cuda((2,), (1,), torch.int64) triton_poi_fused__to_copy_10[grid(2)](buf38, 2, XBLOCK=2, num_warps =1, num_stages=1) buf39 = empty_strided_cuda((2,), (1,), torch.int64) triton_poi_fused_add_clamp_11[grid(2)](buf39, 2, XBLOCK=2, num_warps=1, num_stages=1) buf40 = empty_strided_cuda((2,), (1,), torch.float32) triton_poi_fused__to_copy_add_arange_clamp_mul_sub_12[grid(2)](buf40, 2, XBLOCK=2, num_warps=1, num_stages=1) buf42 = empty_strided_cuda((2, 1), (1, 1), torch.float32) triton_poi_fused__to_copy_add_arange_clamp_mul_sub_12[grid(2)](buf42, 2, XBLOCK=2, num_warps=1, num_stages=1) buf43 = extern_kernels.convolution(buf26, primals_18, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf43, (4, 64, 2, 2), (256, 4, 2, 1)) buf41 = empty_strided_cuda((4, 64, 2, 2), (256, 4, 2, 1), torch.float32 ) buf44 = buf41 del buf41 buf62 = empty_strided_cuda((4, 64, 2, 2), (256, 4, 2, 1), torch.bool) triton_poi_fused__unsafe_index_add_convolution_leaky_relu_leaky_relu_backward_mul_sub_13[ grid(1024)](buf44, buf36, buf38, buf35, primals_17, buf39, buf40, buf43, primals_19, buf37, buf42, buf62, 1024, XBLOCK=256, num_warps=4, num_stages=1) del buf43 del primals_19 buf45 = extern_kernels.convolution(buf44, primals_20, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf45, (4, 64, 2, 2), (256, 4, 2, 1)) buf46 = empty_strided_cuda((4, 1), (1, 1), torch.int64) triton_poi_fused__to_copy_14[grid(4)](buf46, 4, XBLOCK=4, num_warps =1, num_stages=1) buf47 = empty_strided_cuda((4, 1), (1, 1), torch.int64) triton_poi_fused_add_clamp_15[grid(4)](buf47, 4, XBLOCK=4, num_warps=1, num_stages=1) buf48 = empty_strided_cuda((4,), (1,), torch.int64) triton_poi_fused__to_copy_14[grid(4)](buf48, 4, XBLOCK=4, num_warps =1, num_stages=1) buf49 = empty_strided_cuda((4,), (1,), torch.int64) triton_poi_fused_add_clamp_15[grid(4)](buf49, 4, XBLOCK=4, num_warps=1, num_stages=1) buf50 = empty_strided_cuda((4,), (1,), torch.float32) triton_poi_fused__to_copy_add_arange_clamp_mul_sub_16[grid(4)](buf50, 4, XBLOCK=4, num_warps=1, num_stages=1) buf52 = empty_strided_cuda((4, 1), (1, 1), torch.float32) triton_poi_fused__to_copy_add_arange_clamp_mul_sub_16[grid(4)](buf52, 4, XBLOCK=4, num_warps=1, num_stages=1) buf53 = empty_strided_cuda((4, 64, 4, 4), (1024, 16, 4, 1), torch. float32) buf54 = buf53 del buf53 triton_poi_fused__unsafe_index_add_convolution_leaky_relu_mul_sub_17[ grid(4096)](buf54, buf46, buf48, buf45, primals_21, buf49, buf50, buf47, buf52, 4096, XBLOCK=128, num_warps=4, num_stages=1) buf55 = extern_kernels.convolution(buf54, primals_22, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf55, (4, 64, 4, 4), (1024, 16, 4, 1)) buf56 = buf55 del buf55 triton_poi_fused_convolution_1[grid(4096)](buf56, primals_23, 4096, XBLOCK=256, num_warps=4, num_stages=1) del primals_23 buf57 = extern_kernels.convolution(buf56, primals_24, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf57, (4, 64, 4, 4), (1024, 16, 4, 1)) buf58 = buf57 del buf57 triton_poi_fused_convolution_leaky_relu_5[grid(4096)](buf58, primals_25, 4096, XBLOCK=256, num_warps=4, num_stages=1) del primals_25 buf59 = extern_kernels.convolution(buf58, primals_26, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf59, (4, 64, 4, 4), (1024, 16, 4, 1)) buf18 = buf17 del buf17 buf60 = buf59 del buf59 triton_poi_fused_add_convolution_leaky_relu_mul_sigmoid_18[grid(4096)]( buf18, buf60, primals_7, buf56, primals_27, 4096, XBLOCK=128, num_warps=4, num_stages=1) del primals_27 del primals_7 buf61 = empty_strided_cuda((4, 64, 2, 2), (256, 4, 2, 1), torch.bool) triton_poi_fused_convolution_leaky_relu_leaky_relu_backward_19[grid (1024)](buf45, primals_21, buf61, 1024, XBLOCK=256, num_warps=4, num_stages=1) del buf45 del primals_21 buf63 = empty_strided_cuda((4, 64, 1, 1), (64, 1, 1, 1), torch.bool) triton_poi_fused_convolution_leaky_relu_leaky_relu_backward_20[grid (256)](buf35, primals_17, buf63, 256, XBLOCK=128, num_warps=4, num_stages=1) del buf35 del primals_17 return (buf60, primals_1, primals_2, primals_4, primals_6, primals_8, primals_10, primals_12, primals_14, primals_16, primals_18, primals_20, primals_22, primals_24, primals_26, buf0, buf2, reinterpret_tensor(buf4, (4, 64, 4, 4), (5120, 16, 4, 1), 0), reinterpret_tensor(buf4, (4, 64, 4, 4), (5120, 16, 4, 1), 1024), reinterpret_tensor(buf4, (4, 64, 4, 4), (5120, 16, 4, 1), 2048), reinterpret_tensor(buf4, (4, 64, 4, 4), (5120, 16, 4, 1), 3072), reinterpret_tensor(buf4, (4, 64, 4, 4), (5120, 16, 4, 1), 4096), buf15, buf16, buf18, buf20, buf22, buf24, buf26, buf28, buf30, buf32, buf34, buf36, buf37, buf38, buf39, buf40, buf42, buf44, buf46, buf47, buf48, buf49, buf50, buf52, buf54, buf56, buf58, buf61, buf62, buf63) class TSAFusionNew(nn.Module): """Temporal Spatial Attention (TSA) fusion module. Temporal: Calculate the correlation between center frame and neighboring frames; Spatial: It has 3 pyramid levels, the attention is similar to SFT. (SFT: Recovering realistic texture in image super-resolution by deep spatial feature transform.) Args: num_feat (int): Channel number of middle features. Default: 64. num_frame (int): Number of frames. Default: 5. center_frame_idx (int): The index of center frame. Default: 2. """ def __init__(self, num_feat=64, num_frame=5, center_frame_idx=2): super(TSAFusionNew, self).__init__() self.center_frame_idx = center_frame_idx self.temporal_attn1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) self.temporal_attn2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) self.feat_fusion = nn.Conv2d(num_frame * num_feat, num_feat, 1, 1) self.max_pool = nn.MaxPool2d(3, stride=2, padding=1) self.avg_pool = nn.AvgPool2d(3, stride=2, padding=1) self.spatial_attn1 = nn.Conv2d(num_frame * num_feat, num_feat, 1) self.spatial_attn2 = nn.Conv2d(num_feat * 2, num_feat, 1) self.spatial_attn3 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) self.spatial_attn4 = nn.Conv2d(num_feat, num_feat, 1) self.spatial_attn5 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) self.spatial_attn_l1 = nn.Conv2d(num_feat, num_feat, 1) self.spatial_attn_l2 = nn.Conv2d(num_feat * 2, num_feat, 3, 1, 1) self.spatial_attn_l3 = nn.Conv2d(num_feat, num_feat, 3, 1, 1) self.spatial_attn_add1 = nn.Conv2d(num_feat, num_feat, 1) self.spatial_attn_add2 = nn.Conv2d(num_feat, num_feat, 1) self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True) self.upsample = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False) def forward(self, input_0): primals_2 = self.temporal_attn1.weight primals_3 = self.temporal_attn1.bias primals_4 = self.temporal_attn2.weight primals_5 = self.temporal_attn2.bias primals_6 = self.feat_fusion.weight primals_7 = self.feat_fusion.bias primals_8 = self.spatial_attn1.weight primals_9 = self.spatial_attn1.bias primals_10 = self.spatial_attn2.weight primals_11 = self.spatial_attn2.bias primals_16 = self.spatial_attn3.weight primals_13 = self.spatial_attn3.bias primals_12 = self.spatial_attn4.weight primals_15 = self.spatial_attn4.bias primals_18 = self.spatial_attn5.weight primals_17 = self.spatial_attn5.bias primals_20 = self.spatial_attn_l1.weight primals_19 = self.spatial_attn_l1.bias primals_14 = self.spatial_attn_l2.weight primals_21 = self.spatial_attn_l2.bias primals_22 = self.spatial_attn_l3.weight primals_23 = self.spatial_attn_l3.bias primals_24 = self.spatial_attn_add1.weight primals_25 = self.spatial_attn_add1.bias primals_26 = self.spatial_attn_add2.weight primals_27 = self.spatial_attn_add2.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13, primals_14, primals_15, primals_16, primals_17, primals_18, primals_19, primals_20, primals_21, primals_22, primals_23, primals_24, primals_25, primals_26, primals_27]) return output[0]
cyysc1998/EDVRDarts
TSAFusion
false
6,582
[ "MIT" ]
1
201badbc8c6469b519647a8869c3782ebe1176cf
https://github.com/cyysc1998/EDVRDarts/tree/201badbc8c6469b519647a8869c3782ebe1176cf
MyGroupNorm
import torch from torch import nn class AffineChannelwise(nn.Module): def __init__(self, num_channels): super().__init__() self.num_channels = num_channels self.register_parameter('weight', nn.Parameter(torch.ones( num_channels))) self.register_parameter('bias', nn.Parameter(torch.zeros(num_channels)) ) def forward(self, x): param_shape = [1] * len(x.shape) param_shape[1] = self.num_channels return x * self.weight.reshape(*param_shape) + self.bias.reshape(* param_shape) class MyGroupNorm(nn.Module): def __init__(self, num_groups, num_channels, eps=1e-05, affine=True): super().__init__() assert num_channels % num_groups == 0 self.num_groups = num_groups self.num_channels = num_channels self.eps = eps if affine: self.affine = AffineChannelwise(num_channels) else: self.affine = None def forward(self, x): assert len(x.shape) == 4 b, c, h, w = x.shape assert c == self.num_channels g = c // self.num_groups x = x.reshape(b, self.num_groups, g, h, w) mu = x.mean(dim=(2, 3, 4), keepdim=True) sigma = x.var(dim=(2, 3, 4), unbiased=False, keepdim=True) result = (x - mu) / torch.sqrt(sigma + self.eps) result = result.reshape(b, c, h, w) if self.affine is not None: result = self.affine(result) return result def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'num_groups': 1, 'num_channels': 4}]
import torch 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 libdevice from torch import 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_add_mean_mul_sqrt_var_0(in_out_ptr0, in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, 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 r3 = rindex // 16 tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0) tmp27 = tl.load(in_ptr1 + r3, None, eviction_policy='evict_last') tmp29 = tl.load(in_ptr2 + r3, None, eviction_policy='evict_last') tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp3 = tl.where(xmask, tmp1, 0) tmp4 = tl.sum(tmp3, 1)[:, None] tmp6 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp8 = tl.where(xmask, tmp6, 0) tmp9 = tl.sum(tmp8, 1)[:, None] tmp10 = tl.full([XBLOCK, 1], 64, tl.int32) tmp11 = tmp10.to(tl.float32) tmp12 = tmp9 / tmp11 tmp13 = tmp1 - tmp12 tmp14 = tmp13 * tmp13 tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK]) tmp17 = tl.where(xmask, tmp15, 0) tmp18 = tl.sum(tmp17, 1)[:, None] tmp19 = 64.0 tmp20 = tmp4 / tmp19 tmp21 = tmp18 / tmp19 tmp22 = 1e-05 tmp23 = tmp21 + tmp22 tmp24 = libdevice.sqrt(tmp23) tmp25 = tmp0 - tmp20 tmp26 = tmp25 / tmp24 tmp28 = tmp26 * tmp27 tmp30 = tmp28 + tmp29 tl.debug_barrier() tl.store(in_out_ptr0 + x0, tmp20, xmask) tl.debug_barrier() tl.store(in_out_ptr1 + x0, tmp24, xmask) tl.store(out_ptr0 + (r1 + 64 * x0), tmp30, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 1, 1, 1, 1), (1, 4, 4, 4, 4), torch. float32) buf3 = empty_strided_cuda((4, 1, 1, 1, 1), (1, 4, 4, 4, 4), torch. float32) buf1 = reinterpret_tensor(buf0, (4, 1, 1, 1, 1), (1, 1, 1, 1, 1), 0) del buf0 buf5 = reinterpret_tensor(buf3, (4, 1, 1, 1, 1), (1, 1, 1, 1, 1), 0) del buf3 buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_per_fused_add_mean_mul_sqrt_var_0[grid(4)](buf1, buf5, primals_1, primals_2, primals_3, buf6, 4, 64, XBLOCK=1, num_warps=2, num_stages=1) del primals_2 del primals_3 return buf6, primals_1, buf1, buf5 class AffineChannelwise(nn.Module): def __init__(self, num_channels): super().__init__() self.num_channels = num_channels self.register_parameter('weight', nn.Parameter(torch.ones( num_channels))) self.register_parameter('bias', nn.Parameter(torch.zeros(num_channels)) ) def forward(self, x): param_shape = [1] * len(x.shape) param_shape[1] = self.num_channels return x * self.weight.reshape(*param_shape) + self.bias.reshape(* param_shape) class MyGroupNormNew(nn.Module): def __init__(self, num_groups, num_channels, eps=1e-05, affine=True): super().__init__() assert num_channels % num_groups == 0 self.num_groups = num_groups self.num_channels = num_channels self.eps = eps if affine: self.affine = AffineChannelwise(num_channels) else: self.affine = None def forward(self, input_0): primals_2 = self.affine.weight primals_3 = self.affine.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
dniku/dl-norms
MyGroupNorm
false
6,583
[ "MIT" ]
1
0f1eef942bd318ac988ec7dfa9caea300d17e82a
https://github.com/dniku/dl-norms/tree/0f1eef942bd318ac988ec7dfa9caea300d17e82a
HSwish
import torch import torch.nn as nn import torch.nn.functional import torch.nn.parallel import torch.utils.data.distributed class HSwish(nn.Module): """ Applies the Hard-Swish function element-wise. `"Searching for MobileNetV3" <https://arxiv.org/pdf/1905.02244.pdf>`_ Examples: >>> m = Mish() >>> x = torch.randn(2) >>> output = m(x) """ @staticmethod def forward(x: 'torch.Tensor') ->torch.Tensor: out = x * torch.nn.functional.relu6(x + 3, inplace=True) / 6.0 return out def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 torch.nn as nn import torch.nn.functional import torch.nn.parallel import torch.utils.data.distributed assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_add_div_hardtanh_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 3.0 tmp2 = tmp0 + tmp1 tmp3 = 0.0 tmp4 = triton_helpers.maximum(tmp2, tmp3) tmp5 = 6.0 tmp6 = triton_helpers.minimum(tmp4, tmp5) tmp7 = tmp0 * tmp6 tmp8 = 0.16666666666666666 tmp9 = tmp7 * tmp8 tl.store(out_ptr0 + x0, tmp9, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_div_hardtanh_mul_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 return buf0, class HSwishNew(nn.Module): """ Applies the Hard-Swish function element-wise. `"Searching for MobileNetV3" <https://arxiv.org/pdf/1905.02244.pdf>`_ Examples: >>> m = Mish() >>> x = torch.randn(2) >>> output = m(x) """ def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
doansangg/CGAN-PyTorch
HSwish
false
6,584
[ "Apache-2.0" ]
1
941f5bd75102bed7f2eccd7feb9af8e6134af0e4
https://github.com/doansangg/CGAN-PyTorch/tree/941f5bd75102bed7f2eccd7feb9af8e6134af0e4
AffineChannelwise
import torch from torch import nn class AffineChannelwise(nn.Module): def __init__(self, num_channels): super().__init__() self.num_channels = num_channels self.register_parameter('weight', nn.Parameter(torch.ones( num_channels))) self.register_parameter('bias', nn.Parameter(torch.zeros(num_channels)) ) def forward(self, x): param_shape = [1] * len(x.shape) param_shape[1] = self.num_channels return x * self.weight.reshape(*param_shape) + self.bias.reshape(* param_shape) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'num_channels': 4}]
import torch 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 import nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_add_mul_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 16 % 4 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 * tmp1 tmp4 = tmp2 + tmp3 tl.store(out_ptr0 + x3, tmp4, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_mul_0[grid(256)](primals_1, primals_2, primals_3, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 del primals_3 return buf0, primals_1 class AffineChannelwiseNew(nn.Module): def __init__(self, num_channels): super().__init__() self.num_channels = num_channels self.register_parameter('weight', nn.Parameter(torch.ones( num_channels))) self.register_parameter('bias', nn.Parameter(torch.zeros(num_channels)) ) def forward(self, input_0): primals_2 = self.weight primals_3 = self.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
dniku/dl-norms
AffineChannelwise
false
6,585
[ "MIT" ]
1
0f1eef942bd318ac988ec7dfa9caea300d17e82a
https://github.com/dniku/dl-norms/tree/0f1eef942bd318ac988ec7dfa9caea300d17e82a
Model
import torch import torch.nn as nn import torch.utils.data import torch.nn.functional as f class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.conv = nn.Conv2d(1, 16, 5) self.pool = nn.MaxPool2d(2, 2) self.fc = nn.Linear(2304, 10) def forward(self, x): x = self.pool(f.relu(self.conv(x))) x = x.view(-1, 2304) logit_output = self.fc(x) return logit_output def get_inputs(): return [torch.rand([4, 1, 64, 64])] 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 import torch.nn as nn import torch.utils.data 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_convolution_relu_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 230400 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 3600 % 16 x0 = xindex % 3600 x4 = xindex // 3600 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(out_ptr0 + (x0 + 3616 * x4), tmp4, xmask) @triton.jit def triton_poi_fused_max_pool2d_with_indices_1(in_ptr0, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 57600 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 30 x1 = xindex // 30 % 30 x4 = xindex // 900 x3 = xindex // 14400 x5 = xindex % 14400 x6 = xindex tmp0 = tl.load(in_ptr0 + (2 * x0 + 120 * x1 + 3616 * x4), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 120 * x1 + 3616 * x4), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr0 + (60 + 2 * x0 + 120 * x1 + 3616 * x4), xmask, eviction_policy='evict_last') tmp12 = tl.load(in_ptr0 + (61 + 2 * x0 + 120 * x1 + 3616 * x4), xmask, eviction_policy='evict_last') tmp2 = tmp1 > tmp0 tmp3 = tl.full([1], 1, tl.int8) tmp4 = tl.full([1], 0, tl.int8) tmp5 = tl.where(tmp2, tmp3, tmp4) tmp6 = triton_helpers.maximum(tmp1, tmp0) tmp8 = tmp7 > tmp6 tmp9 = tl.full([1], 2, tl.int8) tmp10 = tl.where(tmp8, tmp9, tmp5) tmp11 = triton_helpers.maximum(tmp7, tmp6) tmp13 = tmp12 > tmp11 tmp14 = tl.full([1], 3, tl.int8) tmp15 = tl.where(tmp13, tmp14, tmp10) tmp16 = triton_helpers.maximum(tmp12, tmp11) tl.store(out_ptr0 + (x5 + 14464 * x3), tmp15, xmask) tl.store(out_ptr1 + x6, tmp16, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (16, 1, 5, 5), (25, 25, 5, 1)) assert_size_stride(primals_2, (16,), (1,)) assert_size_stride(primals_3, (4, 1, 64, 64), (4096, 4096, 64, 1)) assert_size_stride(primals_4, (10, 2304), (2304, 1)) assert_size_stride(primals_5, (10,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 16, 60, 60), (57600, 3600, 60, 1)) buf1 = empty_strided_cuda((4, 16, 60, 60), (57856, 3616, 60, 1), torch.float32) get_raw_stream(0) triton_poi_fused_convolution_relu_0[grid(230400)](buf0, primals_2, buf1, 230400, XBLOCK=1024, num_warps=4, num_stages=1) del buf0 del primals_2 buf2 = empty_strided_cuda((4, 16, 30, 30), (14464, 900, 30, 1), torch.int8) buf3 = empty_strided_cuda((4, 16, 30, 30), (14400, 900, 30, 1), torch.float32) triton_poi_fused_max_pool2d_with_indices_1[grid(57600)](buf1, buf2, buf3, 57600, XBLOCK=256, num_warps=4, num_stages=1) buf4 = empty_strided_cuda((25, 10), (10, 1), torch.float32) extern_kernels.addmm(primals_5, reinterpret_tensor(buf3, (25, 2304), (2304, 1), 0), reinterpret_tensor(primals_4, (2304, 10), (1, 2304), 0), alpha=1, beta=1, out=buf4) del primals_5 return buf4, primals_1, primals_3, buf1, buf2, reinterpret_tensor(buf3, (25, 2304), (2304, 1), 0), primals_4 class ModelNew(nn.Module): def __init__(self): super(ModelNew, self).__init__() self.conv = nn.Conv2d(1, 16, 5) self.pool = nn.MaxPool2d(2, 2) self.fc = nn.Linear(2304, 10) def forward(self, input_0): primals_1 = self.conv.weight primals_2 = self.conv.bias primals_4 = self.fc.weight primals_5 = self.fc.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
dohmatob/adversarial-robustness-toolbox
Model
false
6,586
[ "MIT" ]
1
7d3ba7d2d6690be69c08754fbc632947c2d10a97
https://github.com/dohmatob/adversarial-robustness-toolbox/tree/7d3ba7d2d6690be69c08754fbc632947c2d10a97
PowerPropLinear
import torch import torch.nn as nn import torch.nn.functional as F class PowerPropLinear(nn.Linear): """Powerpropagation Linear module.""" def __init__(self, in_features, out_fetaures, alpha, bias=True, *args, **kwargs): self._alpha = alpha super(PowerPropLinear, self).__init__(in_features, out_fetaures, bias, *args, **kwargs) def reset_parameters(self): super(PowerPropLinear, self).reset_parameters() with torch.no_grad(): weight = self.weight weight_modified = torch.sign(weight) * torch.pow(torch.abs( weight), 1.0 / self._alpha) self.weight.copy_(weight_modified) def get_weights(self): return torch.sign(self.weight) * torch.pow(torch.abs(self.weight), self._alpha) def forward(self, inputs, mask=None): params = self.weight * torch.pow(torch.abs(self.weight), self. _alpha - 1) if mask is not None: params *= mask outputs = F.linear(inputs, params, self.bias) return outputs def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_features': 4, 'out_fetaures': 4, 'alpha': 4}]
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_poi_fused_abs_mul_pow_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 x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = tl_math.abs(tmp0) tmp2 = tmp1 * tmp1 tmp3 = tmp2 * tmp1 tmp4 = tmp0 * tmp3 tl.store(out_ptr0 + x0, tmp4, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 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_abs_mul_pow_0[grid(16)](primals_1, buf0, 16, XBLOCK=16, num_warps=1, num_stages=1) buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(buf0, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf1) del buf0 del primals_2 return reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0 ), primals_1, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0) class PowerPropLinearNew(nn.Linear): """Powerpropagation Linear module.""" def __init__(self, in_features, out_fetaures, alpha, bias=True, *args, **kwargs): self._alpha = alpha super(PowerPropLinearNew, self).__init__(in_features, out_fetaures, bias, *args, **kwargs) def reset_parameters(self): super(PowerPropLinearNew, self).reset_parameters() with torch.no_grad(): weight = self.weight weight_modified = torch.sign(weight) * torch.pow(torch.abs( weight), 1.0 / self._alpha) self.weight.copy_(weight_modified) def get_weights(self): return torch.sign(self.weight) * torch.pow(torch.abs(self.weight), self._alpha) def forward(self, input_0): primals_1 = self.weight primals_2 = self.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
dlpbc/powerpropagation-pytorch
PowerPropLinear
false
6,587
[ "MIT" ]
1
99e29ce25ede9330cb8f624cb1fa7ffef6f82f03
https://github.com/dlpbc/powerpropagation-pytorch/tree/99e29ce25ede9330cb8f624cb1fa7ffef6f82f03
AllReduceLinear
import torch from torch import Tensor import torch.distributed as dist import torch.nn as nn from torch.nn import Linear class ParallelModule(nn.Module): """Parents of all parallel layer classes""" def __init__(self): super().__init__() self.mp_group = None def allreduce(self, outputs): if self.mp_group is not None and dist.get_world_size(group=self. mp_group) > 1: dist.all_reduce(outputs, group=self.mp_group) return outputs class AllReduceLinear(Linear, ParallelModule): """All-reduce linear layer""" def forward(self, input: 'Tensor') ->Tensor: outputs = input.matmul(self.weight.t()) self.allreduce(outputs) if self.bias is not None: outputs += self.bias return outputs def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_features': 4, 'out_features': 4}]
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 import torch.distributed as dist import torch.nn as nn from torch.nn import Linear 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_add_view_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x4 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x4, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(in_out_ptr0 + x4, tmp2, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4, 4), (4, 1)) assert_size_stride(primals_3, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0) del primals_2 buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf0 buf2 = buf1 del buf1 get_raw_stream(0) triton_poi_fused_add_view_0[grid(256)](buf2, primals_3, 256, XBLOCK =256, num_warps=4, num_stages=1) del primals_3 return buf2, reinterpret_tensor(primals_1, (64, 4), (4, 1), 0) class ParallelModule(nn.Module): """Parents of all parallel layer classes""" def __init__(self): super().__init__() self.mp_group = None def allreduce(self, outputs): if self.mp_group is not None and dist.get_world_size(group=self. mp_group) > 1: dist.all_reduce(outputs, group=self.mp_group) return outputs class AllReduceLinearNew(Linear, ParallelModule): """All-reduce linear layer""" def forward(self, input_0): primals_2 = self.weight primals_3 = self.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
dobbytk/parallelformers
AllReduceLinear
false
6,588
[ "Apache-2.0" ]
1
a05780b1d178b4ac5100e42c2b6eec7aedc7dd33
https://github.com/dobbytk/parallelformers/tree/a05780b1d178b4ac5100e42c2b6eec7aedc7dd33
PredictTargets
import torch from torch import nn from torch.nn import functional as F class PredictTargets(nn.Module): def __init__(self, dim): super(PredictTargets, self).__init__() self.linear1 = nn.Linear(2 * dim, dim) self.linear2 = nn.Linear(dim, 1) def forward(self, targets, embeddings): nt, b, vs = targets.shape ne = embeddings.size(0) vectors = torch.cat((targets.unsqueeze(1).expand(nt, ne, b, vs), embeddings.unsqueeze(0).expand(nt, ne, b, vs)), 3) return self.linear2(F.tanh(self.linear1(vectors))).squeeze(3) def get_inputs(): return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'dim': 4}]
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 libdevice from torch import 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_poi_fused_cat_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 512 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 8 x1 = xindex // 8 % 4 x3 = xindex // 128 x4 = xindex // 8 % 16 x5 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (4 * x1 + 16 * x3 + x0), tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp6 = tmp0 >= tmp3 tl.full([1], 8, tl.int64) tmp9 = tl.load(in_ptr1 + (4 * x4 + (-4 + x0)), tmp6 & xmask, eviction_policy='evict_last', other=0.0) tmp10 = tl.where(tmp4, tmp5, tmp9) tl.store(out_ptr0 + x5, tmp10, xmask) @triton.jit def triton_poi_fused_tanh_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = libdevice.tanh(tmp2) tl.store(in_out_ptr0 + x2, tmp3, 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), (16, 4, 1)) assert_size_stride(primals_2, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_3, (4, 8), (8, 1)) assert_size_stride(primals_4, (4,), (1,)) assert_size_stride(primals_5, (1, 4), (4, 1)) assert_size_stride(primals_6, (1,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 8), (128, 32, 8, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(512)](primals_1, primals_2, buf0, 512, XBLOCK=256, num_warps=4, num_stages=1) del primals_1 del primals_2 buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf0, (64, 8), (8, 1), 0), reinterpret_tensor(primals_3, (8, 4), (1, 8), 0), out=buf1) del primals_3 buf2 = reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf1 triton_poi_fused_tanh_1[grid(256)](buf2, primals_4, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_4 buf4 = empty_strided_cuda((64, 1), (1, 1), torch.float32) extern_kernels.addmm(primals_6, reinterpret_tensor(buf2, (64, 4), ( 4, 1), 0), reinterpret_tensor(primals_5, (4, 1), (1, 4), 0), alpha=1, beta=1, out=buf4) del primals_6 return reinterpret_tensor(buf4, (4, 4, 4), (16, 4, 1), 0 ), reinterpret_tensor(buf0, (64, 8), (8, 1), 0), buf2, primals_5 class PredictTargetsNew(nn.Module): def __init__(self, dim): super(PredictTargetsNew, self).__init__() self.linear1 = nn.Linear(2 * dim, dim) self.linear2 = nn.Linear(dim, 1) def forward(self, input_0, input_1): primals_3 = self.linear1.weight primals_4 = self.linear1.bias primals_5 = self.linear2.weight primals_6 = self.linear2.bias primals_1 = input_0 primals_2 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6]) return output[0]
dmcinerney/ehr-extraction-models
PredictTargets
false
6,589
[ "Apache-2.0" ]
1
c7e7e176f69a2558d420c607254ed7e98b5e836a
https://github.com/dmcinerney/ehr-extraction-models/tree/c7e7e176f69a2558d420c607254ed7e98b5e836a
SimpleEncoder
import math import torch from torch import Tensor import torch.nn as nn class PositionalEncoding(nn.Module): """ Learnable position embeddings Args: pe_type (str): type of position embeddings, which is chosen from ['fully_learnable', 'sinusoidal'] d_model (int): embed dim (required). max_len (int): max. length of the incoming sequence (default=5000). Examples: >>> pos_encoder = PositionalEncoding(d_model, max_len=100) """ def __init__(self, pe_type: 'str', d_model: 'int', max_len: 'int'=5000): super(PositionalEncoding, self).__init__() if pe_type == 'fully_learnable': self.pe = nn.parameter.Parameter(torch.randn(max_len, 1, d_model)) elif pe_type == 'sinusoidal': pe = torch.zeros(max_len, d_model) position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (- math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) pe = pe.unsqueeze(0).transpose(0, 1) self.register_buffer('pe', pe) else: raise RuntimeError( 'PE type should be fully_learnable/sinusoidal, not {}'. format(pe_type)) def forward(self, x: 'Tensor') ->Tensor: """Inputs of forward function Args: x (Tensor): the sequence fed to the positional encoder model [L, N, C] Returns: output (Tensor): position embeddings [L, N, C] """ return x + self.pe[:x.size(0)] class SimpleEncoder(nn.Module): def __init__(self, feature_dim, encoder_dim, image_size=14): super(SimpleEncoder, self).__init__() self.linear = nn.Conv2d(feature_dim, encoder_dim, kernel_size=1) self.positional_encoding = PositionalEncoding('fully_learnable', 2 * encoder_dim, image_size ** 2) def forward(self, x1, x2): return self.positional_encoding(torch.cat([self.linear(x1).flatten( start_dim=2).permute(2, 0, 1), self.linear(x2).flatten( start_dim=2).permute(2, 0, 1)], dim=2)) def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'feature_dim': 4, 'encoder_dim': 4}]
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 import math from torch import Tensor 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 @triton.jit def triton_poi_fused_add_cat_0(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 512 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 8 x1 = xindex // 8 % 16 x2 = xindex // 128 x4 = xindex % 128 tmp19 = tl.load(in_ptr3 + x4, xmask, eviction_policy='evict_last') tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x1 + 16 * x0 + 64 * x2), tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp6 = tl.load(in_ptr1 + x0, tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp7 = tmp5 + tmp6 tmp8 = tl.full(tmp7.shape, 0.0, tmp7.dtype) tmp9 = tl.where(tmp4, tmp7, tmp8) tmp10 = tmp0 >= tmp3 tl.full([1], 8, tl.int64) tmp13 = tl.load(in_ptr2 + (x1 + 16 * (-4 + x0) + 64 * x2), tmp10 & xmask, eviction_policy='evict_last', other=0.0) tmp14 = tl.load(in_ptr1 + (-4 + x0), tmp10 & xmask, eviction_policy= 'evict_last', other=0.0) tmp15 = tmp13 + tmp14 tmp16 = tl.full(tmp15.shape, 0.0, tmp15.dtype) tmp17 = tl.where(tmp10, tmp15, tmp16) tmp18 = tl.where(tmp4, tmp9, tmp17) tmp20 = tmp18 + tmp19 tl.store(out_ptr0 + (x0 + 8 * x2 + 32 * x1), tmp20, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (4, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_5, (196, 1, 8), (8, 8, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1)) buf1 = extern_kernels.convolution(primals_4, primals_1, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf1, (4, 4, 4, 4), (64, 16, 4, 1)) buf2 = empty_strided_cuda((16, 4, 8), (32, 8, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_cat_0[grid(512)](buf0, primals_2, buf1, primals_5, buf2, 512, XBLOCK=128, num_warps=4, num_stages=1) del buf0 del buf1 del primals_2 del primals_5 return buf2, primals_1, primals_3, primals_4 class PositionalEncoding(nn.Module): """ Learnable position embeddings Args: pe_type (str): type of position embeddings, which is chosen from ['fully_learnable', 'sinusoidal'] d_model (int): embed dim (required). max_len (int): max. length of the incoming sequence (default=5000). Examples: >>> pos_encoder = PositionalEncoding(d_model, max_len=100) """ def __init__(self, pe_type: 'str', d_model: 'int', max_len: 'int'=5000): super(PositionalEncoding, self).__init__() if pe_type == 'fully_learnable': self.pe = nn.parameter.Parameter(torch.randn(max_len, 1, d_model)) elif pe_type == 'sinusoidal': pe = torch.zeros(max_len, d_model) position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (- math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) pe = pe.unsqueeze(0).transpose(0, 1) self.register_buffer('pe', pe) else: raise RuntimeError( 'PE type should be fully_learnable/sinusoidal, not {}'. format(pe_type)) def forward(self, x: 'Tensor') ->Tensor: """Inputs of forward function Args: x (Tensor): the sequence fed to the positional encoder model [L, N, C] Returns: output (Tensor): position embeddings [L, N, C] """ return x + self.pe[:x.size(0)] class SimpleEncoderNew(nn.Module): def __init__(self, feature_dim, encoder_dim, image_size=14): super(SimpleEncoderNew, self).__init__() self.linear = nn.Conv2d(feature_dim, encoder_dim, kernel_size=1) self.positional_encoding = PositionalEncoding('fully_learnable', 2 * encoder_dim, image_size ** 2) def forward(self, input_0, input_1): primals_1 = self.linear.weight primals_2 = self.linear.bias primals_5 = self.positional_encoding.pe primals_3 = input_0 primals_4 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
doiken23/mccformers.pytorch
SimpleEncoder
false
6,590
[ "MIT" ]
1
678bd9448e3a2f35bd408e8c8e510e0ea1f9a19f
https://github.com/doiken23/mccformers.pytorch/tree/678bd9448e3a2f35bd408e8c8e510e0ea1f9a19f
MMTMQuad
import torch import torch.nn as nn from typing import Sequence class MMTMQuad(nn.Module): """ quad modal fusion """ def __init__(self, dim_tab, dim_img, ratio=4): """ Parameters ---------- dim_tab: feature dimension of tabular data dim_img: feature dimension of MIL model ratio """ super(MMTMQuad, self).__init__() dim = dim_tab + dim_img * 3 dim_out = int(2 * dim / ratio) self.fc_squeeze = nn.Linear(dim, dim_out) self.fc_tab = nn.Linear(dim_out, dim_tab) self.fc_img_scale1 = nn.Linear(dim_out, dim_img) self.fc_img_scale2 = nn.Linear(dim_out, dim_img) self.fc_img_scale3 = nn.Linear(dim_out, dim_img) self.relu = nn.ReLU() self.sigmoid = nn.Sigmoid() def forward(self, tab_feat, img_feat_scale1, img_feat_scale2, img_feat_scale3) ->Sequence[torch.Tensor]: """ Parameters ---------- tab_feat: b * c skeleton: b * c Returns ------- """ squeeze = torch.cat([tab_feat, img_feat_scale1, img_feat_scale2, img_feat_scale3], dim=1) excitation = self.fc_squeeze(squeeze) excitation = self.relu(excitation) tab_out = self.fc_tab(excitation) img_out_scale1 = self.fc_img_scale1(excitation) img_out_scale2 = self.fc_img_scale2(excitation) img_out_scale3 = self.fc_img_scale3(excitation) tab_out = self.sigmoid(tab_out) img_out_scale1 = self.sigmoid(img_out_scale1) img_out_scale2 = self.sigmoid(img_out_scale2) img_out_scale3 = self.sigmoid(img_out_scale3) return (tab_feat * tab_out, img_feat_scale1 * img_out_scale1, img_out_scale1, img_feat_scale2 * img_out_scale2, img_out_scale2, img_feat_scale2 * img_out_scale3, img_out_scale3) def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'dim_tab': 4, 'dim_img': 4}]
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 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_poi_fused_cat_0(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 16 x1 = xindex // 16 x2 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy= 'evict_last', other=0.0) tmp6 = tmp0 >= tmp3 tmp7 = tl.full([1], 8, tl.int64) tmp8 = tmp0 < tmp7 tmp9 = tmp6 & tmp8 tmp10 = tl.load(in_ptr1 + (4 * x1 + (-4 + x0)), tmp9 & xmask, eviction_policy='evict_last', other=0.0) tmp11 = tmp0 >= tmp7 tmp12 = tl.full([1], 12, tl.int64) tmp13 = tmp0 < tmp12 tmp14 = tmp11 & tmp13 tmp15 = tl.load(in_ptr2 + (4 * x1 + (-8 + x0)), tmp14 & xmask, eviction_policy='evict_last', other=0.0) tmp16 = tmp0 >= tmp12 tl.full([1], 16, tl.int64) tmp19 = tl.load(in_ptr3 + (4 * x1 + (-12 + x0)), tmp16 & xmask, eviction_policy='evict_last', other=0.0) tmp20 = tl.where(tmp14, tmp15, tmp19) tmp21 = tl.where(tmp9, tmp10, tmp20) tmp22 = tl.where(tmp4, tmp5, tmp21) tl.store(out_ptr0 + x2, tmp22, xmask) @triton.jit def triton_poi_fused_relu_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 32 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 8 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, xmask) @triton.jit def triton_poi_fused_mul_sigmoid_2(in_out_ptr0, in_ptr0, in_ptr1, 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 x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr1 + x2, xmask) tmp2 = tmp0 + tmp1 tmp3 = tl.sigmoid(tmp2) tmp5 = tmp4 * tmp3 tl.store(in_out_ptr0 + x2, tmp3, xmask) tl.store(out_ptr0 + x2, tmp5, xmask) @triton.jit def triton_poi_fused_mul_sigmoid_3(in_out_ptr0, in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp4 = tl.load(in_out_ptr1 + x2, xmask) tmp5 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr2 + x2, xmask) tmp2 = tmp0 + tmp1 tmp3 = tl.sigmoid(tmp2) tmp6 = tmp4 + tmp5 tmp7 = tl.sigmoid(tmp6) tmp9 = tmp8 * tmp7 tmp10 = tmp8 * tmp3 tl.store(in_out_ptr0 + x2, tmp3, xmask) tl.store(in_out_ptr1 + x2, tmp7, xmask) tl.store(out_ptr0 + x2, tmp9, xmask) tl.store(out_ptr1 + x2, tmp10, xmask) @triton.jit def triton_poi_fused_mul_sigmoid_4(in_ptr0, in_ptr1, 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_ptr0 + x0, xmask) tmp1 = tl.load(in_ptr1 + x0, xmask) tmp2 = tl.sigmoid(tmp1) tmp3 = tmp0 * tmp2 tl.store(out_ptr0 + x0, tmp3, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13, primals_14) = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4, 4), (4, 1)) assert_size_stride(primals_3, (4, 4), (4, 1)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (8, 16), (16, 1)) assert_size_stride(primals_6, (8,), (1,)) assert_size_stride(primals_7, (4, 8), (8, 1)) assert_size_stride(primals_8, (4,), (1,)) assert_size_stride(primals_9, (4, 8), (8, 1)) assert_size_stride(primals_10, (4,), (1,)) assert_size_stride(primals_11, (4, 8), (8, 1)) assert_size_stride(primals_12, (4,), (1,)) assert_size_stride(primals_13, (4, 8), (8, 1)) assert_size_stride(primals_14, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 16), (16, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(64)](primals_1, primals_2, primals_3, primals_4, buf0, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_4 buf1 = empty_strided_cuda((4, 8), (8, 1), torch.float32) extern_kernels.mm(buf0, reinterpret_tensor(primals_5, (16, 8), (1, 16), 0), out=buf1) del primals_5 buf2 = buf1 del buf1 triton_poi_fused_relu_1[grid(32)](buf2, primals_6, 32, XBLOCK=32, num_warps=1, num_stages=1) del primals_6 buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_8, buf2, reinterpret_tensor(primals_7, (8, 4), (1, 8), 0), alpha=1, beta=1, out=buf3) del primals_8 buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf2, reinterpret_tensor(primals_9, (8, 4), (1, 8 ), 0), out=buf4) buf5 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf2, reinterpret_tensor(primals_11, (8, 4), (1, 8), 0), out=buf5) buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf2, reinterpret_tensor(primals_13, (8, 4), (1, 8), 0), out=buf6) buf7 = buf4 del buf4 buf11 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_mul_sigmoid_2[grid(16)](buf7, primals_10, primals_2, buf11, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_10 buf9 = buf6 del buf6 buf8 = buf5 del buf5 buf12 = empty_strided_cuda((4, 4), (4, 1), torch.float32) buf13 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_mul_sigmoid_3[grid(16)](buf9, buf8, primals_14, primals_12, primals_3, buf12, buf13, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_12 del primals_14 buf10 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_mul_sigmoid_4[grid(16)](primals_1, buf3, buf10, 16, XBLOCK=16, num_warps=1, num_stages=1) return (buf10, buf11, buf7, buf12, buf8, buf13, buf9, primals_1, primals_2, primals_3, buf0, buf2, buf3, buf7, buf8, buf9, primals_13, primals_11, primals_9, primals_7) class MMTMQuadNew(nn.Module): """ quad modal fusion """ def __init__(self, dim_tab, dim_img, ratio=4): """ Parameters ---------- dim_tab: feature dimension of tabular data dim_img: feature dimension of MIL model ratio """ super(MMTMQuadNew, self).__init__() dim = dim_tab + dim_img * 3 dim_out = int(2 * dim / ratio) self.fc_squeeze = nn.Linear(dim, dim_out) self.fc_tab = nn.Linear(dim_out, dim_tab) self.fc_img_scale1 = nn.Linear(dim_out, dim_img) self.fc_img_scale2 = nn.Linear(dim_out, dim_img) self.fc_img_scale3 = nn.Linear(dim_out, dim_img) self.relu = nn.ReLU() self.sigmoid = nn.Sigmoid() def forward(self, input_0, input_1, input_2, input_3): primals_5 = self.fc_squeeze.weight primals_6 = self.fc_squeeze.bias primals_7 = self.fc_tab.weight primals_8 = self.fc_tab.bias primals_9 = self.fc_img_scale1.weight primals_10 = self.fc_img_scale1.bias primals_11 = self.fc_img_scale2.weight primals_12 = self.fc_img_scale2.bias primals_13 = self.fc_img_scale3.weight primals_14 = self.fc_img_scale3.bias primals_1 = input_0 primals_2 = input_1 primals_3 = input_2 primals_4 = input_3 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13, primals_14]) return output[0], output[1], output[2], output[3], output[4], output[5 ], output[6]
ditannan/Multi-modal-Multi-instance-Learning
MMTMQuad
false
6,591
[ "Apache-2.0" ]
1
06aada1ff85784d5ed50aa528c506947c892d584
https://github.com/ditannan/Multi-modal-Multi-instance-Learning/tree/06aada1ff85784d5ed50aa528c506947c892d584
Discrete
import torch import torch.nn as nn class Discrete(nn.Module): def __init__(self, num_outputs): super(Discrete, self).__init__() def forward(self, x): probs = nn.functional.softmax(x, dim=0) dist = torch.distributions.Categorical(probs=probs) return dist.entropy() def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'num_outputs': 4}]
import torch 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 torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 64 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (64 + x0), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (128 + x0), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (192 + x0), xmask, eviction_policy='evict_last') tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp0 - tmp7 tmp9 = tl_math.exp(tmp8) tl.store(out_ptr0 + x2, tmp9, xmask) @triton.jit def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 64 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (64 + x0), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (128 + x0), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (192 + x0), xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) @triton.jit def triton_poi_fused_div_sum_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 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') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused__softmax_0[grid(256)](arg0_1, buf0, 256, XBLOCK= 128, num_warps=4, num_stages=1) del arg0_1 buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused__softmax_1[grid(256)](buf0, buf1, 256, XBLOCK=256, num_warps=4, num_stages=1) buf2 = buf0 del buf0 triton_poi_fused_div_sum_2[grid(256)](buf1, buf2, 256, XBLOCK=128, num_warps=4, num_stages=1) del buf1 return buf2, class DiscreteNew(nn.Module): def __init__(self, num_outputs): super(DiscreteNew, self).__init__() def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
dreamflasher/client
Discrete
false
6,592
[ "MIT" ]
1
c8267f1c6b8b6970172d622bb8fbf7cc773d78b2
https://github.com/dreamflasher/client/tree/c8267f1c6b8b6970172d622bb8fbf7cc773d78b2
DiceLoss
import functools import torch import numpy as np import torch.nn.functional as F import torch.nn as nn import torch._C import torch.serialization def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are "none", "mean" and "sum". Return: Tensor: Reduced loss tensor. """ reduction_enum = F._Reduction.get_enum(reduction) if reduction_enum == 0: return loss elif reduction_enum == 1: return loss.mean() elif reduction_enum == 2: return loss.sum() def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wise weights. reduction (str): Same as built-in losses of PyTorch. avg_factor (float): Avarage factor when computing the mean of losses. Returns: Tensor: Processed loss values. """ if weight is not None: assert weight.dim() == loss.dim() if weight.dim() > 1: assert weight.size(1) == 1 or weight.size(1) == loss.size(1) loss = loss * weight if avg_factor is None: loss = reduce_loss(loss, reduction) elif reduction == 'mean': loss = loss.sum() / avg_factor elif reduction != 'none': raise ValueError('avg_factor can not be used with reduction="sum"') return loss def get_class_weight(class_weight): """Get class weight for loss function. Args: class_weight (list[float] | str | None): If class_weight is a str, take it as a file name and read from it. """ if isinstance(class_weight, str): if class_weight.endswith('.npy'): class_weight = np.load(class_weight) else: class_weight = mmcv.load(class_weight) return class_weight def weighted_loss(loss_func): """Create a weighted version of a given loss function. To use this decorator, the loss function must have the signature like `loss_func(pred, target, **kwargs)`. The function only needs to compute element-wise loss without any reduction. This decorator will add weight and reduction arguments to the function. The decorated function will have the signature like `loss_func(pred, target, weight=None, reduction='mean', avg_factor=None, **kwargs)`. :Example: >>> import torch >>> @weighted_loss >>> def l1_loss(pred, target): >>> return (pred - target).abs() >>> pred = torch.Tensor([0, 2, 3]) >>> target = torch.Tensor([1, 1, 1]) >>> weight = torch.Tensor([1, 0, 1]) >>> l1_loss(pred, target) tensor(1.3333) >>> l1_loss(pred, target, weight) tensor(1.) >>> l1_loss(pred, target, reduction='none') tensor([1., 1., 2.]) >>> l1_loss(pred, target, weight, avg_factor=2) tensor(1.5000) """ @functools.wraps(loss_func) def wrapper(pred, target, weight=None, reduction='mean', avg_factor= None, **kwargs): loss = loss_func(pred, target, **kwargs) loss = weight_reduce_loss(loss, weight, reduction, avg_factor) return loss return wrapper @weighted_loss def binary_dice_loss(pred, target, valid_mask, smooth=1, exponent=2, **kwards): assert pred.shape[0] == target.shape[0] pred = pred.reshape(pred.shape[0], -1) target = target.reshape(target.shape[0], -1) valid_mask = valid_mask.reshape(valid_mask.shape[0], -1) num = torch.sum(torch.mul(pred, target) * valid_mask, dim=1) * 2 + smooth den = torch.sum(pred.pow(exponent) + target.pow(exponent), dim=1) + smooth return 1 - num / den @weighted_loss def dice_loss(pred, target, valid_mask, smooth=1, exponent=2, class_weight= None, ignore_index=255): assert pred.shape[0] == target.shape[0] total_loss = 0 num_classes = pred.shape[1] for i in range(num_classes): if i != ignore_index: dice_loss = binary_dice_loss(pred[:, i], target[..., i], valid_mask=valid_mask, smooth=smooth, exponent=exponent) if class_weight is not None: dice_loss *= class_weight[i] total_loss += dice_loss return total_loss / num_classes class DiceLoss(nn.Module): """DiceLoss. This loss is proposed in `V-Net: Fully Convolutional Neural Networks for Volumetric Medical Image Segmentation <https://arxiv.org/abs/1606.04797>`_. Args: loss_type (str, optional): Binary or multi-class loss. Default: 'multi_class'. Options are "binary" and "multi_class". smooth (float): A float number to smooth loss, and avoid NaN error. Default: 1 exponent (float): An float number to calculate denominator value: \\sum{x^exponent} + \\sum{y^exponent}. Default: 2. reduction (str, optional): The method used to reduce the loss. Options are "none", "mean" and "sum". This parameter only works when per_image is True. Default: 'mean'. class_weight (list[float] | str, optional): Weight of each class. If in str format, read them from a file. Defaults to None. loss_weight (float, optional): Weight of the loss. Default to 1.0. ignore_index (int | None): The label index to be ignored. Default: 255. loss_name (str, optional): Name of the loss item. If you want this loss item to be included into the backward graph, `loss_` must be the prefix of the name. Defaults to 'loss_dice'. """ def __init__(self, smooth=1, exponent=2, reduction='mean', class_weight =None, loss_weight=1.0, ignore_index=255, loss_name='loss_dice', ** kwards): super(DiceLoss, self).__init__() self.smooth = smooth self.exponent = exponent self.reduction = reduction self.class_weight = get_class_weight(class_weight) self.loss_weight = loss_weight self.ignore_index = ignore_index self._loss_name = loss_name def forward(self, pred, target, avg_factor=None, reduction_override= None, **kwards): assert reduction_override in (None, 'none', 'mean', 'sum') reduction = (reduction_override if reduction_override else self. reduction) if self.class_weight is not None: class_weight = pred.new_tensor(self.class_weight) else: class_weight = None pred = F.softmax(pred, dim=1) num_classes = pred.shape[1] one_hot_target = F.one_hot(torch.clamp(target.long(), 0, num_classes - 1), num_classes=num_classes) valid_mask = (target != self.ignore_index).long() loss = self.loss_weight * dice_loss(pred, one_hot_target, valid_mask=valid_mask, reduction=reduction, avg_factor= avg_factor, smooth=self.smooth, exponent=self.exponent, class_weight=class_weight, ignore_index=self.ignore_index) return loss @property def loss_name(self): """Loss Name. This function must be implemented and will return the name of this loss function. This name will be used to combine different loss items by simple sum operation. In addition, if you want this loss item to be included into the backward graph, `loss_` must be the prefix of the name. Returns: str: The name of this loss item. """ return self._loss_name def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 functools import numpy as np import torch.nn.functional as F import torch.nn as nn import torch._C import torch.serialization assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused__softmax_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') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp0 - tmp7 tmp9 = tl_math.exp(tmp8) tl.store(out_ptr0 + x2, tmp9, xmask) @triton.jit def triton_poi_fused__softmax_1(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') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) @triton.jit def triton_per_fused__to_copy_add_div_mean_mul_ne_pow_rsub_sum_view_2( in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 4 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + 4 * r0, None, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + 4 * r0, None, eviction_policy='evict_last') tmp16 = tl.load(in_ptr1 + (1 + 4 * r0), None, eviction_policy='evict_last') tmp29 = tl.load(in_ptr1 + (2 + 4 * r0), None, eviction_policy='evict_last') tmp42 = tl.load(in_ptr1 + (3 + 4 * r0), None, eviction_policy='evict_last') tmp71 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last') tmp112 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last' ) tmp153 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last' ) tmp2 = tmp1.to(tl.int64) tmp3 = tl.full([1, 1], 0, tl.int64) tmp4 = triton_helpers.maximum(tmp2, tmp3) tmp5 = tl.full([1, 1], 3, tl.int64) tmp6 = triton_helpers.minimum(tmp4, tmp5) tmp7 = tmp6 == tmp3 tmp8 = tmp7.to(tl.int64) tmp9 = tmp8.to(tl.float32) tmp10 = tmp0 * tmp9 tmp11 = 255.0 tmp12 = tmp1 != tmp11 tmp13 = tmp12.to(tl.int64) tmp14 = tmp13.to(tl.float32) tmp15 = tmp10 * tmp14 tmp17 = tmp16.to(tl.int64) tmp18 = triton_helpers.maximum(tmp17, tmp3) tmp19 = triton_helpers.minimum(tmp18, tmp5) tmp20 = tmp19 == tmp3 tmp21 = tmp20.to(tl.int64) tmp22 = tmp21.to(tl.float32) tmp23 = tmp0 * tmp22 tmp24 = tmp16 != tmp11 tmp25 = tmp24.to(tl.int64) tmp26 = tmp25.to(tl.float32) tmp27 = tmp23 * tmp26 tmp28 = tmp15 + tmp27 tmp30 = tmp29.to(tl.int64) tmp31 = triton_helpers.maximum(tmp30, tmp3) tmp32 = triton_helpers.minimum(tmp31, tmp5) tmp33 = tmp32 == tmp3 tmp34 = tmp33.to(tl.int64) tmp35 = tmp34.to(tl.float32) tmp36 = tmp0 * tmp35 tmp37 = tmp29 != tmp11 tmp38 = tmp37.to(tl.int64) tmp39 = tmp38.to(tl.float32) tmp40 = tmp36 * tmp39 tmp41 = tmp28 + tmp40 tmp43 = tmp42.to(tl.int64) tmp44 = triton_helpers.maximum(tmp43, tmp3) tmp45 = triton_helpers.minimum(tmp44, tmp5) tmp46 = tmp45 == tmp3 tmp47 = tmp46.to(tl.int64) tmp48 = tmp47.to(tl.float32) tmp49 = tmp0 * tmp48 tmp50 = tmp42 != tmp11 tmp51 = tmp50.to(tl.int64) tmp52 = tmp51.to(tl.float32) tmp53 = tmp49 * tmp52 tmp54 = tmp41 + tmp53 tmp55 = tmp0 * tmp0 tmp56 = tmp8 * tmp8 tmp57 = tmp56.to(tl.float32) tmp58 = tmp55 + tmp57 tmp59 = tmp21 * tmp21 tmp60 = tmp59.to(tl.float32) tmp61 = tmp55 + tmp60 tmp62 = tmp58 + tmp61 tmp63 = tmp34 * tmp34 tmp64 = tmp63.to(tl.float32) tmp65 = tmp55 + tmp64 tmp66 = tmp62 + tmp65 tmp67 = tmp47 * tmp47 tmp68 = tmp67.to(tl.float32) tmp69 = tmp55 + tmp68 tmp70 = tmp66 + tmp69 tmp72 = tl.full([1, 1], 1, tl.int64) tmp73 = tmp6 == tmp72 tmp74 = tmp73.to(tl.int64) tmp75 = tmp74.to(tl.float32) tmp76 = tmp71 * tmp75 tmp77 = tmp76 * tmp14 tmp78 = tmp19 == tmp72 tmp79 = tmp78.to(tl.int64) tmp80 = tmp79.to(tl.float32) tmp81 = tmp71 * tmp80 tmp82 = tmp81 * tmp26 tmp83 = tmp77 + tmp82 tmp84 = tmp32 == tmp72 tmp85 = tmp84.to(tl.int64) tmp86 = tmp85.to(tl.float32) tmp87 = tmp71 * tmp86 tmp88 = tmp87 * tmp39 tmp89 = tmp83 + tmp88 tmp90 = tmp45 == tmp72 tmp91 = tmp90.to(tl.int64) tmp92 = tmp91.to(tl.float32) tmp93 = tmp71 * tmp92 tmp94 = tmp93 * tmp52 tmp95 = tmp89 + tmp94 tmp96 = tmp71 * tmp71 tmp97 = tmp74 * tmp74 tmp98 = tmp97.to(tl.float32) tmp99 = tmp96 + tmp98 tmp100 = tmp79 * tmp79 tmp101 = tmp100.to(tl.float32) tmp102 = tmp96 + tmp101 tmp103 = tmp99 + tmp102 tmp104 = tmp85 * tmp85 tmp105 = tmp104.to(tl.float32) tmp106 = tmp96 + tmp105 tmp107 = tmp103 + tmp106 tmp108 = tmp91 * tmp91 tmp109 = tmp108.to(tl.float32) tmp110 = tmp96 + tmp109 tmp111 = tmp107 + tmp110 tmp113 = tl.full([1, 1], 2, tl.int64) tmp114 = tmp6 == tmp113 tmp115 = tmp114.to(tl.int64) tmp116 = tmp115.to(tl.float32) tmp117 = tmp112 * tmp116 tmp118 = tmp117 * tmp14 tmp119 = tmp19 == tmp113 tmp120 = tmp119.to(tl.int64) tmp121 = tmp120.to(tl.float32) tmp122 = tmp112 * tmp121 tmp123 = tmp122 * tmp26 tmp124 = tmp118 + tmp123 tmp125 = tmp32 == tmp113 tmp126 = tmp125.to(tl.int64) tmp127 = tmp126.to(tl.float32) tmp128 = tmp112 * tmp127 tmp129 = tmp128 * tmp39 tmp130 = tmp124 + tmp129 tmp131 = tmp45 == tmp113 tmp132 = tmp131.to(tl.int64) tmp133 = tmp132.to(tl.float32) tmp134 = tmp112 * tmp133 tmp135 = tmp134 * tmp52 tmp136 = tmp130 + tmp135 tmp137 = tmp112 * tmp112 tmp138 = tmp115 * tmp115 tmp139 = tmp138.to(tl.float32) tmp140 = tmp137 + tmp139 tmp141 = tmp120 * tmp120 tmp142 = tmp141.to(tl.float32) tmp143 = tmp137 + tmp142 tmp144 = tmp140 + tmp143 tmp145 = tmp126 * tmp126 tmp146 = tmp145.to(tl.float32) tmp147 = tmp137 + tmp146 tmp148 = tmp144 + tmp147 tmp149 = tmp132 * tmp132 tmp150 = tmp149.to(tl.float32) tmp151 = tmp137 + tmp150 tmp152 = tmp148 + tmp151 tmp154 = tmp6 == tmp5 tmp155 = tmp154.to(tl.int64) tmp156 = tmp155.to(tl.float32) tmp157 = tmp153 * tmp156 tmp158 = tmp157 * tmp14 tmp159 = tmp19 == tmp5 tmp160 = tmp159.to(tl.int64) tmp161 = tmp160.to(tl.float32) tmp162 = tmp153 * tmp161 tmp163 = tmp162 * tmp26 tmp164 = tmp158 + tmp163 tmp165 = tmp32 == tmp5 tmp166 = tmp165.to(tl.int64) tmp167 = tmp166.to(tl.float32) tmp168 = tmp153 * tmp167 tmp169 = tmp168 * tmp39 tmp170 = tmp164 + tmp169 tmp171 = tmp45 == tmp5 tmp172 = tmp171.to(tl.int64) tmp173 = tmp172.to(tl.float32) tmp174 = tmp153 * tmp173 tmp175 = tmp174 * tmp52 tmp176 = tmp170 + tmp175 tmp177 = tmp153 * tmp153 tmp178 = tmp155 * tmp155 tmp179 = tmp178.to(tl.float32) tmp180 = tmp177 + tmp179 tmp181 = tmp160 * tmp160 tmp182 = tmp181.to(tl.float32) tmp183 = tmp177 + tmp182 tmp184 = tmp180 + tmp183 tmp185 = tmp166 * tmp166 tmp186 = tmp185.to(tl.float32) tmp187 = tmp177 + tmp186 tmp188 = tmp184 + tmp187 tmp189 = tmp172 * tmp172 tmp190 = tmp189.to(tl.float32) tmp191 = tmp177 + tmp190 tmp192 = tmp188 + tmp191 tmp193 = 2.0 tmp194 = tmp54 * tmp193 tmp195 = 1.0 tmp196 = tmp194 + tmp195 tmp197 = tmp70 + tmp195 tmp198 = tmp196 / tmp197 tmp199 = tmp195 - tmp198 tmp200 = tl.broadcast_to(tmp199, [XBLOCK, RBLOCK]) tmp202 = tl.sum(tmp200, 1)[:, None] tmp203 = tmp95 * tmp193 tmp204 = tmp203 + tmp195 tmp205 = tmp111 + tmp195 tmp206 = tmp204 / tmp205 tmp207 = tmp195 - tmp206 tmp208 = tl.broadcast_to(tmp207, [XBLOCK, RBLOCK]) tmp210 = tl.sum(tmp208, 1)[:, None] tmp211 = tmp136 * tmp193 tmp212 = tmp211 + tmp195 tmp213 = tmp152 + tmp195 tmp214 = tmp212 / tmp213 tmp215 = tmp195 - tmp214 tmp216 = tl.broadcast_to(tmp215, [XBLOCK, RBLOCK]) tmp218 = tl.sum(tmp216, 1)[:, None] tmp219 = tmp176 * tmp193 tmp220 = tmp219 + tmp195 tmp221 = tmp192 + tmp195 tmp222 = tmp220 / tmp221 tmp223 = tmp195 - tmp222 tmp224 = tl.broadcast_to(tmp223, [XBLOCK, RBLOCK]) tmp226 = tl.sum(tmp224, 1)[:, None] tmp227 = 4.0 tmp228 = tmp202 / tmp227 tmp229 = 0.0 tmp230 = tmp228 + tmp229 tmp231 = tmp210 / tmp227 tmp232 = tmp230 + tmp231 tmp233 = tmp218 / tmp227 tmp234 = tmp232 + tmp233 tmp235 = tmp226 / tmp227 tmp236 = tmp234 + tmp235 tmp237 = 0.25 tmp238 = tmp236 * tmp237 tmp239 = tmp238 / tmp195 tmp240 = tmp239 * tmp195 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp240, None) 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__softmax_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__softmax_1[grid(16)](buf0, buf1, 16, XBLOCK=16, num_warps=1, num_stages=1) del buf0 buf10 = empty_strided_cuda((), (), torch.float32) buf14 = buf10 del buf10 triton_per_fused__to_copy_add_div_mean_mul_ne_pow_rsub_sum_view_2[grid (1)](buf14, buf1, arg1_1, 1, 4, XBLOCK=1, num_warps=2, num_stages=1 ) del arg1_1 del buf1 return buf14, def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are "none", "mean" and "sum". Return: Tensor: Reduced loss tensor. """ reduction_enum = F._Reduction.get_enum(reduction) if reduction_enum == 0: return loss elif reduction_enum == 1: return loss.mean() elif reduction_enum == 2: return loss.sum() def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wise weights. reduction (str): Same as built-in losses of PyTorch. avg_factor (float): Avarage factor when computing the mean of losses. Returns: Tensor: Processed loss values. """ if weight is not None: assert weight.dim() == loss.dim() if weight.dim() > 1: assert weight.size(1) == 1 or weight.size(1) == loss.size(1) loss = loss * weight if avg_factor is None: loss = reduce_loss(loss, reduction) elif reduction == 'mean': loss = loss.sum() / avg_factor elif reduction != 'none': raise ValueError('avg_factor can not be used with reduction="sum"') return loss def get_class_weight(class_weight): """Get class weight for loss function. Args: class_weight (list[float] | str | None): If class_weight is a str, take it as a file name and read from it. """ if isinstance(class_weight, str): if class_weight.endswith('.npy'): class_weight = np.load(class_weight) else: class_weight = mmcv.load(class_weight) return class_weight def weighted_loss(loss_func): """Create a weighted version of a given loss function. To use this decorator, the loss function must have the signature like `loss_func(pred, target, **kwargs)`. The function only needs to compute element-wise loss without any reduction. This decorator will add weight and reduction arguments to the function. The decorated function will have the signature like `loss_func(pred, target, weight=None, reduction='mean', avg_factor=None, **kwargs)`. :Example: >>> import torch >>> @weighted_loss >>> def l1_loss(pred, target): >>> return (pred - target).abs() >>> pred = torch.Tensor([0, 2, 3]) >>> target = torch.Tensor([1, 1, 1]) >>> weight = torch.Tensor([1, 0, 1]) >>> l1_loss(pred, target) tensor(1.3333) >>> l1_loss(pred, target, weight) tensor(1.) >>> l1_loss(pred, target, reduction='none') tensor([1., 1., 2.]) >>> l1_loss(pred, target, weight, avg_factor=2) tensor(1.5000) """ @functools.wraps(loss_func) def wrapper(pred, target, weight=None, reduction='mean', avg_factor= None, **kwargs): loss = loss_func(pred, target, **kwargs) loss = weight_reduce_loss(loss, weight, reduction, avg_factor) return loss return wrapper @weighted_loss def binary_dice_loss(pred, target, valid_mask, smooth=1, exponent=2, **kwards): assert pred.shape[0] == target.shape[0] pred = pred.reshape(pred.shape[0], -1) target = target.reshape(target.shape[0], -1) valid_mask = valid_mask.reshape(valid_mask.shape[0], -1) num = torch.sum(torch.mul(pred, target) * valid_mask, dim=1) * 2 + smooth den = torch.sum(pred.pow(exponent) + target.pow(exponent), dim=1) + smooth return 1 - num / den @weighted_loss def dice_loss(pred, target, valid_mask, smooth=1, exponent=2, class_weight= None, ignore_index=255): assert pred.shape[0] == target.shape[0] total_loss = 0 num_classes = pred.shape[1] for i in range(num_classes): if i != ignore_index: dice_loss = binary_dice_loss(pred[:, i], target[..., i], valid_mask=valid_mask, smooth=smooth, exponent=exponent) if class_weight is not None: dice_loss *= class_weight[i] total_loss += dice_loss return total_loss / num_classes class DiceLossNew(nn.Module): """DiceLoss. This loss is proposed in `V-Net: Fully Convolutional Neural Networks for Volumetric Medical Image Segmentation <https://arxiv.org/abs/1606.04797>`_. Args: loss_type (str, optional): Binary or multi-class loss. Default: 'multi_class'. Options are "binary" and "multi_class". smooth (float): A float number to smooth loss, and avoid NaN error. Default: 1 exponent (float): An float number to calculate denominator value: \\sum{x^exponent} + \\sum{y^exponent}. Default: 2. reduction (str, optional): The method used to reduce the loss. Options are "none", "mean" and "sum". This parameter only works when per_image is True. Default: 'mean'. class_weight (list[float] | str, optional): Weight of each class. If in str format, read them from a file. Defaults to None. loss_weight (float, optional): Weight of the loss. Default to 1.0. ignore_index (int | None): The label index to be ignored. Default: 255. loss_name (str, optional): Name of the loss item. If you want this loss item to be included into the backward graph, `loss_` must be the prefix of the name. Defaults to 'loss_dice'. """ def __init__(self, smooth=1, exponent=2, reduction='mean', class_weight =None, loss_weight=1.0, ignore_index=255, loss_name='loss_dice', ** kwards): super(DiceLossNew, self).__init__() self.smooth = smooth self.exponent = exponent self.reduction = reduction self.class_weight = get_class_weight(class_weight) self.loss_weight = loss_weight self.ignore_index = ignore_index self._loss_name = loss_name @property def loss_name(self): """Loss Name. This function must be implemented and will return the name of this loss function. This name will be used to combine different loss items by simple sum operation. In addition, if you want this loss item to be included into the backward graph, `loss_` must be the prefix of the name. Returns: str: The name of this loss item. """ return self._loss_name def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
dkswxd/Swin-Spectral
DiceLoss
false
6,593
[ "Apache-2.0" ]
1
5d8c364b0d89e4dd21590bb58f7a434a5b97254c
https://github.com/dkswxd/Swin-Spectral/tree/5d8c364b0d89e4dd21590bb58f7a434a5b97254c
Critic
import torch import torch.nn as nn import torch.nn.functional as F class Critic(nn.Module): def __init__(self, state_dim, action_dim): super(Critic, self).__init__() self.l1 = nn.Linear(state_dim, 400) self.l2 = nn.Linear(400 + action_dim, 300) self.l3 = nn.Linear(300, 1) def forward(self, state, action): q = F.relu(self.l1(state)) q = F.relu(self.l2(torch.cat([q, action], 1))) q = self.l3(q) return q def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'state_dim': 4, 'action_dim': 4}]
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 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_poi_fused_cat_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 1616 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 404 x1 = xindex // 404 x2 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 400, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (400 * x1 + x0), tmp4 & xmask, eviction_policy ='evict_last', other=0.0) tmp6 = tl.load(in_ptr1 + x0, tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp7 = tmp5 + tmp6 tmp8 = tl.full([1], 0, tl.int32) tmp9 = triton_helpers.maximum(tmp8, tmp7) tmp10 = tl.full(tmp9.shape, 0.0, tmp9.dtype) tmp11 = tl.where(tmp4, tmp9, tmp10) tmp12 = tmp0 >= tmp3 tl.full([1], 404, tl.int64) tmp15 = tl.load(in_ptr2 + (4 * x1 + (-400 + x0)), tmp12 & xmask, eviction_policy='evict_last', other=0.0) tmp16 = tl.where(tmp4, tmp11, tmp15) tl.store(out_ptr0 + x2, tmp16, xmask) @triton.jit def triton_poi_fused_relu_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 1200 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 300 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, xmask) @triton.jit def triton_poi_fused_relu_threshold_backward_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 1600 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 400 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x0, 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(out_ptr0 + x2, tmp6, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8) = args args.clear() assert_size_stride(primals_1, (400, 4), (4, 1)) assert_size_stride(primals_2, (400,), (1,)) assert_size_stride(primals_3, (4, 4), (4, 1)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (300, 404), (404, 1)) assert_size_stride(primals_6, (300,), (1,)) assert_size_stride(primals_7, (1, 300), (300, 1)) assert_size_stride(primals_8, (1,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 400), (400, 1), torch.float32) extern_kernels.mm(primals_3, reinterpret_tensor(primals_1, (4, 400), (1, 4), 0), out=buf0) del primals_1 buf1 = empty_strided_cuda((4, 404), (404, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(1616)](buf0, primals_2, primals_4, buf1, 1616, XBLOCK=128, num_warps=4, num_stages=1) del primals_4 buf2 = empty_strided_cuda((4, 300), (300, 1), torch.float32) extern_kernels.mm(buf1, reinterpret_tensor(primals_5, (404, 300), ( 1, 404), 0), out=buf2) buf3 = buf2 del buf2 triton_poi_fused_relu_1[grid(1200)](buf3, primals_6, 1200, XBLOCK= 256, num_warps=4, num_stages=1) del primals_6 buf5 = empty_strided_cuda((4, 1), (1, 1), torch.float32) extern_kernels.addmm(primals_8, buf3, reinterpret_tensor(primals_7, (300, 1), (1, 300), 0), alpha=1, beta=1, out=buf5) del primals_8 buf6 = empty_strided_cuda((4, 400), (400, 1), torch.bool) triton_poi_fused_relu_threshold_backward_2[grid(1600)](buf0, primals_2, buf6, 1600, XBLOCK=128, num_warps=4, num_stages=1) del buf0 del primals_2 return buf5, primals_3, buf1, buf3, primals_7, primals_5, buf6 class CriticNew(nn.Module): def __init__(self, state_dim, action_dim): super(CriticNew, self).__init__() self.l1 = nn.Linear(state_dim, 400) self.l2 = nn.Linear(400 + action_dim, 300) self.l3 = nn.Linear(300, 1) def forward(self, input_0, input_1): primals_1 = self.l1.weight primals_2 = self.l1.bias primals_5 = self.l2.weight primals_6 = self.l2.bias primals_7 = self.l3.weight primals_8 = self.l3.bias primals_3 = input_0 primals_4 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8]) return output[0]
dmund95/bcq
Critic
false
6,594
[ "MIT" ]
1
b1ae39ad7789443f02273aaa1a433c55c6836a5f
https://github.com/dmund95/bcq/tree/b1ae39ad7789443f02273aaa1a433c55c6836a5f
SquareRoot
import torch import torch.nn.functional from torch import nn class SquareRoot(nn.Module): def forward(self, x): return x.sqrt() def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 libdevice import torch.nn.functional from torch import nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_sqrt_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = libdevice.sqrt(tmp0) tl.store(out_ptr0 + x0, tmp1, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_sqrt_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 return buf0, class SquareRootNew(nn.Module): def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
drivendataorg/DrivenData-2021-Geopose-Solution
SquareRoot
false
6,595
[ "MIT" ]
1
fc1dead0aeb1ade9e9d87b55f56e631c57e966a6
https://github.com/drivendataorg/DrivenData-2021-Geopose-Solution/tree/fc1dead0aeb1ade9e9d87b55f56e631c57e966a6
Net
import torch import torch.nn as nn class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc1 = nn.Linear(4, 64) self.fc2 = nn.Linear(64, 64) self.fc3 = nn.Linear(64, 2) def forward(self, x): x = torch.tanh(self.fc1(x)) x = torch.tanh(self.fc2(x)) x = self.fc3(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] 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.triton_helpers import libdevice 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_poi_fused_tanh_0(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 % 64 tmp0 = tl.load(in_out_ptr0 + x2, None) tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = libdevice.tanh(tmp2) tl.store(in_out_ptr0 + x2, tmp3, None) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7) = args args.clear() assert_size_stride(primals_1, (64, 4), (4, 1)) assert_size_stride(primals_2, (64,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (64, 64), (64, 1)) assert_size_stride(primals_5, (64,), (1,)) assert_size_stride(primals_6, (2, 64), (64, 1)) assert_size_stride(primals_7, (2,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 64), (64, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 64), (1, 4), 0), out=buf0) del primals_1 buf1 = reinterpret_tensor(buf0, (4, 4, 4, 64), (1024, 256, 64, 1), 0) del buf0 get_raw_stream(0) triton_poi_fused_tanh_0[grid(4096)](buf1, primals_2, 4096, XBLOCK= 128, num_warps=4, num_stages=1) del primals_2 buf2 = empty_strided_cuda((64, 64), (64, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf1, (64, 64), (64, 1), 0), reinterpret_tensor(primals_4, (64, 64), (1, 64), 0), out=buf2) buf3 = reinterpret_tensor(buf2, (4, 4, 4, 64), (1024, 256, 64, 1), 0) del buf2 triton_poi_fused_tanh_0[grid(4096)](buf3, primals_5, 4096, XBLOCK= 128, num_warps=4, num_stages=1) del primals_5 buf4 = empty_strided_cuda((64, 2), (2, 1), torch.float32) extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 64), (64, 1), 0), reinterpret_tensor(primals_6, (64, 2), (1, 64), 0), alpha=1, beta=1, out=buf4) del primals_7 return reinterpret_tensor(buf4, (4, 4, 4, 2), (32, 8, 2, 1), 0 ), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), buf1, buf3, primals_6, primals_4 class NetNew(nn.Module): def __init__(self): super(NetNew, self).__init__() self.fc1 = nn.Linear(4, 64) self.fc2 = nn.Linear(64, 64) self.fc3 = nn.Linear(64, 2) def forward(self, input_0): primals_1 = self.fc1.weight primals_2 = self.fc1.bias primals_4 = self.fc2.weight primals_5 = self.fc2.bias primals_6 = self.fc3.weight primals_7 = self.fc3.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0]
dongminlee94/supplement4deeprl
Net
false
6,596
[ "MIT" ]
1
4db1a83f5dd3254abd8135fe94734a0d8d14a957
https://github.com/dongminlee94/supplement4deeprl/tree/4db1a83f5dd3254abd8135fe94734a0d8d14a957
Value
import torch import torch.nn as nn import torch.nn.functional as F class Value(nn.Module): def __init__(self, num_inputs): super(Value, self).__init__() self.affine1 = nn.Linear(num_inputs, 64) self.affine2 = nn.Linear(64, 64) self.value_head = nn.Linear(64, 1) self.value_head.weight.data.mul_(0.1) self.value_head.bias.data.mul_(0.0) def forward(self, x): x = F.tanh(self.affine1(x)) x = F.tanh(self.affine2(x)) state_values = self.value_head(x) return state_values def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'num_inputs': 4}]
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 libdevice 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_poi_fused_tanh_0(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 % 64 tmp0 = tl.load(in_out_ptr0 + x2, None) tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = libdevice.tanh(tmp2) tl.store(in_out_ptr0 + x2, tmp3, None) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7) = args args.clear() assert_size_stride(primals_1, (64, 4), (4, 1)) assert_size_stride(primals_2, (64,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (64, 64), (64, 1)) assert_size_stride(primals_5, (64,), (1,)) assert_size_stride(primals_6, (1, 64), (64, 1)) assert_size_stride(primals_7, (1,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 64), (64, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 64), (1, 4), 0), out=buf0) del primals_1 buf1 = reinterpret_tensor(buf0, (4, 4, 4, 64), (1024, 256, 64, 1), 0) del buf0 get_raw_stream(0) triton_poi_fused_tanh_0[grid(4096)](buf1, primals_2, 4096, XBLOCK= 128, num_warps=4, num_stages=1) del primals_2 buf2 = empty_strided_cuda((64, 64), (64, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf1, (64, 64), (64, 1), 0), reinterpret_tensor(primals_4, (64, 64), (1, 64), 0), out=buf2) buf3 = reinterpret_tensor(buf2, (4, 4, 4, 64), (1024, 256, 64, 1), 0) del buf2 triton_poi_fused_tanh_0[grid(4096)](buf3, primals_5, 4096, XBLOCK= 128, num_warps=4, num_stages=1) del primals_5 buf5 = empty_strided_cuda((64, 1), (1, 1), torch.float32) extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 64), (64, 1), 0), reinterpret_tensor(primals_6, (64, 1), (1, 64), 0), alpha=1, beta=1, out=buf5) del primals_7 return reinterpret_tensor(buf5, (4, 4, 4, 1), (16, 4, 1, 1), 0 ), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), buf1, buf3, primals_6, primals_4 class ValueNew(nn.Module): def __init__(self, num_inputs): super(ValueNew, self).__init__() self.affine1 = nn.Linear(num_inputs, 64) self.affine2 = nn.Linear(64, 64) self.value_head = nn.Linear(64, 1) self.value_head.weight.data.mul_(0.1) self.value_head.bias.data.mul_(0.0) def forward(self, input_0): primals_1 = self.affine1.weight primals_2 = self.affine1.bias primals_4 = self.affine2.weight primals_5 = self.affine2.bias primals_6 = self.value_head.weight primals_7 = self.value_head.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0]
dragen1860/TRPO-Pytorch
Value
false
6,597
[ "MIT" ]
1
c5a8e5ac890ec50e331db12fd5885dd4fb753a3b
https://github.com/dragen1860/TRPO-Pytorch/tree/c5a8e5ac890ec50e331db12fd5885dd4fb753a3b
Policy
import torch import torch.nn as nn import torch.nn.functional as F class Policy(nn.Module): def __init__(self, num_inputs, num_outputs): super(Policy, self).__init__() self.affine1 = nn.Linear(num_inputs, 64) self.affine2 = nn.Linear(64, 64) self.action_mean = nn.Linear(64, num_outputs) self.action_mean.weight.data.mul_(0.1) self.action_mean.bias.data.mul_(0.0) self.action_log_std = nn.Parameter(torch.zeros(1, num_outputs)) self.saved_actions = [] self.rewards = [] self.final_value = 0 def forward(self, x): x = F.tanh(self.affine1(x)) x = F.tanh(self.affine2(x)) action_mean = self.action_mean(x) action_log_std = self.action_log_std.expand_as(action_mean) action_std = torch.exp(action_log_std) return action_mean, action_log_std, action_std def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'num_inputs': 4, 'num_outputs': 4}]
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 libdevice, 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_poi_fused_tanh_0(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 % 64 tmp0 = tl.load(in_out_ptr0 + x2, None) tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = libdevice.tanh(tmp2) tl.store(in_out_ptr0 + x2, tmp3, None) @triton.jit def triton_poi_fused_exp_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 4 x2 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp1 = tl_math.exp(tmp0) tl.store(out_ptr0 + x2, tmp1, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8) = args args.clear() assert_size_stride(primals_1, (64, 4), (4, 1)) assert_size_stride(primals_2, (64,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (64, 64), (64, 1)) assert_size_stride(primals_5, (64,), (1,)) assert_size_stride(primals_6, (4, 64), (64, 1)) assert_size_stride(primals_7, (4,), (1,)) assert_size_stride(primals_8, (1, 4), (4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 64), (64, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 64), (1, 4), 0), out=buf0) del primals_1 buf1 = reinterpret_tensor(buf0, (4, 4, 4, 64), (1024, 256, 64, 1), 0) del buf0 get_raw_stream(0) triton_poi_fused_tanh_0[grid(4096)](buf1, primals_2, 4096, XBLOCK= 128, num_warps=4, num_stages=1) del primals_2 buf2 = empty_strided_cuda((64, 64), (64, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf1, (64, 64), (64, 1), 0), reinterpret_tensor(primals_4, (64, 64), (1, 64), 0), out=buf2) buf3 = reinterpret_tensor(buf2, (4, 4, 4, 64), (1024, 256, 64, 1), 0) del buf2 triton_poi_fused_tanh_0[grid(4096)](buf3, primals_5, 4096, XBLOCK= 128, num_warps=4, num_stages=1) del primals_5 buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 64), (64, 1), 0), reinterpret_tensor(primals_6, (64, 4), (1, 64), 0), alpha=1, beta=1, out=buf4) del primals_7 buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_exp_1[grid(256)](primals_8, buf5, 256, XBLOCK=256, num_warps=4, num_stages=1) return reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0 ), reinterpret_tensor(primals_8, (4, 4, 4, 4), (0, 0, 0, 1), 0 ), buf5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), buf1, buf3, buf5, primals_6, primals_4 class PolicyNew(nn.Module): def __init__(self, num_inputs, num_outputs): super(PolicyNew, self).__init__() self.affine1 = nn.Linear(num_inputs, 64) self.affine2 = nn.Linear(64, 64) self.action_mean = nn.Linear(64, num_outputs) self.action_mean.weight.data.mul_(0.1) self.action_mean.bias.data.mul_(0.0) self.action_log_std = nn.Parameter(torch.zeros(1, num_outputs)) self.saved_actions = [] self.rewards = [] self.final_value = 0 def forward(self, input_0): primals_8 = self.action_log_std primals_1 = self.affine1.weight primals_2 = self.affine1.bias primals_4 = self.affine2.weight primals_5 = self.affine2.bias primals_6 = self.action_mean.weight primals_7 = self.action_mean.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8]) return output[0], output[1], output[2]
dragen1860/TRPO-Pytorch
Policy
false
6,598
[ "MIT" ]
1
c5a8e5ac890ec50e331db12fd5885dd4fb753a3b
https://github.com/dragen1860/TRPO-Pytorch/tree/c5a8e5ac890ec50e331db12fd5885dd4fb753a3b
GlobalWeightedAvgPool2d
import torch import torch.nn as nn class GlobalWeightedAvgPool2d(nn.Module): """ Global Weighted Average Pooling from paper "Global Weighted Average Pooling Bridges Pixel-level Localization and Image-level Classification" """ def __init__(self, features: 'int', flatten=False): super().__init__() self.conv = nn.Conv2d(features, 1, kernel_size=1, bias=True) self.flatten = flatten def fscore(self, x): m = self.conv(x) m = m.sigmoid().exp() return m def norm(self, x: 'torch.Tensor'): return x / x.sum(dim=[2, 3], keepdim=True) def forward(self, x): input_x = x x = self.fscore(x) x = self.norm(x) x = x * input_x x = x.sum(dim=[2, 3], keepdim=not self.flatten) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'features': 4}]
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 @triton.jit def triton_per_fused_convolution_exp_sigmoid_sum_0(in_out_ptr0, in_ptr0, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 4 RBLOCK: tl.constexpr = 16 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_out_ptr0 + (r1 + 16 * x0), xmask, other=0.0) tmp1 = tl.load(in_ptr0 + 0) tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp3 = tmp0 + tmp2 tmp4 = tl.sigmoid(tmp3) tmp5 = tl_math.exp(tmp4) tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK]) tmp8 = tl.where(xmask, tmp6, 0) tmp9 = tl.sum(tmp8, 1)[:, None] tl.store(in_out_ptr0 + (r1 + 16 * x0), tmp3, xmask) tl.store(out_ptr0 + x0, tmp9, xmask) @triton.jit def triton_per_fused_div_exp_mul_sigmoid_sum_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 16 RBLOCK: tl.constexpr = 16 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) r2 = rindex x1 = xindex // 4 x3 = xindex tmp0 = tl.load(in_ptr0 + (r2 + 16 * x1), xmask, eviction_policy= 'evict_last', other=0.0) tmp3 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr2 + (r2 + 16 * x3), xmask, other=0.0) tmp1 = tl.sigmoid(tmp0) tmp2 = tl_math.exp(tmp1) tmp4 = tmp2 / tmp3 tmp6 = tmp4 * tmp5 tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK]) tmp9 = tl.where(xmask, tmp7, 0) tmp10 = tl.sum(tmp9, 1)[:, None] tl.store(out_ptr0 + x3, tmp10, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (1, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_3, (1,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 1, 4, 4), (16, 16, 4, 1)) buf1 = buf0 del buf0 buf2 = empty_strided_cuda((4, 1, 1, 1), (1, 1, 1, 1), torch.float32) get_raw_stream(0) triton_per_fused_convolution_exp_sigmoid_sum_0[grid(4)](buf1, primals_3, buf2, 4, 16, XBLOCK=1, num_warps=2, num_stages=1) del primals_3 buf3 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.float32) triton_per_fused_div_exp_mul_sigmoid_sum_1[grid(16)](buf1, buf2, primals_1, buf3, 16, 16, XBLOCK=8, num_warps=2, num_stages=1) return buf3, primals_1, primals_2, buf1, buf2 class GlobalWeightedAvgPool2dNew(nn.Module): """ Global Weighted Average Pooling from paper "Global Weighted Average Pooling Bridges Pixel-level Localization and Image-level Classification" """ def __init__(self, features: 'int', flatten=False): super().__init__() self.conv = nn.Conv2d(features, 1, kernel_size=1, bias=True) self.flatten = flatten def fscore(self, x): m = self.conv(x) m = m.sigmoid().exp() return m def norm(self, x: 'torch.Tensor'): return x / x.sum(dim=[2, 3], keepdim=True) def forward(self, input_0): primals_2 = self.conv.weight primals_3 = self.conv.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
dong03/DogNoseLandmarks
GlobalWeightedAvgPool2d
false
6,599
[ "MIT" ]
1
ac5d1e0436e9e0835a6939f8d125f1d36007bc62
https://github.com/dong03/DogNoseLandmarks/tree/ac5d1e0436e9e0835a6939f8d125f1d36007bc62
MSELossWithIgnore
import torch import torch.nn.functional from torch import nn class MSELossWithIgnore(nn.Module): def __init__(self, ignore_value: 'int', fraction: 'float'=1.0): super().__init__() self.ignore_value = ignore_value self.fraction = fraction def forward(self, output, target): loss = torch.nn.functional.mse_loss(output, target, reduction='none') loss = torch.masked_fill(loss, target.eq(self.ignore_value), 0) if self.fraction < 1: loss = loss.reshape(loss.size(0), -1) M = loss.size(1) num_elements_to_keep = int(M * self.fraction) loss, _ = torch.topk(loss, k=num_elements_to_keep, dim=1, largest=False, sorted=False) return loss.mean() def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'ignore_value': 4}]
import torch 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 torch.nn.functional from torch import nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_eq_masked_fill_mean_mse_loss_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp3 = tl.load(in_ptr1 + r0, None) tmp1 = 4.0 tmp2 = tmp0 == tmp1 tmp4 = tmp3 - tmp0 tmp5 = tmp4 * tmp4 tmp6 = 0.0 tmp7 = tl.where(tmp2, tmp6, tmp5) tmp8 = tl.broadcast_to(tmp7, [RBLOCK]) tmp10 = triton_helpers.promote_to_tensor(tl.sum(tmp8, 0)) tmp11 = 256.0 tmp12 = tmp10 / tmp11 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp12, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf1 = buf0 del buf0 get_raw_stream(0) triton_per_fused_eq_masked_fill_mean_mse_loss_0[grid(1)](buf1, arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 return buf1, class MSELossWithIgnoreNew(nn.Module): def __init__(self, ignore_value: 'int', fraction: 'float'=1.0): super().__init__() self.ignore_value = ignore_value self.fraction = fraction def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
drivendataorg/DrivenData-2021-Geopose-Solution
MSELossWithIgnore
false
6,600
[ "MIT" ]
1
fc1dead0aeb1ade9e9d87b55f56e631c57e966a6
https://github.com/drivendataorg/DrivenData-2021-Geopose-Solution/tree/fc1dead0aeb1ade9e9d87b55f56e631c57e966a6
ATTA
import torch import torch.nn as nn class ATTA(nn.Module): def __init__(self): super(ATTA, self).__init__() self.conv1 = nn.Conv2d(3, 3, 16, padding='same', groups=1, bias=False) self.lr = nn.LeakyReLU(0.2) self.conv2 = nn.Conv2d(3, 3, 3, padding='same', groups=1, bias=False) torch.nn.init.dirac_(self.conv1.weight, 1) torch.nn.init.dirac_(self.conv2.weight, 1) self.conv1.weight.data += torch.randn_like(self.conv1.weight.data ) * 0.01 self.conv2.weight.data += torch.randn_like(self.conv2.weight.data ) * 0.01 def forward(self, x): x2 = self.conv1(x) x3 = self.lr(x2) x4 = self.conv2(x3) return x4 def get_inputs(): return [torch.rand([4, 3, 4, 4])] 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 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 @triton.jit def triton_poi_fused_constant_pad_nd_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 300 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 5 % 5 x0 = xindex % 5 x2 = xindex // 25 x3 = xindex tmp0 = x1 tmp1 = tl.full([1], 4, tl.int64) tmp2 = tmp0 < tmp1 tmp3 = x0 tmp4 = tmp3 < tmp1 tmp5 = tmp2 & tmp4 tmp6 = tl.load(in_ptr0 + (x0 + 4 * x1 + 16 * x2), tmp5 & xmask, other=0.0) tl.store(out_ptr0 + x3, tmp6, xmask) @triton.jit def triton_poi_fused_leaky_relu_1(in_ptr0, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 192 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 0.0 tmp2 = tmp0 > tmp1 tmp3 = 0.2 tmp4 = tmp0 * tmp3 tmp5 = tl.where(tmp2, tmp0, tmp4) tl.store(out_ptr0 + x0, tmp2, xmask) tl.store(out_ptr1 + x0, tmp5, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (3, 3, 16, 16), (768, 256, 16, 1)) assert_size_stride(primals_2, (4, 3, 4, 4), (48, 16, 4, 1)) assert_size_stride(primals_3, (3, 3, 3, 3), (27, 9, 3, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 3, 5, 5), (75, 25, 5, 1), torch.float32) get_raw_stream(0) triton_poi_fused_constant_pad_nd_0[grid(300)](primals_2, buf0, 300, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 buf1 = extern_kernels.convolution(buf0, primals_1, stride=(1, 1), padding=(7, 7), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf1, (4, 3, 4, 4), (48, 16, 4, 1)) buf2 = empty_strided_cuda((4, 3, 4, 4), (48, 16, 4, 1), torch.bool) buf3 = empty_strided_cuda((4, 3, 4, 4), (48, 16, 4, 1), torch.float32) triton_poi_fused_leaky_relu_1[grid(192)](buf1, buf2, buf3, 192, XBLOCK=256, num_warps=4, num_stages=1) del buf1 buf4 = extern_kernels.convolution(buf3, primals_3, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf4, (4, 3, 4, 4), (48, 16, 4, 1)) return buf4, primals_1, primals_3, buf0, buf2, buf3 class ATTANew(nn.Module): def __init__(self): super(ATTANew, self).__init__() self.conv1 = nn.Conv2d(3, 3, 16, padding='same', groups=1, bias=False) self.lr = nn.LeakyReLU(0.2) self.conv2 = nn.Conv2d(3, 3, 3, padding='same', groups=1, bias=False) torch.nn.init.dirac_(self.conv1.weight, 1) torch.nn.init.dirac_(self.conv2.weight, 1) self.conv1.weight.data += torch.randn_like(self.conv1.weight.data ) * 0.01 self.conv2.weight.data += torch.randn_like(self.conv2.weight.data ) * 0.01 def forward(self, input_0): primals_1 = self.conv1.weight primals_3 = self.conv2.weight primals_2 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
dreamflake/ODI
ATTA
false
6,601
[ "MIT" ]
1
d58001b96821c8a74d6ebb5402bd2be2b524890a
https://github.com/dreamflake/ODI/tree/d58001b96821c8a74d6ebb5402bd2be2b524890a
Exponent
import torch import torch.nn.functional from torch import nn class Exponent(nn.Module): def forward(self, x): return x.exp() def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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.functional from torch import nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_exp_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = tl_math.exp(tmp0) tl.store(out_ptr0 + x0, tmp1, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_exp_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 return buf0, class ExponentNew(nn.Module): def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
drivendataorg/DrivenData-2021-Geopose-Solution
Exponent
false
6,602
[ "MIT" ]
1
fc1dead0aeb1ade9e9d87b55f56e631c57e966a6
https://github.com/drivendataorg/DrivenData-2021-Geopose-Solution/tree/fc1dead0aeb1ade9e9d87b55f56e631c57e966a6
LogCoshWithIgnore
import torch import torch.nn.functional from torch import nn class LogCoshWithIgnore(nn.Module): def __init__(self, ignore_value, fraction: 'float'=1.0): super().__init__() self.ignore_value = ignore_value self.fraction = fraction def forward(self, output, target): r = output - target log2 = 0.30102999566 loss = torch.logaddexp(r, -r) - log2 loss = torch.masked_fill(loss, target.eq(self.ignore_value), 0) if self.fraction < 1: loss = loss.reshape(loss.size(0), -1) M = loss.size(1) num_elements_to_keep = int(M * self.fraction) loss, _ = torch.topk(loss, k=num_elements_to_keep, dim=1, largest=False, sorted=False) return loss.mean() def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'ignore_value': 4}]
import torch 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, math as tl_math import torch.nn.functional from torch import nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_eq_logaddexp_masked_fill_mean_neg_sub_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp3 = tl.load(in_ptr1 + r0, None) tmp1 = 4.0 tmp2 = tmp0 == tmp1 tmp4 = tmp3 - tmp0 tmp5 = tmp4 == tmp4 tmp6 = tl_math.abs(tmp4) tmp7 = float('inf') tmp8 = tmp6 != tmp7 tmp9 = tmp5 & tmp8 tmp10 = tmp9 == 0 tmp11 = -tmp4 tmp12 = tmp4 == tmp11 tmp13 = tmp10 & tmp12 tmp14 = tmp4 >= tmp11 tmp15 = tl.where(tmp14, tmp4, tmp11) tmp16 = tl.where(tmp14, tmp11, tmp4) tmp17 = tmp16 - tmp15 tmp18 = tl_math.exp(tmp17) tmp19 = libdevice.log1p(tmp18) tmp20 = tmp15 + tmp19 tmp21 = tl.where(tmp13, tmp4, tmp20) tmp22 = 0.30102999566 tmp23 = tmp21 - tmp22 tmp24 = 0.0 tmp25 = tl.where(tmp2, tmp24, tmp23) tmp26 = tl.broadcast_to(tmp25, [RBLOCK]) tmp28 = triton_helpers.promote_to_tensor(tl.sum(tmp26, 0)) tmp29 = 256.0 tmp30 = tmp28 / tmp29 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp30, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf1 = buf0 del buf0 get_raw_stream(0) triton_per_fused_eq_logaddexp_masked_fill_mean_neg_sub_0[grid(1)](buf1, arg1_1, arg0_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 return buf1, class LogCoshWithIgnoreNew(nn.Module): def __init__(self, ignore_value, fraction: 'float'=1.0): super().__init__() self.ignore_value = ignore_value self.fraction = fraction def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
drivendataorg/DrivenData-2021-Geopose-Solution
LogCoshWithIgnore
false
6,603
[ "MIT" ]
1
fc1dead0aeb1ade9e9d87b55f56e631c57e966a6
https://github.com/drivendataorg/DrivenData-2021-Geopose-Solution/tree/fc1dead0aeb1ade9e9d87b55f56e631c57e966a6
GlobalAvgPool2d
import torch from torch import nn class GlobalAvgPool2d(nn.Module): """Performs global average pooling over the entire height and width of a batched 2D tensor # Arguments input: Input tensor """ def forward(self, input): return nn.functional.avg_pool2d(input, kernel_size=input.size()[2:] ).view(-1, input.size(1)) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 import 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_poi_fused_avg_pool2d_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 x0 = xindex tmp0 = tl.load(in_ptr0 + 16 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp3 = tl.load(in_ptr0 + (2 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp5 = tl.load(in_ptr0 + (3 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp7 = tl.load(in_ptr0 + (4 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp9 = tl.load(in_ptr0 + (5 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp11 = tl.load(in_ptr0 + (6 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp13 = tl.load(in_ptr0 + (7 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp15 = tl.load(in_ptr0 + (8 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp17 = tl.load(in_ptr0 + (9 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp19 = tl.load(in_ptr0 + (10 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp21 = tl.load(in_ptr0 + (11 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp23 = tl.load(in_ptr0 + (12 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp25 = tl.load(in_ptr0 + (13 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp27 = tl.load(in_ptr0 + (14 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp29 = tl.load(in_ptr0 + (15 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp2 = tmp1 + tmp0 tmp4 = tmp3 + tmp2 tmp6 = tmp5 + tmp4 tmp8 = tmp7 + tmp6 tmp10 = tmp9 + tmp8 tmp12 = tmp11 + tmp10 tmp14 = tmp13 + tmp12 tmp16 = tmp15 + tmp14 tmp18 = tmp17 + tmp16 tmp20 = tmp19 + tmp18 tmp22 = tmp21 + tmp20 tmp24 = tmp23 + tmp22 tmp26 = tmp25 + tmp24 tmp28 = tmp27 + tmp26 tmp30 = tmp29 + tmp28 tmp31 = 0.0625 tmp32 = tmp30 * tmp31 tl.store(out_ptr0 + x0, tmp32, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.float32) get_raw_stream(0) triton_poi_fused_avg_pool2d_0[grid(16)](arg0_1, buf0, 16, XBLOCK=16, num_warps=1, num_stages=1) del arg0_1 return reinterpret_tensor(buf0, (4, 4), (4, 1), 0), class GlobalAvgPool2dNew(nn.Module): """Performs global average pooling over the entire height and width of a batched 2D tensor # Arguments input: Input tensor """ def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
drjosephliu/few-shot-learning
GlobalAvgPool2d
false
6,604
[ "MIT" ]
1
707c7ce2a0b1813327fb4e39660415b9437b8ec1
https://github.com/drjosephliu/few-shot-learning/tree/707c7ce2a0b1813327fb4e39660415b9437b8ec1
CosineSimilarityLoss
import torch import torch.nn.functional from torch import nn class CosineSimilarityLoss(nn.Module): def __init__(self, gamma=1): super().__init__() self.gamma = gamma def forward(self, output, target): loss = 1.0 - torch.clamp(torch.nn.functional.cosine_similarity( output, target, dim=1, eps=0.001), -1, +1) if self.gamma != 1: loss = torch.pow(loss, self.gamma) return loss.mean() def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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.functional from torch import nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_clamp_min_div_linalg_vector_norm_mul_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x0 = xindex % 16 x2 = xindex // 64 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp3 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp9 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp16 = tl.load(in_ptr1 + x3, xmask) tmp17 = tl.load(in_ptr1 + (x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp19 = tl.load(in_ptr1 + (16 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp22 = tl.load(in_ptr1 + (32 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp25 = tl.load(in_ptr1 + (48 + x0 + 64 * x2), 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 = 0.001 tmp14 = triton_helpers.maximum(tmp12, tmp13) tmp15 = tmp0 / tmp14 tmp18 = tmp17 * tmp17 tmp20 = tmp19 * tmp19 tmp21 = tmp18 + tmp20 tmp23 = tmp22 * tmp22 tmp24 = tmp21 + tmp23 tmp26 = tmp25 * tmp25 tmp27 = tmp24 + tmp26 tmp28 = libdevice.sqrt(tmp27) tmp29 = triton_helpers.maximum(tmp28, tmp13) tmp30 = tmp16 / tmp29 tmp31 = tmp15 * tmp30 tl.store(out_ptr0 + x3, tmp31, xmask) @triton.jit def triton_per_fused_clamp_mean_rsub_sum_1(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 64 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex % 16 r1 = rindex // 16 tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None) tmp1 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None) tmp3 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None) tmp5 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None) tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp6 = tmp4 + tmp5 tmp7 = -1.0 tmp8 = triton_helpers.maximum(tmp6, tmp7) tmp9 = 1.0 tmp10 = triton_helpers.minimum(tmp8, tmp9) tmp11 = tmp9 - tmp10 tmp12 = tl.broadcast_to(tmp11, [XBLOCK, RBLOCK]) tmp14 = tl.sum(tmp12, 1)[:, None] tmp15 = 64.0 tmp16 = tmp14 / tmp15 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp16, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_clamp_min_div_linalg_vector_norm_mul_0[grid(256)]( arg1_1, arg0_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 del arg1_1 buf1 = empty_strided_cuda((), (), torch.float32) buf2 = buf1 del buf1 triton_per_fused_clamp_mean_rsub_sum_1[grid(1)](buf2, buf0, 1, 64, XBLOCK=1, num_warps=2, num_stages=1) del buf0 return buf2, class CosineSimilarityLossNew(nn.Module): def __init__(self, gamma=1): super().__init__() self.gamma = gamma def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
drivendataorg/DrivenData-2021-Geopose-Solution
CosineSimilarityLoss
false
6,605
[ "MIT" ]
1
fc1dead0aeb1ade9e9d87b55f56e631c57e966a6
https://github.com/drivendataorg/DrivenData-2021-Geopose-Solution/tree/fc1dead0aeb1ade9e9d87b55f56e631c57e966a6
HuberLossWithIgnore
import torch from torch import Tensor import torch.nn.functional from torch import nn class HuberLossWithIgnore(nn.Module): def __init__(self, ignore_value: 'int', delta: 'float'=1, fraction: 'float'=1.0): super().__init__() self.ignore_value = ignore_value self.delta = delta self.fraction = fraction def forward(self, output, target): loss = torch.nn.functional.huber_loss(output, target, delta=self. delta, reduction='none') loss: 'Tensor' = torch.masked_fill(loss, target.eq(self. ignore_value), 0) if self.fraction < 1: loss = loss.reshape(loss.size(0), -1) M = loss.size(1) num_elements_to_keep = int(M * self.fraction) loss, _ = torch.topk(loss, k=num_elements_to_keep, dim=1, largest=False, sorted=False) return loss.mean() def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'ignore_value': 4}]
import torch 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 torch.nn.functional from torch import nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_eq_huber_loss_masked_fill_mean_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp3 = tl.load(in_ptr1 + r0, None) tmp1 = 4.0 tmp2 = tmp0 == tmp1 tmp4 = tmp3 - tmp0 tmp5 = tl_math.abs(tmp4) tmp6 = 1.0 tmp7 = tmp5 < tmp6 tmp8 = 0.5 tmp9 = tmp5 * tmp8 tmp10 = tmp9 * tmp5 tmp11 = tmp5 - tmp8 tmp12 = tmp11 * tmp6 tmp13 = tl.where(tmp7, tmp10, tmp12) tmp14 = 0.0 tmp15 = tl.where(tmp2, tmp14, tmp13) tmp16 = tl.broadcast_to(tmp15, [RBLOCK]) tmp18 = triton_helpers.promote_to_tensor(tl.sum(tmp16, 0)) tmp19 = 256.0 tmp20 = tmp18 / tmp19 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp20, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf1 = buf0 del buf0 get_raw_stream(0) triton_per_fused_eq_huber_loss_masked_fill_mean_0[grid(1)](buf1, arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 return buf1, class HuberLossWithIgnoreNew(nn.Module): def __init__(self, ignore_value: 'int', delta: 'float'=1, fraction: 'float'=1.0): super().__init__() self.ignore_value = ignore_value self.delta = delta self.fraction = fraction def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
drivendataorg/DrivenData-2021-Geopose-Solution
HuberLossWithIgnore
false
6,606
[ "MIT" ]
1
fc1dead0aeb1ade9e9d87b55f56e631c57e966a6
https://github.com/drivendataorg/DrivenData-2021-Geopose-Solution/tree/fc1dead0aeb1ade9e9d87b55f56e631c57e966a6
SmoothL1LossWithIgnore
import torch import torch.nn.functional from torch import nn class SmoothL1LossWithIgnore(nn.Module): def __init__(self, ignore_value: 'int', fraction: 'float'=1.0): super().__init__() self.ignore_value = ignore_value self.fraction = fraction def forward(self, output, target): loss = torch.nn.functional.smooth_l1_loss(output, target, reduction ='none') loss = torch.masked_fill(loss, target.eq(self.ignore_value), 0) if self.fraction < 1: loss = loss.reshape(loss.size(0), -1) M = loss.size(1) num_elements_to_keep = int(M * self.fraction) loss, _ = torch.topk(loss, k=num_elements_to_keep, dim=1, largest=False, sorted=False) return loss.mean() def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'ignore_value': 4}]
import torch 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 torch.nn.functional from torch import nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_eq_masked_fill_mean_smooth_l1_loss_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp3 = tl.load(in_ptr1 + r0, None) tmp1 = 4.0 tmp2 = tmp0 == tmp1 tmp4 = tmp3 - tmp0 tmp5 = tl_math.abs(tmp4) tmp6 = 1.0 tmp7 = tmp5 < tmp6 tmp8 = tmp5 * tmp5 tmp9 = 0.5 tmp10 = tmp8 * tmp9 tmp11 = tmp10 * tmp6 tmp12 = tmp5 - tmp9 tmp13 = tl.where(tmp7, tmp11, tmp12) tmp14 = 0.0 tmp15 = tl.where(tmp2, tmp14, tmp13) tmp16 = tl.broadcast_to(tmp15, [RBLOCK]) tmp18 = triton_helpers.promote_to_tensor(tl.sum(tmp16, 0)) tmp19 = 256.0 tmp20 = tmp18 / tmp19 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp20, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf1 = buf0 del buf0 get_raw_stream(0) triton_per_fused_eq_masked_fill_mean_smooth_l1_loss_0[grid(1)](buf1, arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 return buf1, class SmoothL1LossWithIgnoreNew(nn.Module): def __init__(self, ignore_value: 'int', fraction: 'float'=1.0): super().__init__() self.ignore_value = ignore_value self.fraction = fraction def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
drivendataorg/DrivenData-2021-Geopose-Solution
SmoothL1LossWithIgnore
false
6,607
[ "MIT" ]
1
fc1dead0aeb1ade9e9d87b55f56e631c57e966a6
https://github.com/drivendataorg/DrivenData-2021-Geopose-Solution/tree/fc1dead0aeb1ade9e9d87b55f56e631c57e966a6
MyLeakyReLU
import torch import torch.nn as nn class MyLeakyReLU(nn.Module): def __init__(self, negative_slope=0.01): super(MyLeakyReLU, self).__init__() self.negative_slope = negative_slope def forward(self, x): return torch.clamp(x, min=0.0) + torch.clamp(x, max=0.0 ) * self.negative_slope def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_add_clamp_mul_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 0.0 tmp2 = triton_helpers.maximum(tmp0, tmp1) tmp3 = triton_helpers.minimum(tmp0, tmp1) tmp4 = 0.01 tmp5 = tmp3 * tmp4 tmp6 = tmp2 + tmp5 tl.store(out_ptr0 + x0, tmp6, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_clamp_mul_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 return buf0, class MyLeakyReLUNew(nn.Module): def __init__(self, negative_slope=0.01): super(MyLeakyReLUNew, self).__init__() self.negative_slope = negative_slope def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
dsarrut/gaga
MyLeakyReLU
false
6,608
[ "Apache-2.0" ]
1
4b34210074f8f82acb12e0ffb38858e83c319dc3
https://github.com/dsarrut/gaga/tree/4b34210074f8f82acb12e0ffb38858e83c319dc3
GlobalMaxPool1d
import torch from torch import nn class GlobalMaxPool1d(nn.Module): """Performs global max pooling over the entire length of a batched 1D tensor # Arguments input: Input tensor """ def forward(self, input): return nn.functional.max_pool1d(input, kernel_size=input.size()[2:] ).view(-1, input.size(1)) def get_inputs(): return [torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 import 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_poi_fused_max_pool2d_with_indices_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 x0 = xindex tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last') tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp6 = triton_helpers.maximum(tmp5, tmp4) tl.store(out_ptr0 + x0, tmp6, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4), (16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32) get_raw_stream(0) triton_poi_fused_max_pool2d_with_indices_0[grid(16)](arg0_1, buf0, 16, XBLOCK=16, num_warps=1, num_stages=1) del arg0_1 return reinterpret_tensor(buf0, (4, 4), (4, 1), 0), class GlobalMaxPool1dNew(nn.Module): """Performs global max pooling over the entire length of a batched 1D tensor # Arguments input: Input tensor """ def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
drjosephliu/few-shot-learning
GlobalMaxPool1d
false
6,609
[ "MIT" ]
1
707c7ce2a0b1813327fb4e39660415b9437b8ec1
https://github.com/drjosephliu/few-shot-learning/tree/707c7ce2a0b1813327fb4e39660415b9437b8ec1
LabelSmoothing
import torch from torch import nn class LabelSmoothing(nn.Module): """ Label Smoothing Attributes ---------- criterion : torch.nn.KLDivLoss padding_idx : int eps : float n_vocab : int """ def __init__(self, n_vocab, eps, padding_idx=0): """ Parameters ---------- n_vocab : int size of vocab eps : float portion of the one hot that will be taken away padding_idx : int indicator of which value should be considered as padding """ super(LabelSmoothing, self).__init__() self.criterion = nn.KLDivLoss(reduction='sum') self.padding_idx = padding_idx self.eps = eps self.n_vocab = n_vocab def forward(self, pred, gold): """ Parameters ---------- pred : 2d tensor (batch_size * seq_len, n_vocab) gold : 1d tensor of int (batch_size * seq_len) """ n_vocab, eps, padding_idx = self.n_vocab, self.eps, self.padding_idx dist = pred.clone() dist.fill_(eps / (n_vocab - 2)) dist.scatter_(1, gold.view(gold.shape[0], -1), 1 - eps) dist[:, padding_idx] = 0 mask = gold != padding_idx dist.mul_(mask.view(dist.shape[0], 1)) return self.criterion(pred, dist) def get_inputs(): return [torch.rand([4, 2]), torch.ones([4, 1], dtype=torch.int64)] def get_init_inputs(): return [[], {'n_vocab': 4, 'eps': 4}]
import torch 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 libdevice, math as tl_math from torch import nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_fill_lift_fresh_mul_ne_scatter_sub_sum_xlogy_0(in_ptr0, in_ptr1, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 8 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex % 2 r1 = rindex // 2 r2 = rindex tmp3 = tl.load(in_ptr0 + r1, None, eviction_policy='evict_last') tmp21 = tl.load(in_ptr1 + r2, None) tmp0 = r0 tmp1 = tl.full([1, 1], 0, tl.int32) tmp2 = tmp0 == tmp1 tmp4 = tmp3 == tmp0 tmp5 = -3.0 tmp6 = 2.0 tmp7 = tl.where(tmp4, tmp5, tmp6) tmp8 = 0.0 tmp9 = tl.where(tmp2, tmp8, tmp7) tmp10 = tl.full([1, 1], 0, tl.int64) tmp11 = tmp3 != tmp10 tmp12 = tmp11.to(tl.float32) tmp13 = tmp9 * tmp12 tmp14 = libdevice.isnan(tmp13).to(tl.int1) tmp15 = tmp13 == tmp8 tmp16 = tl_math.log(tmp13) tmp17 = tmp13 * tmp16 tmp18 = tl.where(tmp15, tmp8, tmp17) tmp19 = float('nan') tmp20 = tl.where(tmp14, tmp19, tmp18) tmp22 = tmp13 * tmp21 tmp23 = tmp20 - tmp22 tmp24 = tl.broadcast_to(tmp23, [XBLOCK, RBLOCK]) tmp26 = tl.sum(tmp24, 1)[:, None] tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp26, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 2), (2, 1)) assert_size_stride(arg1_1, (4, 1), (1, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) get_raw_stream(0) triton_per_fused_fill_lift_fresh_mul_ne_scatter_sub_sum_xlogy_0[grid(1) ](arg1_1, arg0_1, buf0, 1, 8, XBLOCK=1, num_warps=2, num_stages=1) del arg0_1 del arg1_1 return buf0, class LabelSmoothingNew(nn.Module): """ Label Smoothing Attributes ---------- criterion : torch.nn.KLDivLoss padding_idx : int eps : float n_vocab : int """ def __init__(self, n_vocab, eps, padding_idx=0): """ Parameters ---------- n_vocab : int size of vocab eps : float portion of the one hot that will be taken away padding_idx : int indicator of which value should be considered as padding """ super(LabelSmoothingNew, self).__init__() self.criterion = nn.KLDivLoss(reduction='sum') self.padding_idx = padding_idx self.eps = eps self.n_vocab = n_vocab def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
dugusword/transformer
LabelSmoothing
false
6,610
[ "MIT" ]
1
7aa10968f0e60d545bbd17f1f8c1dfb7ee88c62b
https://github.com/dugusword/transformer/tree/7aa10968f0e60d545bbd17f1f8c1dfb7ee88c62b
ViTClassifierPipe
from _paritybench_helpers import _mock_config import torch import torch.nn as nn class ViTClassifierPipe(nn.Module): def __init__(self, config: 'ViTConfig'): super().__init__() self.layernorm = nn.LayerNorm(config.hidden_size, eps=config. layer_norm_eps) self.classifier = nn.Linear(config.hidden_size, config.num_labels ) if config.num_labels > 0 else nn.Identity() def forward(self, args): hidden_states = args[0] hidden_states = self.layernorm(hidden_states) logits = self.classifier(hidden_states[:, 0, :]) return logits def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'config': _mock_config(hidden_size=4, layer_norm_eps=1, num_labels=4)}]
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 libdevice 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_poi_fused_native_layer_norm_0(in_ptr0, out_ptr0, out_ptr1, 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_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp6 = tmp4 + tmp5 tmp7 = 4.0 tmp8 = tmp6 / tmp7 tmp9 = tmp0 - tmp8 tmp10 = tmp9 * tmp9 tmp11 = tmp1 - tmp8 tmp12 = tmp11 * tmp11 tmp13 = tmp10 + tmp12 tmp14 = tmp3 - tmp8 tmp15 = tmp14 * tmp14 tmp16 = tmp13 + tmp15 tmp17 = tmp5 - tmp8 tmp18 = tmp17 * tmp17 tmp19 = tmp16 + tmp18 tmp20 = tmp19 / tmp7 tmp21 = 1.0 tmp22 = tmp20 + tmp21 tmp23 = libdevice.rsqrt(tmp22) tl.store(out_ptr0 + x0, tmp8, xmask) tl.store(out_ptr1 + x0, tmp23, xmask) @triton.jit def triton_poi_fused_native_layer_norm_1(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 - tmp1 tmp4 = tmp2 * tmp3 tmp6 = tmp4 * tmp5 tmp8 = tmp6 + tmp7 tl.store(out_ptr0 + x2, tmp4, xmask) tl.store(out_ptr1 + x2, tmp8, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4,), (1,)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32) buf1 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32) get_raw_stream(0) triton_poi_fused_native_layer_norm_0[grid(16)](primals_1, buf0, buf1, 16, XBLOCK=16, num_warps=1, num_stages=1) buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_native_layer_norm_1[grid(64)](primals_1, buf0, buf1, primals_2, primals_3, buf2, buf3, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf0 del primals_1 del primals_2 del primals_3 buf4 = reinterpret_tensor(buf1, (4, 4), (4, 1), 0) del buf1 extern_kernels.addmm(primals_5, reinterpret_tensor(buf3, (4, 4), ( 16, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf4) del primals_5 return buf4, buf2, reinterpret_tensor(buf3, (4, 4), (16, 1), 0), primals_4 class ViTClassifierPipeNew(nn.Module): def __init__(self, config: 'ViTConfig'): super().__init__() self.layernorm = nn.LayerNorm(config.hidden_size, eps=config. layer_norm_eps) self.classifier = nn.Linear(config.hidden_size, config.num_labels ) if config.num_labels > 0 else nn.Identity() def forward(self, input_0): primals_2 = self.layernorm.weight primals_3 = self.layernorm.bias primals_4 = self.classifier.weight primals_5 = self.classifier.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
drunkcoding/huggingface-utils
ViTClassifierPipe
false
6,611
[ "MIT" ]
1
4baad306857c357d94607076c6ab0cb5d6350cbe
https://github.com/drunkcoding/huggingface-utils/tree/4baad306857c357d94607076c6ab0cb5d6350cbe
MultiHeadAttention
import math import torch from torch import nn class ScaledDotProductAttention(nn.Module): """ Scaled Dot-Product Attention Layer Attributes ---------- softmax : nn.Functional softmax function applied at the last dimension """ def __init__(self, dropout=0.1): super(ScaledDotProductAttention, self).__init__() self.softmax = nn.Softmax(dim=-1) self.dropout = nn.Dropout(dropout) def forward(self, Q, K, V, mask=None): """ Parameters ---------- Q : 4d tensor (batch_size, h, seq_len, d_K) K : 4d tensor (batch_size, h, seq_len, d_K) V : 4d tensor (batch_size, h, seq_len, d_V) mask : 2d tensor (seq_len, seq_len) 2d binary tensor, where 1 means connection should be blocked and 0 means values can be fed forward to softmax Returns ------- 4d tensor (batch_size, h, seq_len, d_V) """ scaled = torch.matmul(Q, K.transpose_(2, 3)) scaled = scaled / math.sqrt(K.shape[3]) if mask is not None: scaled.masked_fill_(mask, float('-inf')) scaled = self.softmax(scaled) scaled = self.dropout(scaled) attn = torch.matmul(scaled, V) return attn class MultiHeadAttention(nn.Module): """ Multi-Head Attention Layer Attributes ---------- h : int number of parallel heads d_K : int dimension of features in both query and key d_V : int dimension of features in value d_model : int dimension of token embedding spd_attn: ScaledDotProductattention layer sub module to apply scaled dot product W_Q : 2d tensor (d_model, d_K * h) learned parameters used to linearly project query to Q W_K : 2d tensor (d_model, d_K * h) learned parameters used to linearly project key to K W_V : 2d tensor (d_model, d_V * h) learned parameters used to linearly project val to V W_O : 2d tensor (d_V * h, d_model) learned parameters used to linearly project scaled attention to the output tensor with the same dimension as input """ def __init__(self, h, d_model, d_K, d_V, dropout=0.1): super(MultiHeadAttention, self).__init__() self.h = h self.d_K = d_K self.d_V = d_V self.d_model = d_model self.sdp_attn = ScaledDotProductAttention(dropout=dropout) self.W_Q = nn.Parameter(torch.Tensor(d_model, d_K * h)) self.W_K = nn.Parameter(torch.Tensor(d_model, d_K * h)) self.W_V = nn.Parameter(torch.Tensor(d_model, d_V * h)) self.W_O = nn.Parameter(torch.Tensor(d_V * h, d_model)) self.dropout = nn.Dropout(dropout) self.reset_parameters() def reset_parameters(self): slope = math.sqrt(5) nn.init.kaiming_uniform_(self.W_Q, a=slope) nn.init.kaiming_uniform_(self.W_K, a=slope) nn.init.kaiming_uniform_(self.W_V, a=slope) nn.init.kaiming_uniform_(self.W_O, a=slope) def forward(self, query, key, val, mask=None): """ Parameters ---------- query : 3d tensor (batch_size, seq_len, d_model) embedded query sequence key : 3d tensor (batch_size, seq_len, d_model) embedded key sequence val : 3d tensor (batch_size, seq_len, d_model) embedded value sequence mask : 2d tensor (seq_len, seq_len) 2d binary tensor, where 1 means pass, 0 means block Returns ------- 3d tensor (batch_size, seq_len, d_model) """ h, d_K, d_V, _d_model = self.h, self.d_K, self.d_V, self.d_model W_Q, W_K, W_V, W_O = self.W_Q, self.W_K, self.W_V, self.W_O bs_q, l_q = query.shape[0], query.shape[1] bs_k, l_k = key.shape[0], key.shape[1] bs_v, l_v = val.shape[0], val.shape[1] Q = torch.matmul(query, W_Q) K = torch.matmul(key, W_K) V = torch.matmul(val, W_V) Q = Q.view(bs_q, l_q, h, d_K) K = K.view(bs_k, l_k, h, d_K) V = V.view(bs_v, l_v, h, d_V) Q.transpose_(1, 2) K.transpose_(1, 2) V.transpose_(1, 2) head = self.sdp_attn(Q, K, V, mask) head.transpose_(1, 2) head = head.reshape(bs_q, l_q, h * d_V) res = torch.matmul(head, W_O) return self.dropout(res) def get_inputs(): return [torch.rand([4, 4, 4]), torch.rand([4, 4, 4]), torch.rand([4, 4, 4]) ] def get_init_inputs(): return [[], {'h': 4, 'd_model': 4, 'd_K': 4, 'd_V': 4}]
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 import math from torch import 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_poi_fused_view_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tl.store(out_ptr0 + x0, tmp0, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7) = args args.clear() assert_size_stride(primals_1, (4, 16), (16, 1)) assert_size_stride(primals_2, (4, 16), (16, 1)) assert_size_stride(primals_3, (4, 16), (16, 1)) assert_size_stride(primals_4, (16, 4), (4, 1)) assert_size_stride(primals_5, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_6, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_7, (4, 4, 4), (16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((16, 16), (16, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_5, (16, 4), (4, 1), 0), primals_1, out=buf0) del primals_1 buf1 = empty_strided_cuda((16, 16), (16, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_6, (16, 4), (4, 1), 0), primals_2, out=buf1) del primals_2 buf2 = empty_strided_cuda((16, 16), (16, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_7, (16, 4), (4, 1), 0), primals_3, out=buf2) del primals_3 buf3 = torch.ops.aten._scaled_dot_product_efficient_attention.default( reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 4, 16, 1), 0), reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 4, 16, 1), 0), reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 4, 16, 1), 0), None, True, scale=0.5) buf4 = buf3[0] buf5 = buf3[1] buf6 = buf3[2] buf7 = buf3[3] del buf3 buf8 = empty_strided_cuda((16, 16), (16, 1), torch.float32) get_raw_stream(0) triton_poi_fused_view_0[grid(256)](buf4, buf8, 256, XBLOCK=128, num_warps=4, num_stages=1) buf9 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(buf8, primals_4, out=buf9) return reinterpret_tensor(buf9, (4, 4, 4), (16, 4, 1), 0 ), reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 4, 16, 1), 0 ), reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 4, 16, 1), 0 ), reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 4, 16, 1), 0 ), buf4, buf5, buf6, buf7, reinterpret_tensor(buf8, (16, 16), (1, 16), 0), reinterpret_tensor(primals_4, (4, 16), (1, 4), 0 ), reinterpret_tensor(primals_7, (4, 16), (1, 4), 0 ), reinterpret_tensor(primals_6, (4, 16), (1, 4), 0 ), reinterpret_tensor(primals_5, (4, 16), (1, 4), 0) class ScaledDotProductAttention(nn.Module): """ Scaled Dot-Product Attention Layer Attributes ---------- softmax : nn.Functional softmax function applied at the last dimension """ def __init__(self, dropout=0.1): super(ScaledDotProductAttention, self).__init__() self.softmax = nn.Softmax(dim=-1) self.dropout = nn.Dropout(dropout) def forward(self, Q, K, V, mask=None): """ Parameters ---------- Q : 4d tensor (batch_size, h, seq_len, d_K) K : 4d tensor (batch_size, h, seq_len, d_K) V : 4d tensor (batch_size, h, seq_len, d_V) mask : 2d tensor (seq_len, seq_len) 2d binary tensor, where 1 means connection should be blocked and 0 means values can be fed forward to softmax Returns ------- 4d tensor (batch_size, h, seq_len, d_V) """ scaled = torch.matmul(Q, K.transpose_(2, 3)) scaled = scaled / math.sqrt(K.shape[3]) if mask is not None: scaled.masked_fill_(mask, float('-inf')) scaled = self.softmax(scaled) scaled = self.dropout(scaled) attn = torch.matmul(scaled, V) return attn class MultiHeadAttentionNew(nn.Module): """ Multi-Head Attention Layer Attributes ---------- h : int number of parallel heads d_K : int dimension of features in both query and key d_V : int dimension of features in value d_model : int dimension of token embedding spd_attn: ScaledDotProductattention layer sub module to apply scaled dot product W_Q : 2d tensor (d_model, d_K * h) learned parameters used to linearly project query to Q W_K : 2d tensor (d_model, d_K * h) learned parameters used to linearly project key to K W_V : 2d tensor (d_model, d_V * h) learned parameters used to linearly project val to V W_O : 2d tensor (d_V * h, d_model) learned parameters used to linearly project scaled attention to the output tensor with the same dimension as input """ def __init__(self, h, d_model, d_K, d_V, dropout=0.1): super(MultiHeadAttentionNew, self).__init__() self.h = h self.d_K = d_K self.d_V = d_V self.d_model = d_model self.sdp_attn = ScaledDotProductAttention(dropout=dropout) self.W_Q = nn.Parameter(torch.Tensor(d_model, d_K * h)) self.W_K = nn.Parameter(torch.Tensor(d_model, d_K * h)) self.W_V = nn.Parameter(torch.Tensor(d_model, d_V * h)) self.W_O = nn.Parameter(torch.Tensor(d_V * h, d_model)) self.dropout = nn.Dropout(dropout) self.reset_parameters() def reset_parameters(self): slope = math.sqrt(5) nn.init.kaiming_uniform_(self.W_Q, a=slope) nn.init.kaiming_uniform_(self.W_K, a=slope) nn.init.kaiming_uniform_(self.W_V, a=slope) nn.init.kaiming_uniform_(self.W_O, a=slope) def forward(self, input_0, input_1, input_2): primals_1 = self.W_Q primals_2 = self.W_K primals_3 = self.W_V primals_4 = self.W_O primals_5 = input_0 primals_6 = input_1 primals_7 = input_2 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0]
dugusword/transformer
MultiHeadAttention
false
6,612
[ "MIT" ]
1
7aa10968f0e60d545bbd17f1f8c1dfb7ee88c62b
https://github.com/dugusword/transformer/tree/7aa10968f0e60d545bbd17f1f8c1dfb7ee88c62b
Fusion
import torch import torch.nn as nn import torch.utils.checkpoint class Fusion(nn.Module): """ The subnetwork that is used in TFN for video and audio in the pre-fusion stage """ def __init__(self, in_size, hidden_size, n_class, dropout, modal_name= 'text'): """ Args: in_size: input dimension hidden_size: hidden layer dimension dropout: dropout probability Output: (return value in forward) a tensor of shape (batch_size, hidden_size) """ super(Fusion, self).__init__() self.drop = nn.Dropout(p=dropout) self.linear_1 = nn.Linear(in_size, hidden_size) self.linear_2 = nn.Linear(hidden_size, hidden_size) self.linear_3 = nn.Linear(hidden_size, n_class) def forward(self, x): """ Args: x: tensor of shape (batch_size, in_size) """ dropped = self.drop(x) y_1 = torch.tanh(self.linear_1(dropped)) self.linear_2(y_1) y_2 = torch.tanh(self.linear_2(y_1)) y_3 = self.linear_3(y_2) return y_2, y_3 def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_size': 4, 'hidden_size': 4, 'n_class': 4, 'dropout': 0.5}]
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 libdevice import torch.nn as nn import torch.utils.checkpoint 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_tanh_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = libdevice.tanh(tmp2) tl.store(in_out_ptr0 + x2, tmp3, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7) = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4, 4), (4, 1)) assert_size_stride(primals_3, (4,), (1,)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (4, 4), (4, 1)) assert_size_stride(primals_7, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0) del primals_2 buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf0 get_raw_stream(0) triton_poi_fused_tanh_0[grid(256)](buf1, primals_3, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_3 buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf2) buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf2 triton_poi_fused_tanh_0[grid(256)](buf3, primals_5, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_5 buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_7, reinterpret_tensor(buf3, (64, 4), ( 4, 1), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf4) del primals_7 return buf3, reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0 ), reinterpret_tensor(primals_1, (64, 4), (4, 1), 0 ), buf1, buf3, primals_6, primals_4 class FusionNew(nn.Module): """ The subnetwork that is used in TFN for video and audio in the pre-fusion stage """ def __init__(self, in_size, hidden_size, n_class, dropout, modal_name= 'text'): """ Args: in_size: input dimension hidden_size: hidden layer dimension dropout: dropout probability Output: (return value in forward) a tensor of shape (batch_size, hidden_size) """ super(FusionNew, self).__init__() self.drop = nn.Dropout(p=dropout) self.linear_1 = nn.Linear(in_size, hidden_size) self.linear_2 = nn.Linear(hidden_size, hidden_size) self.linear_3 = nn.Linear(hidden_size, n_class) def forward(self, input_0): primals_2 = self.linear_1.weight primals_3 = self.linear_1.bias primals_4 = self.linear_2.weight primals_5 = self.linear_2.bias primals_6 = self.linear_3.weight primals_7 = self.linear_3.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0], output[1]
dumpmemory/MMSA
Fusion
false
6,613
[ "MIT" ]
1
08b3a7f4529c380356eeb1cf6bf9a89e7c9701e7
https://github.com/dumpmemory/MMSA/tree/08b3a7f4529c380356eeb1cf6bf9a89e7c9701e7
FeatureVolume
import torch import torch.nn as nn import torch.nn.functional as F class FeatureVolume(nn.Module): def __init__(self, fdim, fsize): super().__init__() self.fsize = fsize self.fdim = fdim var = 0.01 self.fmx = nn.Parameter(torch.randn(1, fdim, fsize, fsize) * var) self.sparse = None self.padding_mode = 'reflection' def forward(self, x): N = x.shape[0] if len(x.shape) == 3: sample_coords = x.reshape(1, N, x.shape[1], 3) sampley = F.grid_sample(self.fmx, sample_coords[..., [0, 2]], align_corners=True, padding_mode=self.padding_mode)[0, :, :, : ].transpose(0, 1) else: sample_coords = x.reshape(1, N, 1, 3) sampley = F.grid_sample(self.fmx, sample_coords[..., [0, 2]], align_corners=True, padding_mode=self.padding_mode)[0, :, :, 0 ].transpose(0, 1) return sampley def get_inputs(): return [torch.rand([1, 1, 1, 3])] def get_init_inputs(): return [[], {'fdim': 4, 'fsize': 4}]
import torch 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, 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_poi_fused_index_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 2 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = x0 tmp1 = tl.full([1], 1, tl.int64) tmp2 = tmp0 < tmp1 tmp3 = tl.full([1], 0, tl.int64) tmp4 = tl.full([1], 2, tl.int64) tmp5 = tl.where(tmp2, tmp3, tmp4) tmp6 = tl.load(in_ptr0 + tmp5, xmask, eviction_policy='evict_last') tl.store(out_ptr0 + x0, tmp6, xmask) @triton.jit def triton_poi_fused_grid_sampler_2d_1(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 4 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + 1) tmp1 = tl.broadcast_to(tmp0, [XBLOCK]) tmp30 = tl.load(in_ptr0 + 0) tmp31 = tl.broadcast_to(tmp30, [XBLOCK]) tmp2 = 1.5 tmp3 = tmp1 * tmp2 tmp4 = tmp3 + tmp2 tmp5 = 0.0 tmp6 = tmp4 - tmp5 tmp7 = tl_math.abs(tmp6) tmp8 = 0.3333333333333333 tmp9 = tmp7 * tmp8 tmp10 = libdevice.floor(tmp9) tmp11 = tmp10.to(tl.int8) tmp12 = tl.full([1], 1, tl.int8) tmp13 = tmp11 & tmp12 tmp14 = tl.full([1], 0, tl.int8) tmp15 = tmp13 == tmp14 tmp16 = 3.0 tmp17 = libdevice.fmod(tmp7, tmp16) tmp18 = tmp17 + tmp5 tmp19 = tmp16 - tmp17 tmp20 = tl.where(tmp15, tmp18, tmp19) tmp21 = triton_helpers.maximum(tmp20, tmp5) tmp22 = triton_helpers.minimum(tmp21, tmp16) tmp23 = libdevice.floor(tmp22) tmp24 = 1.0 tmp25 = tmp23 + tmp24 tmp26 = tmp25 >= tmp5 tmp27 = 4.0 tmp28 = tmp25 < tmp27 tmp29 = tmp26 & tmp28 tmp32 = tmp31 * tmp2 tmp33 = tmp32 + tmp2 tmp34 = tmp33 - tmp5 tmp35 = tl_math.abs(tmp34) tmp36 = tmp35 * tmp8 tmp37 = libdevice.floor(tmp36) tmp38 = tmp37.to(tl.int8) tmp39 = tmp38 & tmp12 tmp40 = tmp39 == tmp14 tmp41 = libdevice.fmod(tmp35, tmp16) tmp42 = tmp41 + tmp5 tmp43 = tmp16 - tmp41 tmp44 = tl.where(tmp40, tmp42, tmp43) tmp45 = triton_helpers.maximum(tmp44, tmp5) tmp46 = triton_helpers.minimum(tmp45, tmp16) tmp47 = libdevice.floor(tmp46) tmp48 = tmp47 >= tmp5 tmp49 = tmp47 < tmp27 tmp50 = tmp49 & tmp29 tmp51 = tmp48 & tmp50 tmp52 = tmp47 + tmp24 tmp53 = tmp52 < tmp27 tmp54 = tmp53 & tmp29 tmp55 = tmp23 >= tmp5 tmp56 = tmp23 < tmp27 tmp57 = tmp55 & tmp56 tmp58 = tmp53 & tmp57 tmp59 = tmp49 & tmp57 tmp60 = tmp52 - tmp46 tmp61 = tmp22 - tmp23 tmp62 = tmp60 * tmp61 tmp63 = tmp46 - tmp47 tmp64 = tmp25 - tmp22 tmp65 = tmp63 * tmp64 tmp66 = tmp52 >= tmp5 tmp67 = tmp66 & tmp58 tmp68 = tl.where(tmp67, tmp65, tmp5) tmp69 = tmp63 * tmp61 tmp70 = tmp66 & tmp54 tmp71 = tl.where(tmp70, tmp69, tmp5) tmp72 = tmp60 * tmp64 tmp73 = tmp52.to(tl.int64) tmp74 = tl.full([1], 0, tl.int64) tmp75 = tl.where(tmp67, tmp73, tmp74) tmp76 = tmp23.to(tl.int64) tmp77 = tl.where(tmp67, tmp76, tmp74) tmp78 = tl.where(tmp70, tmp73, tmp74) tmp79 = tmp25.to(tl.int64) tmp80 = tl.where(tmp70, tmp79, tmp74) tmp81 = tl.where(tmp51, tmp79, tmp74) tmp82 = tmp48 & tmp59 tmp83 = tmp47.to(tl.int64) tmp84 = tl.where(tmp82, tmp83, tmp74) tmp85 = tl.where(tmp82, tmp76, tmp74) tmp86 = tl.full([XBLOCK], 4, tl.int32) tmp87 = tmp85 + tmp86 tmp88 = tmp85 < 0 tmp89 = tl.where(tmp88, tmp87, tmp85) tl.device_assert((0 <= tmp89) & (tmp89 < 4), 'index out of bounds: 0 <= tmp89 < 4') tmp91 = tmp84 + tmp86 tmp92 = tmp84 < 0 tmp93 = tl.where(tmp92, tmp91, tmp84) tl.device_assert((0 <= tmp93) & (tmp93 < 4), 'index out of bounds: 0 <= tmp93 < 4') tmp95 = tl.load(in_ptr1 + (tmp93 + 4 * tmp89 + 16 * x0), xmask, eviction_policy='evict_last') tmp96 = tl.where(tmp82, tmp72, tmp5) tmp97 = tmp95 * tmp96 tmp98 = tmp81 + tmp86 tmp99 = tmp81 < 0 tmp100 = tl.where(tmp99, tmp98, tmp81) tl.device_assert((0 <= tmp100) & (tmp100 < 4), 'index out of bounds: 0 <= tmp100 < 4') tmp102 = tl.where(tmp51, tmp83, tmp74) tmp103 = tmp102 + tmp86 tmp104 = tmp102 < 0 tmp105 = tl.where(tmp104, tmp103, tmp102) tl.device_assert((0 <= tmp105) & (tmp105 < 4), 'index out of bounds: 0 <= tmp105 < 4') tmp107 = tl.load(in_ptr1 + (tmp105 + 4 * tmp100 + 16 * x0), xmask, eviction_policy='evict_last') tmp108 = tmp77 + tmp86 tmp109 = tmp77 < 0 tmp110 = tl.where(tmp109, tmp108, tmp77) tl.device_assert((0 <= tmp110) & (tmp110 < 4), 'index out of bounds: 0 <= tmp110 < 4') tmp112 = tmp75 + tmp86 tmp113 = tmp75 < 0 tmp114 = tl.where(tmp113, tmp112, tmp75) tl.device_assert((0 <= tmp114) & (tmp114 < 4), 'index out of bounds: 0 <= tmp114 < 4') tmp116 = tl.load(in_ptr1 + (tmp114 + 4 * tmp110 + 16 * x0), xmask, eviction_policy='evict_last') tmp117 = tmp116 * tmp68 tmp118 = tmp97 + tmp117 tmp119 = tl.where(tmp51, tmp62, tmp5) tmp120 = tmp107 * tmp119 tmp121 = tmp118 + tmp120 tmp122 = tmp80 + tmp86 tmp123 = tmp80 < 0 tmp124 = tl.where(tmp123, tmp122, tmp80) tl.device_assert((0 <= tmp124) & (tmp124 < 4), 'index out of bounds: 0 <= tmp124 < 4') tmp126 = tmp78 + tmp86 tmp127 = tmp78 < 0 tmp128 = tl.where(tmp127, tmp126, tmp78) tl.device_assert((0 <= tmp128) & (tmp128 < 4), 'index out of bounds: 0 <= tmp128 < 4') tmp130 = tl.load(in_ptr1 + (tmp128 + 4 * tmp124 + 16 * x0), xmask, eviction_policy='evict_last') tmp131 = tmp130 * tmp71 tmp132 = tmp121 + tmp131 tl.store(in_out_ptr0 + x0, tmp132, xmask) def call(args): primals_1, primals_2 = args args.clear() assert_size_stride(primals_1, (1, 1, 1, 3), (3, 3, 3, 1)) assert_size_stride(primals_2, (1, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((1, 1, 1, 2), (2, 2, 2, 1), torch.float32) get_raw_stream(0) triton_poi_fused_index_0[grid(2)](primals_1, buf0, 2, XBLOCK=2, num_warps=1, num_stages=1) del primals_1 buf2 = empty_strided_cuda((1, 4, 1, 1), (4, 1, 4, 4), torch.float32) buf12 = buf2 del buf2 buf21 = buf12 del buf12 triton_poi_fused_grid_sampler_2d_1[grid(4)](buf21, buf0, primals_2, 4, XBLOCK=4, num_warps=1, num_stages=1) return reinterpret_tensor(buf21, (1, 4), (1, 1), 0), primals_2, buf0 class FeatureVolumeNew(nn.Module): def __init__(self, fdim, fsize): super().__init__() self.fsize = fsize self.fdim = fdim var = 0.01 self.fmx = nn.Parameter(torch.randn(1, fdim, fsize, fsize) * var) self.sparse = None self.padding_mode = 'reflection' def forward(self, input_0): primals_2 = self.fmx primals_1 = input_0 output = call([primals_1, primals_2]) return output[0]
drixs2050/nglod
FeatureVolume
false
6,614
[ "MIT" ]
1
0f3627d3ece82464335b0fab89c2269fcb016308
https://github.com/drixs2050/nglod/tree/0f3627d3ece82464335b0fab89c2269fcb016308
CoAttentionTransformerEncoderLayer
import torch from torch import Tensor from typing import Optional import torch.nn as nn import torch.nn.functional as F def _get_activation_fn(activation): if activation == 'relu': return F.relu elif activation == 'gelu': return F.gelu raise ValueError('activation should be relu/gelu, not {}'.format( activation)) class CoAttentionTransformerEncoderLayer(nn.Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation='relu'): super(CoAttentionTransformerEncoderLayer, self).__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) self.linear1 = nn.Linear(d_model, dim_feedforward) self.dropout = nn.Dropout(dropout) self.linear2 = nn.Linear(dim_feedforward, d_model) self.norm1 = nn.LayerNorm(d_model) self.norm2 = nn.LayerNorm(d_model) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.activation = _get_activation_fn(activation) def __setstate__(self, state): if 'activation' not in state: state['activation'] = F.relu super(CoAttentionTransformerEncoderLayer, self).__setstate__(state) def forward(self, src: 'Tensor', src_: 'Tensor', src_mask: 'Optional[Tensor]'=None, src_key_padding_mask: 'Optional[Tensor]'=None ) ->Tensor: """Pass the input through the encoder layer. Args: src: the sequence to the encoder layer (required). src_: the sequence to the encoder layer (required). src_mask: the mask for the src sequence (optional). src_key_padding_mask: the mask for the src keys per batch (optional). Shape: see the docs in Transformer class. """ src2 = self.self_attn(src, src_, src_, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0] src = src + self.dropout1(src2) src = self.norm1(src) src2 = self.linear2(self.dropout(self.activation(self.linear1(src)))) src = src + self.dropout2(src2) src = self.norm2(src) return src def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'d_model': 4, 'nhead': 4}]
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, math as tl_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_mul_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 1.0 tmp4 = tmp2 * tmp3 tl.store(in_out_ptr0 + x2, tmp4, xmask) @triton.jit def triton_poi_fused__softmax_1(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 x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp0 - tmp7 tmp9 = tl_math.exp(tmp8) tl.store(out_ptr0 + x2, tmp9, xmask) @triton.jit def triton_poi_fused__softmax_2(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 x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) @triton.jit def triton_poi_fused_clone_3(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 4 xnumel = 4 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x1 = xindex y0 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask) tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_add_native_layer_norm_4(in_ptr0, in_ptr1, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 4 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp12 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp2 = tmp0 + tmp1 tmp5 = tmp3 + tmp4 tmp6 = tmp2 + tmp5 tmp9 = tmp7 + tmp8 tmp10 = tmp6 + tmp9 tmp13 = tmp11 + tmp12 tmp14 = tmp10 + tmp13 tmp15 = 4.0 tmp16 = tmp14 / tmp15 tmp17 = tmp2 - tmp16 tmp18 = tmp17 * tmp17 tmp19 = tmp5 - tmp16 tmp20 = tmp19 * tmp19 tmp21 = tmp18 + tmp20 tmp22 = tmp9 - tmp16 tmp23 = tmp22 * tmp22 tmp24 = tmp21 + tmp23 tmp25 = tmp13 - tmp16 tmp26 = tmp25 * tmp25 tmp27 = tmp24 + tmp26 tmp28 = tmp27 / tmp15 tl.store(out_ptr0 + x0, tmp16, xmask) tl.store(out_ptr1 + x0, tmp28, xmask) @triton.jit def triton_poi_fused_add_native_layer_norm_5(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, 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 x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x2, xmask) tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last') tmp10 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last') tmp12 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp4 = tmp2 - tmp3 tmp6 = 1e-05 tmp7 = tmp5 + tmp6 tmp8 = libdevice.rsqrt(tmp7) tmp9 = tmp4 * tmp8 tmp11 = tmp9 * tmp10 tmp13 = tmp11 + tmp12 tl.store(out_ptr0 + x2, tmp13, xmask) @triton.jit def triton_poi_fused_relu_6(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 % 2048 tmp0 = tl.load(in_out_ptr0 + x2, None) tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, None) @triton.jit def triton_poi_fused_add_7(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_out_ptr0 + x2, xmask) tmp2 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp4 = tmp0 + tmp3 tl.store(in_out_ptr0 + x2, tmp4, xmask) @triton.jit def triton_poi_fused_native_layer_norm_8(in_ptr0, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 4 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp6 = tmp4 + tmp5 tmp7 = 4.0 tmp8 = tmp6 / tmp7 tmp9 = tmp0 - tmp8 tmp10 = tmp9 * tmp9 tmp11 = tmp1 - tmp8 tmp12 = tmp11 * tmp11 tmp13 = tmp10 + tmp12 tmp14 = tmp3 - tmp8 tmp15 = tmp14 * tmp14 tmp16 = tmp13 + tmp15 tmp17 = tmp5 - tmp8 tmp18 = tmp17 * tmp17 tmp19 = tmp16 + tmp18 tmp20 = tmp19 / tmp7 tmp21 = 1e-05 tmp22 = tmp20 + tmp21 tmp23 = libdevice.rsqrt(tmp22) tl.store(out_ptr0 + x0, tmp8, xmask) tl.store(out_ptr1 + x0, tmp23, xmask) @triton.jit def triton_poi_fused_native_layer_norm_9(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, 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 x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 - tmp1 tmp4 = tmp2 * tmp3 tmp6 = tmp4 * tmp5 tmp8 = tmp6 + tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13, primals_14) = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4, 4), (4, 1)) assert_size_stride(primals_3, (12, 4), (4, 1)) assert_size_stride(primals_4, (12,), (1,)) assert_size_stride(primals_5, (4, 4), (4, 1)) assert_size_stride(primals_6, (4,), (1,)) assert_size_stride(primals_7, (4,), (1,)) assert_size_stride(primals_8, (4,), (1,)) assert_size_stride(primals_9, (2048, 4), (4, 1)) assert_size_stride(primals_10, (2048,), (1,)) assert_size_stride(primals_11, (4, 2048), (2048, 1)) assert_size_stride(primals_12, (4,), (1,)) assert_size_stride(primals_13, (4,), (1,)) assert_size_stride(primals_14, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(primals_1, reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf0) buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(reinterpret_tensor(primals_4, (4,), (1,), 4), primals_2, reinterpret_tensor(primals_3, (4, 4), (1, 4), 16), alpha=1, beta=1, out=buf1) buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(reinterpret_tensor(primals_4, (4,), (1,), 8), primals_2, reinterpret_tensor(primals_3, (4, 4), (1, 4), 32), alpha=1, beta=1, out=buf2) del primals_3 buf3 = reinterpret_tensor(buf0, (4, 4, 1), (1, 4, 16), 0) del buf0 get_raw_stream(0) triton_poi_fused_mul_0[grid(16)](buf3, primals_4, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_4 buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(buf3, reinterpret_tensor(buf1, (4, 1, 4), (1, 1, 4), 0), out=buf4) buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused__softmax_1[grid(64)](buf4, buf5, 64, XBLOCK=64, num_warps=1, num_stages=1) buf6 = buf4 del buf4 triton_poi_fused__softmax_2[grid(64)](buf5, buf6, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf5 buf7 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32) extern_kernels.bmm(buf6, reinterpret_tensor(buf2, (4, 4, 1), (1, 4, 1), 0), out=buf7) buf8 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32) triton_poi_fused_clone_3[grid(4, 4)](buf7, buf8, 4, 4, XBLOCK=4, YBLOCK=4, num_warps=1, num_stages=1) buf9 = reinterpret_tensor(buf7, (4, 4), (4, 1), 0) del buf7 extern_kernels.addmm(primals_6, reinterpret_tensor(buf8, (4, 4), (4, 1), 0), reinterpret_tensor(primals_5, (4, 4), (1, 4), 0), alpha =1, beta=1, out=buf9) del primals_6 buf10 = empty_strided_cuda((4, 1), (1, 4), torch.float32) buf11 = empty_strided_cuda((4, 1), (1, 4), torch.float32) triton_poi_fused_add_native_layer_norm_4[grid(4)](primals_1, buf9, buf10, buf11, 4, XBLOCK=4, num_warps=1, num_stages=1) buf12 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_add_native_layer_norm_5[grid(16)](primals_1, buf9, buf10, buf11, primals_7, primals_8, buf12, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_8 buf13 = empty_strided_cuda((4, 2048), (2048, 1), torch.float32) extern_kernels.mm(buf12, reinterpret_tensor(primals_9, (4, 2048), ( 1, 4), 0), out=buf13) buf14 = buf13 del buf13 triton_poi_fused_relu_6[grid(8192)](buf14, primals_10, 8192, XBLOCK =256, num_warps=4, num_stages=1) del primals_10 buf15 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf14, reinterpret_tensor(primals_11, (2048, 4), (1, 2048), 0), out=buf15) buf16 = buf15 del buf15 triton_poi_fused_add_7[grid(16)](buf16, buf12, primals_12, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_12 buf17 = buf11 del buf11 buf18 = buf10 del buf10 triton_poi_fused_native_layer_norm_8[grid(4)](buf16, buf17, buf18, 4, XBLOCK=4, num_warps=1, num_stages=1) buf19 = empty_strided_cuda((4, 4), (4, 1), torch.float32) triton_poi_fused_native_layer_norm_9[grid(16)](buf16, buf17, buf18, primals_13, primals_14, buf19, 16, XBLOCK=16, num_warps=1, num_stages=1) del buf17 del buf18 del primals_14 return (buf19, primals_1, primals_7, primals_13, primals_2, buf6, reinterpret_tensor(buf8, (4, 4), (4, 1), 0), buf9, buf12, buf14, buf16, primals_11, primals_9, primals_5, reinterpret_tensor(buf2, ( 4, 1, 4), (1, 1, 4), 0), reinterpret_tensor(buf3, (4, 1, 4), (1, 1, 4), 0), reinterpret_tensor(buf1, (4, 4, 1), (1, 4, 1), 0)) def _get_activation_fn(activation): if activation == 'relu': return F.relu elif activation == 'gelu': return F.gelu raise ValueError('activation should be relu/gelu, not {}'.format( activation)) class CoAttentionTransformerEncoderLayerNew(nn.Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation='relu'): super(CoAttentionTransformerEncoderLayerNew, self).__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) self.linear1 = nn.Linear(d_model, dim_feedforward) self.dropout = nn.Dropout(dropout) self.linear2 = nn.Linear(dim_feedforward, d_model) self.norm1 = nn.LayerNorm(d_model) self.norm2 = nn.LayerNorm(d_model) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.activation = _get_activation_fn(activation) def __setstate__(self, state): if 'activation' not in state: state['activation'] = F.relu super(CoAttentionTransformerEncoderLayerNew, self).__setstate__(state) def forward(self, input_0, input_1): primals_3 = self.self_attn.in_proj_weight primals_4 = self.self_attn.in_proj_bias primals_1 = self.self_attn.out_proj.weight primals_6 = self.self_attn.out_proj.bias primals_9 = self.linear1.weight primals_10 = self.linear1.bias primals_11 = self.linear2.weight primals_7 = self.linear2.bias primals_8 = self.norm1.weight primals_12 = self.norm1.bias primals_13 = self.norm2.weight primals_14 = self.norm2.bias primals_2 = input_0 primals_5 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13, primals_14]) return output[0]
doiken23/mccformers.pytorch
CoAttentionTransformerEncoderLayer
false
6,615
[ "MIT" ]
1
678bd9448e3a2f35bd408e8c8e510e0ea1f9a19f
https://github.com/doiken23/mccformers.pytorch/tree/678bd9448e3a2f35bd408e8c8e510e0ea1f9a19f
Adversarial_Loss
import torch import torch.nn as nn from numpy import * class Adversarial_Loss(nn.Module): def __init__(self, lambda_adv): super(Adversarial_Loss, self).__init__() self.lambda_adv = lambda_adv pass def forward(self, input_p, input_h): dis_p = input_p * torch.log(input_p) dis_h = torch.log(torch.ones_like(input_h) - input_h) adv_loss = dis_h + dis_p return torch.sum(self.lambda_adv * adv_loss) def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'lambda_adv': 4}]
import torch 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 torch.nn as nn from numpy import * assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_add_log_mul_ones_like_sub_sum_0(in_ptr0, in_ptr1, out_ptr0, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp4 = tl.load(in_ptr1 + r0, None) tmp1 = 1.0 tmp2 = tmp1 - tmp0 tmp3 = tl_math.log(tmp2) tmp5 = tl_math.log(tmp4) tmp6 = tmp4 * tmp5 tmp7 = tmp3 + tmp6 tmp8 = 4.0 tmp9 = tmp7 * tmp8 tmp10 = tl.broadcast_to(tmp9, [RBLOCK]) tmp12 = triton_helpers.promote_to_tensor(tl.sum(tmp10, 0)) tl.store(out_ptr0 + tl.full([1], 0, tl.int32), tmp12, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) get_raw_stream(0) triton_per_fused_add_log_mul_ones_like_sub_sum_0[grid(1)](arg1_1, arg0_1, buf0, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 return buf0, class Adversarial_LossNew(nn.Module): def __init__(self, lambda_adv): super(Adversarial_LossNew, self).__init__() self.lambda_adv = lambda_adv pass def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
ducviet00/HMER
Adversarial_Loss
false
6,616
[ "MIT" ]
1
0fa322ed35412737a24ec3955c9a3d96d1989bd4
https://github.com/ducviet00/HMER/tree/0fa322ed35412737a24ec3955c9a3d96d1989bd4
MixedPad
import torch def mixed_pad(input, pad, mode='constant', value=0, reversed_axes=False): """Mixed mode padding. :type input: tensor[B,C,D1,D2,...,DD] :type pad: int or tuple of ints with 2*D length :type mode: str or tuple :type value: float or tuple Dimension numbering: reverse order means [B,C,Dn,...,D2,D1], while regular order means [B,C,D1,D2,...Dn]. If the mode is a string, everything falls back to classic padding. If the mode is a tuple, for each dimension the given padding is used. The input tensor must have D+2 dimensions (batch, channel, D1,D2,...) The padding must be integer or (left, right) padding for each dimension. If the padding value is not a single float, it must be a sequence with length of D always. E.g. the value '1' isn't used but required: mixed_pad(t, pad=(1,1,2,2,1,1), mode=('circular','constant', 'constant'), value = (1,2,3)) """ D = input.ndim - 2 if not isinstance(pad, tuple): pad = (pad, pad) * D if not isinstance(mode, tuple): return torch.nn.functional.pad(input, pad, mode=mode, value=value) if not reversed_axes: pad = pad[::-1] mode = mode[::-1] assert len(mode) == D if not isinstance(value, tuple): value = (value,) * D zero = (0, 0) * D result = input for i in range(D): pre = zero[0:2 * i] mid = pad[2 * i:2 * i + 2] post = zero[2 * i + 2:] sequence = pre + mid + post if mode[i] == 'constant': result = torch.nn.functional.pad(result, sequence, mode= 'constant', value=value[i]) else: result = torch.nn.functional.pad(result, sequence, mode=mode[i]) return result class MixedPad(torch.nn.Module): def __init__(self, pad, mode='constant', value=0, reversed_axes=False): super().__init__() self.pad = pad self.mode = mode self.value = value self.reversed_axes = reversed_axes def forward(self, x): return mixed_pad(x, self.pad, self.mode, self.value, self.reversed_axes ) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'pad': 4}]
import torch 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 assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_constant_pad_nd_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 2304 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 12 % 12 x0 = xindex % 12 x2 = xindex // 144 x4 = xindex tmp0 = -4 + x1 tmp1 = tl.full([1], 0, tl.int64) tmp2 = tmp0 >= tmp1 tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = -4 + x0 tmp6 = tmp5 >= tmp1 tmp7 = tmp5 < tmp3 tmp8 = tmp2 & tmp4 tmp9 = tmp8 & tmp6 tmp10 = tmp9 & tmp7 tmp11 = tl.load(in_ptr0 + (-20 + x0 + 4 * x1 + 16 * x2), tmp10 & xmask, other=0.0) tl.store(out_ptr0 + x4, tmp11, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 12, 12), (576, 144, 12, 1), torch. float32) get_raw_stream(0) triton_poi_fused_constant_pad_nd_0[grid(2304)](arg0_1, buf0, 2304, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 return buf0, def mixed_pad(input, pad, mode='constant', value=0, reversed_axes=False): """Mixed mode padding. :type input: tensor[B,C,D1,D2,...,DD] :type pad: int or tuple of ints with 2*D length :type mode: str or tuple :type value: float or tuple Dimension numbering: reverse order means [B,C,Dn,...,D2,D1], while regular order means [B,C,D1,D2,...Dn]. If the mode is a string, everything falls back to classic padding. If the mode is a tuple, for each dimension the given padding is used. The input tensor must have D+2 dimensions (batch, channel, D1,D2,...) The padding must be integer or (left, right) padding for each dimension. If the padding value is not a single float, it must be a sequence with length of D always. E.g. the value '1' isn't used but required: mixed_pad(t, pad=(1,1,2,2,1,1), mode=('circular','constant', 'constant'), value = (1,2,3)) """ D = input.ndim - 2 if not isinstance(pad, tuple): pad = (pad, pad) * D if not isinstance(mode, tuple): return torch.nn.functional.pad(input, pad, mode=mode, value=value) if not reversed_axes: pad = pad[::-1] mode = mode[::-1] assert len(mode) == D if not isinstance(value, tuple): value = (value,) * D zero = (0, 0) * D result = input for i in range(D): pre = zero[0:2 * i] mid = pad[2 * i:2 * i + 2] post = zero[2 * i + 2:] sequence = pre + mid + post if mode[i] == 'constant': result = torch.nn.functional.pad(result, sequence, mode= 'constant', value=value[i]) else: result = torch.nn.functional.pad(result, sequence, mode=mode[i]) return result class MixedPadNew(torch.nn.Module): def __init__(self, pad, mode='constant', value=0, reversed_axes=False): super().__init__() self.pad = pad self.mode = mode self.value = value self.reversed_axes = reversed_axes def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
dvolgyes/highresnet
MixedPad
false
6,617
[ "MIT" ]
1
12b8831ed52e2dc45d2e14cc6f2954c583c97a46
https://github.com/dvolgyes/highresnet/tree/12b8831ed52e2dc45d2e14cc6f2954c583c97a46
NetworkDQN
import torch import torch.nn as nn import torch.nn.functional as F class NetworkDQN(nn.Module): def __init__(self, fs, input_dim, fc1, fc2, n_actions): super(NetworkDQN, self).__init__() self.conv1 = nn.Conv2d(fs, 64, 8, 4) self.pool1 = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(64, 64, 4, 2) self.conv3 = nn.Conv2d(64, 48, 3, 1) self.lin1 = nn.Linear(256 * 3 + 2, fc1) self.lin2 = nn.Linear(fc1 + 2, fc2) self.actl = nn.Linear(fc2 + 2, n_actions) def forward(self, observation): jr = observation[:, 0, 0:2, 0] observation = (observation - 127) / 255 x = F.relu(self.conv1(observation)) x = self.pool1(x) x = self.conv2(x) x = F.relu(self.conv3(x)) x = torch.flatten(x, 1) x = torch.cat([x, jr], dim=1) x = F.relu(self.lin1(x)) x = torch.cat([x, jr], dim=1) x = F.relu(self.lin2(x)) x = torch.cat([x, jr], dim=1) action_val = self.actl(x) return action_val def get_inputs(): return [torch.rand([4, 4, 128, 128])] def get_init_inputs(): return [[], {'fs': 4, 'input_dim': 4, 'fc1': 4, 'fc2': 4, 'n_actions': 4}]
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 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_poi_fused_div_sub_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x0 = xindex tmp0 = tl.load(in_ptr0 + x0, None) tmp1 = 127.0 tmp2 = tmp0 - tmp1 tmp3 = 0.00392156862745098 tmp4 = tmp2 * tmp3 tl.store(out_ptr0 + x0, tmp4, None) @triton.jit def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 246016 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 961 % 64 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) tl.store(in_out_ptr0 + x3, tmp4, xmask) @triton.jit def triton_poi_fused_max_pool2d_with_indices_2(in_ptr0, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 57600 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 15 x1 = xindex // 15 % 15 x2 = xindex // 225 x5 = xindex x4 = xindex // 14400 x6 = xindex % 14400 tmp0 = tl.load(in_ptr0 + (2 * x0 + 62 * x1 + 961 * x2), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 62 * x1 + 961 * x2), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (31 + 2 * x0 + 62 * x1 + 961 * x2), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (32 + 2 * x0 + 62 * x1 + 961 * x2), xmask, eviction_policy='evict_last') tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp6 = triton_helpers.maximum(tmp5, tmp4) tmp7 = tmp1 > tmp0 tmp8 = tl.full([1], 1, tl.int8) tmp9 = tl.full([1], 0, tl.int8) tmp10 = tl.where(tmp7, tmp8, tmp9) tmp11 = tmp3 > tmp2 tmp12 = tl.full([1], 2, tl.int8) tmp13 = tl.where(tmp11, tmp12, tmp10) tmp14 = tmp5 > tmp4 tmp15 = tl.full([1], 3, tl.int8) tmp16 = tl.where(tmp14, tmp15, tmp13) tl.store(out_ptr0 + x5, tmp6, xmask) tl.store(out_ptr1 + (x6 + 14464 * x4), tmp16, xmask) @triton.jit def triton_poi_fused_convolution_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 9216 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 36 % 64 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) @triton.jit def triton_poi_fused_cat_4(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 3080 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 770 x1 = xindex // 770 x2 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 768, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (768 * x1 + x0 % 768), tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp6 = tl.load(in_ptr1 + x0 // 16 % 48, tmp4 & xmask, eviction_policy= 'evict_last', other=0.0) tmp7 = tmp5 + tmp6 tmp8 = tl.full([1], 0, tl.int32) tmp9 = triton_helpers.maximum(tmp8, tmp7) tmp10 = tl.full(tmp9.shape, 0.0, tmp9.dtype) tmp11 = tl.where(tmp4, tmp9, tmp10) tmp12 = tmp0 >= tmp3 tl.full([1], 770, tl.int64) tmp15 = tl.load(in_ptr2 + (128 * (-768 + x0) + 65536 * x1), tmp12 & xmask, eviction_policy='evict_last', other=0.0) tmp16 = tl.where(tmp4, tmp11, tmp15) tl.store(out_ptr0 + x2, tmp16, xmask) @triton.jit def triton_poi_fused_cat_5(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 24 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 6 x1 = xindex // 6 x2 = xindex tmp0 = x0 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (4 * x1 + x0), tmp4 & xmask, eviction_policy= 'evict_last', other=0.0) tmp6 = tl.load(in_ptr1 + x0, tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp7 = tmp5 + tmp6 tmp8 = tl.full([1], 0, tl.int32) tmp9 = triton_helpers.maximum(tmp8, tmp7) tmp10 = tl.full(tmp9.shape, 0.0, tmp9.dtype) tmp11 = tl.where(tmp4, tmp9, tmp10) tmp12 = tmp0 >= tmp3 tl.full([1], 6, tl.int64) tmp15 = tl.load(in_ptr2 + (128 * (-4 + x0) + 65536 * x1), tmp12 & xmask, eviction_policy='evict_last', other=0.0) tmp16 = tl.where(tmp4, tmp11, tmp15) tl.store(out_ptr0 + x2, tmp16, xmask) @triton.jit def triton_poi_fused_relu_threshold_backward_6(in_ptr0, in_ptr1, 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 x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x0, 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(out_ptr0 + x2, tmp6, xmask) @triton.jit def triton_poi_fused_convolution_relu_threshold_backward_7(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 3072 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 16 % 48 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr1 + 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(out_ptr0 + x3, tmp6, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13) = args args.clear() assert_size_stride(primals_1, (4, 4, 128, 128), (65536, 16384, 128, 1)) assert_size_stride(primals_2, (64, 4, 8, 8), (256, 64, 8, 1)) assert_size_stride(primals_3, (64,), (1,)) assert_size_stride(primals_4, (64, 64, 4, 4), (1024, 16, 4, 1)) assert_size_stride(primals_5, (64,), (1,)) assert_size_stride(primals_6, (48, 64, 3, 3), (576, 9, 3, 1)) assert_size_stride(primals_7, (48,), (1,)) assert_size_stride(primals_8, (4, 770), (770, 1)) assert_size_stride(primals_9, (4,), (1,)) assert_size_stride(primals_10, (4, 6), (6, 1)) assert_size_stride(primals_11, (4,), (1,)) assert_size_stride(primals_12, (4, 6), (6, 1)) assert_size_stride(primals_13, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 128, 128), (65536, 16384, 128, 1), torch.float32) get_raw_stream(0) triton_poi_fused_div_sub_0[grid(262144)](primals_1, buf0, 262144, XBLOCK=512, num_warps=8, num_stages=1) buf1 = extern_kernels.convolution(buf0, primals_2, stride=(4, 4), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf1, (4, 64, 31, 31), (61504, 961, 31, 1)) buf2 = buf1 del buf1 triton_poi_fused_convolution_relu_1[grid(246016)](buf2, primals_3, 246016, XBLOCK=512, num_warps=8, num_stages=1) del primals_3 buf3 = empty_strided_cuda((4, 64, 15, 15), (14400, 225, 15, 1), torch.float32) buf4 = empty_strided_cuda((4, 64, 15, 15), (14464, 225, 15, 1), torch.int8) triton_poi_fused_max_pool2d_with_indices_2[grid(57600)](buf2, buf3, buf4, 57600, XBLOCK=256, num_warps=4, num_stages=1) buf5 = extern_kernels.convolution(buf3, primals_4, stride=(2, 2), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf5, (4, 64, 6, 6), (2304, 36, 6, 1)) buf6 = buf5 del buf5 triton_poi_fused_convolution_3[grid(9216)](buf6, primals_5, 9216, XBLOCK=256, num_warps=4, num_stages=1) del primals_5 buf7 = extern_kernels.convolution(buf6, primals_6, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf7, (4, 48, 4, 4), (768, 16, 4, 1)) buf8 = empty_strided_cuda((4, 770), (770, 1), torch.float32) triton_poi_fused_cat_4[grid(3080)](buf7, primals_7, primals_1, buf8, 3080, XBLOCK=128, num_warps=4, num_stages=1) buf9 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf8, reinterpret_tensor(primals_8, (770, 4), (1, 770), 0), out=buf9) buf10 = empty_strided_cuda((4, 6), (6, 1), torch.float32) triton_poi_fused_cat_5[grid(24)](buf9, primals_9, primals_1, buf10, 24, XBLOCK=32, num_warps=1, num_stages=1) buf11 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(buf10, reinterpret_tensor(primals_10, (6, 4), (1, 6), 0), out=buf11) buf12 = empty_strided_cuda((4, 6), (6, 1), torch.float32) triton_poi_fused_cat_5[grid(24)](buf11, primals_11, primals_1, buf12, 24, XBLOCK=32, num_warps=1, num_stages=1) del primals_1 buf13 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_13, buf12, reinterpret_tensor( primals_12, (6, 4), (1, 6), 0), alpha=1, beta=1, out=buf13) del primals_13 buf14 = empty_strided_cuda((4, 4), (4, 1), torch.bool) triton_poi_fused_relu_threshold_backward_6[grid(16)](buf11, primals_11, buf14, 16, XBLOCK=16, num_warps=1, num_stages=1) del buf11 del primals_11 buf15 = empty_strided_cuda((4, 4), (4, 1), torch.bool) triton_poi_fused_relu_threshold_backward_6[grid(16)](buf9, primals_9, buf15, 16, XBLOCK=16, num_warps=1, num_stages=1) del buf9 del primals_9 buf16 = empty_strided_cuda((4, 48, 4, 4), (768, 16, 4, 1), torch.bool) triton_poi_fused_convolution_relu_threshold_backward_7[grid(3072)](buf7 , primals_7, buf16, 3072, XBLOCK=256, num_warps=4, num_stages=1) del buf7 del primals_7 return (buf13, primals_2, primals_4, primals_6, buf0, buf2, buf3, buf4, buf6, buf8, buf10, buf12, primals_12, buf14, primals_10, buf15, primals_8, buf16) class NetworkDQNNew(nn.Module): def __init__(self, fs, input_dim, fc1, fc2, n_actions): super(NetworkDQNNew, self).__init__() self.conv1 = nn.Conv2d(fs, 64, 8, 4) self.pool1 = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(64, 64, 4, 2) self.conv3 = nn.Conv2d(64, 48, 3, 1) self.lin1 = nn.Linear(256 * 3 + 2, fc1) self.lin2 = nn.Linear(fc1 + 2, fc2) self.actl = nn.Linear(fc2 + 2, n_actions) def forward(self, input_0): primals_2 = self.conv1.weight primals_3 = self.conv1.bias primals_4 = self.conv2.weight primals_5 = self.conv2.bias primals_6 = self.conv3.weight primals_7 = self.conv3.bias primals_8 = self.lin1.weight primals_9 = self.lin1.bias primals_10 = self.lin2.weight primals_11 = self.lin2.bias primals_12 = self.actl.weight primals_13 = self.actl.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13]) return output[0]
doganjr/MarioDQN
NetworkDQN
false
6,618
[ "MIT" ]
1
62daa390f8ee0b732275e71675a2b9eae85c43a4
https://github.com/doganjr/MarioDQN/tree/62daa390f8ee0b732275e71675a2b9eae85c43a4
Loss_D
import torch import torch.nn as nn from numpy import * class Loss_D(nn.Module): """docstring for Loss_D""" def __init__(self): super(Loss_D, self).__init__() def forward(self, input_h): return -input_h * torch.log(input_h) pass def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 from numpy import * assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_log_mul_neg_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = -tmp0 tmp2 = tl_math.log(tmp0) tmp3 = tmp1 * tmp2 tl.store(out_ptr0 + x0, tmp3, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_log_mul_neg_0[grid(256)](arg0_1, buf0, 256, XBLOCK =128, num_warps=4, num_stages=1) del arg0_1 return buf0, class Loss_DNew(nn.Module): """docstring for Loss_D""" def __init__(self): super(Loss_DNew, self).__init__() def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
ducviet00/HMER
Loss_D
false
6,619
[ "MIT" ]
1
0fa322ed35412737a24ec3955c9a3d96d1989bd4
https://github.com/ducviet00/HMER/tree/0fa322ed35412737a24ec3955c9a3d96d1989bd4
Invertible1x1Conv
import torch import torch.nn.functional as F from torch.autograd import Variable import torch.utils.data import torch.nn class Invertible1x1Conv(torch.nn.Module): """ The layer outputs both the convolution, and the log determinant of its weight matrix. If reverse=True it does convolution with inverse """ def __init__(self, c): super(Invertible1x1Conv, self).__init__() self.conv = torch.nn.Conv1d(c, c, kernel_size=1, stride=1, padding= 0, bias=False) W = torch.qr(torch.FloatTensor(c, c).normal_())[0] if torch.det(W) < 0: W[:, 0] = -1 * W[:, 0] W = W.view(c, c, 1) self.conv.weight.data = W def forward(self, z): batch_size, _group_size, n_of_groups = z.size() W = self.conv.weight.squeeze() log_det_W = batch_size * n_of_groups * torch.logdet(W.unsqueeze(0). float()).squeeze() z = self.conv(z) return z, log_det_W def infer(self, z): _batch_size, _group_size, _n_of_groups = z.size() W = self.conv.weight.squeeze() if not hasattr(self, 'W_inverse'): W_inverse = W.float().inverse() W_inverse = Variable(W_inverse[..., None]) if z.type() == 'torch.cuda.HalfTensor' or z.type( ) == 'torch.HalfTensor': W_inverse = W_inverse.half() self.W_inverse = W_inverse z = F.conv1d(z, self.W_inverse, bias=None, stride=1, padding=0) return z def get_inputs(): return [torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'c': 4}]
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 import torch.nn.functional as F from torch.autograd import Variable import torch.utils.data import torch.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_poi_fused_eq_mul_0(in_out_ptr0, in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) tmp0 = tl.load(in_ptr0 + 0) tmp1 = tl.broadcast_to(tmp0, [XBLOCK]) tmp4 = tl.load(in_out_ptr0 + 0) tmp5 = tl.broadcast_to(tmp4, [XBLOCK]) tmp2 = -1.0 tmp3 = tmp1 == tmp2 tmp6 = float('nan') tmp7 = tl.where(tmp3, tmp6, tmp5) tmp8 = 16.0 tmp9 = tmp7 * tmp8 tl.store(out_ptr0 + tl.full([XBLOCK], 0, tl.int32), tmp3, None) tl.store(in_out_ptr0 + tl.full([XBLOCK], 0, tl.int32), tmp9, None) @triton.jit def triton_poi_fused_convolution_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): ynumel = 4 xnumel = 4 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x1 = xindex y0 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask) tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask) def call(args): primals_1, primals_2 = args args.clear() assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_2, (4, 4, 1), (1, 4, 4)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = torch.ops.aten._linalg_slogdet.default(reinterpret_tensor( primals_2, (1, 4, 4), (0, 1, 4), 0)) buf1 = buf0[0] buf2 = buf0[1] buf3 = buf0[2] buf4 = buf0[3] del buf0 buf5 = empty_strided_cuda((1,), (1,), torch.bool) buf8 = reinterpret_tensor(buf2, (), (), 0) del buf2 get_raw_stream(0) triton_poi_fused_eq_mul_0[grid(1)](buf8, buf1, buf5, 1, XBLOCK=1, num_warps=1, num_stages=1) del buf1 buf6 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32) triton_poi_fused_convolution_1[grid(4, 4)](primals_2, buf6, 4, 4, XBLOCK=4, YBLOCK=4, num_warps=1, num_stages=1) buf7 = extern_kernels.convolution(primals_1, buf6, stride=(1,), padding=(0,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf7, (4, 4, 4), (16, 4, 1)) del buf6 return buf7, buf8, primals_1, primals_2, buf3, buf4, buf5 class Invertible1x1ConvNew(torch.nn.Module): """ The layer outputs both the convolution, and the log determinant of its weight matrix. If reverse=True it does convolution with inverse """ def __init__(self, c): super(Invertible1x1ConvNew, self).__init__() self.conv = torch.nn.Conv1d(c, c, kernel_size=1, stride=1, padding= 0, bias=False) W = torch.qr(torch.FloatTensor(c, c).normal_())[0] if torch.det(W) < 0: W[:, 0] = -1 * W[:, 0] W = W.view(c, c, 1) self.conv.weight.data = W def infer(self, z): _batch_size, _group_size, _n_of_groups = z.size() W = self.conv.weight.squeeze() if not hasattr(self, 'W_inverse'): W_inverse = W.float().inverse() W_inverse = Variable(W_inverse[..., None]) if z.type() == 'torch.cuda.HalfTensor' or z.type( ) == 'torch.HalfTensor': W_inverse = W_inverse.half() self.W_inverse = W_inverse z = F.conv1d(z, self.W_inverse, bias=None, stride=1, padding=0) return z def forward(self, input_0): primals_2 = self.conv.weight primals_1 = input_0 output = call([primals_1, primals_2]) return output[0], output[1]
drostifrosti/TensorRT
Invertible1x1Conv
false
6,620
[ "Apache-2.0" ]
1
76d673366139538fcb47a67e08734ff429306162
https://github.com/drostifrosti/TensorRT/tree/76d673366139538fcb47a67e08734ff429306162
InterpolationBlock
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.data class InterpolationBlock(nn.Module): """ Interpolation block. Parameters: ---------- scale_factor : float Multiplier for spatial size. """ def __init__(self, scale_factor): super(InterpolationBlock, self).__init__() self.scale_factor = scale_factor def forward(self, x): return F.interpolate(input=x, scale_factor=self.scale_factor, mode= 'bilinear', align_corners=True) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'scale_factor': 1.0}]
import torch 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 torch.nn as nn import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused__to_copy__unsafe_index_add_arange_clamp_mul_sub_0( in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 4 % 4 x0 = xindex % 4 x2 = xindex // 16 x4 = xindex tmp0 = x1 tmp1 = tmp0.to(tl.float32) tmp2 = 1.0 tmp3 = tmp1 * tmp2 tmp4 = 0.0 tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp6 = tmp5.to(tl.int32) tmp7 = tl.full([1], 1, tl.int64) tmp8 = tmp6 + tmp7 tmp9 = tl.full([1], 3, tl.int64) tmp10 = triton_helpers.minimum(tmp8, tmp9) tmp11 = x0 tmp12 = tmp11.to(tl.float32) tmp13 = tmp12 * tmp2 tmp14 = triton_helpers.maximum(tmp13, tmp4) tmp15 = tmp14.to(tl.int32) tmp16 = tl.load(in_ptr0 + (tmp15 + 4 * tmp10 + 16 * x2), xmask, eviction_policy='evict_last') tmp17 = tmp15 + tmp7 tmp18 = triton_helpers.minimum(tmp17, tmp9) tmp19 = tl.load(in_ptr0 + (tmp18 + 4 * tmp10 + 16 * x2), xmask, eviction_policy='evict_last') tmp20 = tmp19 - tmp16 tmp21 = tmp15.to(tl.float32) tmp22 = tmp14 - tmp21 tmp23 = triton_helpers.maximum(tmp22, tmp4) tmp24 = triton_helpers.minimum(tmp23, tmp2) tmp25 = tmp20 * tmp24 tmp26 = tmp16 + tmp25 tmp27 = tl.load(in_ptr0 + (tmp15 + 4 * tmp6 + 16 * x2), xmask, eviction_policy='evict_last') tmp28 = tl.load(in_ptr0 + (tmp18 + 4 * tmp6 + 16 * x2), xmask, eviction_policy='evict_last') tmp29 = tmp28 - tmp27 tmp30 = tmp29 * tmp24 tmp31 = tmp27 + tmp30 tmp32 = tmp26 - tmp31 tmp33 = tmp6.to(tl.float32) tmp34 = tmp5 - tmp33 tmp35 = triton_helpers.maximum(tmp34, tmp4) tmp36 = triton_helpers.minimum(tmp35, tmp2) tmp37 = tmp32 * tmp36 tmp38 = tmp31 + tmp37 tl.store(in_out_ptr0 + x4, tmp38, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused__to_copy__unsafe_index_add_arange_clamp_mul_sub_0[grid (256)](buf1, arg0_1, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 return buf1, class InterpolationBlockNew(nn.Module): """ Interpolation block. Parameters: ---------- scale_factor : float Multiplier for spatial size. """ def __init__(self, scale_factor): super(InterpolationBlockNew, self).__init__() self.scale_factor = scale_factor def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
earhian/imgclsmob
InterpolationBlock
false
6,621
[ "MIT" ]
1
c87c0942420876941868c016211073dec4392e4d
https://github.com/earhian/imgclsmob/tree/c87c0942420876941868c016211073dec4392e4d
DiracConv
import torch import torch.nn as nn import torch.utils.data class DiracConv(nn.Module): """ DiracNetV2 specific convolution block with pre-activation. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. kernel_size : int or tuple/list of 2 int Convolution window size. stride : int or tuple/list of 2 int Strides of the convolution. padding : int or tuple/list of 2 int Padding value for convolution layer. """ def __init__(self, in_channels, out_channels, kernel_size, stride, padding ): super(DiracConv, self).__init__() self.activ = nn.ReLU(inplace=True) self.conv = nn.Conv2d(in_channels=in_channels, out_channels= out_channels, kernel_size=kernel_size, stride=stride, padding= padding, bias=True) def forward(self, x): x = self.activ(x) x = self.conv(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4, 'stride': 1, 'padding': 4}]
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 torch.nn as nn import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_relu_0(in_ptr0, out_ptr0, out_ptr1, xnumel, XBLOCK: tl .constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = tl.full([1], 0, tl.int32) tmp2 = triton_helpers.maximum(tmp1, tmp0) tl.store(out_ptr0 + x0, tmp2, xmask) tl.store(out_ptr1 + x0, tmp2, 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 = 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,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_relu_0[grid(256)](primals_1, buf0, primals_1, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_1 buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1, 1), padding=(4, 4), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf1, (4, 4, 9, 9), (324, 81, 9, 1)) buf2 = buf1 del buf1 triton_poi_fused_convolution_1[grid(1296)](buf2, primals_3, 1296, XBLOCK=128, num_warps=4, num_stages=1) del primals_3 return buf2, primals_2, buf0 class DiracConvNew(nn.Module): """ DiracNetV2 specific convolution block with pre-activation. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. kernel_size : int or tuple/list of 2 int Convolution window size. stride : int or tuple/list of 2 int Strides of the convolution. padding : int or tuple/list of 2 int Padding value for convolution layer. """ def __init__(self, in_channels, out_channels, kernel_size, stride, padding ): super(DiracConvNew, self).__init__() self.activ = nn.ReLU(inplace=True) self.conv = nn.Conv2d(in_channels=in_channels, out_channels= out_channels, kernel_size=kernel_size, stride=stride, padding= padding, bias=True) def forward(self, input_0): primals_1 = self.conv.weight primals_3 = self.conv.bias primals_2 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
earhian/imgclsmob
DiracConv
false
6,622
[ "MIT" ]
1
c87c0942420876941868c016211073dec4392e4d
https://github.com/earhian/imgclsmob/tree/c87c0942420876941868c016211073dec4392e4d
MaxPoolBranch
import torch import torch.nn as nn import torch.utils.data class MaxPoolBranch(nn.Module): """ PolyNet specific max pooling branch block. """ def __init__(self): super(MaxPoolBranch, self).__init__() self.pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=0) def forward(self, x): x = self.pool(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 torch.nn as nn import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_max_pool2d_with_indices_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 x0 = xindex tmp0 = tl.load(in_ptr0 + 16 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp3 = tl.load(in_ptr0 + (2 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp5 = tl.load(in_ptr0 + (4 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp7 = tl.load(in_ptr0 + (5 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp9 = tl.load(in_ptr0 + (6 + 16 * x0), xmask, eviction_policy='evict_last' ) tmp11 = tl.load(in_ptr0 + (8 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp13 = tl.load(in_ptr0 + (9 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp15 = tl.load(in_ptr0 + (10 + 16 * x0), xmask, eviction_policy= 'evict_last') tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp6 = triton_helpers.maximum(tmp5, tmp4) tmp8 = triton_helpers.maximum(tmp7, tmp6) tmp10 = triton_helpers.maximum(tmp9, tmp8) tmp12 = triton_helpers.maximum(tmp11, tmp10) tmp14 = triton_helpers.maximum(tmp13, tmp12) tmp16 = triton_helpers.maximum(tmp15, tmp14) tl.store(out_ptr0 + x0, tmp16, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.float32) get_raw_stream(0) triton_poi_fused_max_pool2d_with_indices_0[grid(16)](arg0_1, buf0, 16, XBLOCK=16, num_warps=1, num_stages=1) del arg0_1 return buf0, class MaxPoolBranchNew(nn.Module): """ PolyNet specific max pooling branch block. """ def __init__(self): super(MaxPoolBranchNew, self).__init__() self.pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=0) def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
earhian/imgclsmob
MaxPoolBranch
false
6,623
[ "MIT" ]
1
c87c0942420876941868c016211073dec4392e4d
https://github.com/earhian/imgclsmob/tree/c87c0942420876941868c016211073dec4392e4d
DiracInitBlock
import torch import torch.nn as nn import torch.utils.data class DiracInitBlock(nn.Module): """ DiracNetV2 specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. """ def __init__(self, in_channels, out_channels): super(DiracInitBlock, self).__init__() self.conv = nn.Conv2d(in_channels=in_channels, out_channels= out_channels, kernel_size=7, stride=2, padding=3, bias=True) self.pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) def forward(self, x): x = self.conv(x) x = self.pool(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'out_channels': 4}]
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 torch.nn as nn import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_convolution_0(in_out_ptr0, in_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 tl.store(in_out_ptr0 + x3, tmp2, xmask) @triton.jit def triton_poi_fused_max_pool2d_with_indices_1(in_ptr0, out_ptr0, out_ptr1, 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.full([1], -1, tl.int64) tmp1 = tl.full([1], 0, tl.int64) tmp2 = tmp0 >= tmp1 tmp3 = tl.full([1], 2, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tmp2 & tmp4 tmp6 = tmp5 & tmp5 tmp7 = tl.load(in_ptr0 + (-3 + 4 * x0), tmp6 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp8 = tmp1 >= tmp1 tmp9 = tmp1 < tmp3 tmp10 = tmp8 & tmp9 tmp11 = tmp5 & tmp10 tmp12 = tl.load(in_ptr0 + (-2 + 4 * x0), tmp11 & xmask, eviction_policy ='evict_last', other=float('-inf')) tmp13 = triton_helpers.maximum(tmp12, tmp7) tmp14 = tl.full([1], 1, tl.int64) tmp15 = tmp14 >= tmp1 tmp16 = tmp14 < tmp3 tmp17 = tmp15 & tmp16 tmp18 = tmp5 & tmp17 tmp19 = tl.load(in_ptr0 + (-1 + 4 * x0), tmp18 & xmask, eviction_policy ='evict_last', other=float('-inf')) tmp20 = triton_helpers.maximum(tmp19, tmp13) tmp21 = tmp10 & tmp5 tmp22 = tl.load(in_ptr0 + (-1 + 4 * x0), tmp21 & xmask, eviction_policy ='evict_last', other=float('-inf')) tmp23 = triton_helpers.maximum(tmp22, tmp20) tmp24 = tmp10 & tmp10 tmp25 = tl.load(in_ptr0 + 4 * x0, tmp24 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp26 = triton_helpers.maximum(tmp25, tmp23) tmp27 = tmp10 & tmp17 tmp28 = tl.load(in_ptr0 + (1 + 4 * x0), tmp27 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp29 = triton_helpers.maximum(tmp28, tmp26) tmp30 = tmp17 & tmp5 tmp31 = tl.load(in_ptr0 + (1 + 4 * x0), tmp30 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp32 = triton_helpers.maximum(tmp31, tmp29) tmp33 = tmp17 & tmp10 tmp34 = tl.load(in_ptr0 + (2 + 4 * x0), tmp33 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp35 = triton_helpers.maximum(tmp34, tmp32) tmp36 = tmp17 & tmp17 tmp37 = tl.load(in_ptr0 + (3 + 4 * x0), tmp36 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp38 = triton_helpers.maximum(tmp37, tmp35) tmp39 = tmp12 > tmp7 tmp40 = tl.full([1], 1, tl.int8) tmp41 = tl.full([1], 0, tl.int8) tmp42 = tl.where(tmp39, tmp40, tmp41) tmp43 = tmp19 > tmp13 tmp44 = tl.full([1], 2, tl.int8) tmp45 = tl.where(tmp43, tmp44, tmp42) tmp46 = tmp22 > tmp20 tmp47 = tl.full([1], 3, tl.int8) tmp48 = tl.where(tmp46, tmp47, tmp45) tmp49 = tmp25 > tmp23 tmp50 = tl.full([1], 4, tl.int8) tmp51 = tl.where(tmp49, tmp50, tmp48) tmp52 = tmp28 > tmp26 tmp53 = tl.full([1], 5, tl.int8) tmp54 = tl.where(tmp52, tmp53, tmp51) tmp55 = tmp31 > tmp29 tmp56 = tl.full([1], 6, tl.int8) tmp57 = tl.where(tmp55, tmp56, tmp54) tmp58 = tmp34 > tmp32 tmp59 = tl.full([1], 7, tl.int8) tmp60 = tl.where(tmp58, tmp59, tmp57) tmp61 = tmp37 > tmp35 tmp62 = tl.full([1], 8, tl.int8) tmp63 = tl.where(tmp61, tmp62, tmp60) tl.store(out_ptr0 + x0, tmp38, xmask) tl.store(out_ptr1 + x0, tmp63, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 7, 7), (196, 49, 7, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(2, 2), padding=(3, 3), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 4, 2, 2), (16, 4, 2, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_0[grid(64)](buf1, primals_2, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_2 buf2 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.float32) buf3 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.int8) triton_poi_fused_max_pool2d_with_indices_1[grid(16)](buf1, buf2, buf3, 16, XBLOCK=16, num_warps=1, num_stages=1) return buf2, primals_1, primals_3, buf1, buf3 class DiracInitBlockNew(nn.Module): """ DiracNetV2 specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. """ def __init__(self, in_channels, out_channels): super(DiracInitBlockNew, self).__init__() self.conv = nn.Conv2d(in_channels=in_channels, out_channels= out_channels, kernel_size=7, stride=2, padding=3, bias=True) self.pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) def forward(self, input_0): primals_1 = self.conv.weight primals_2 = self.conv.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
earhian/imgclsmob
DiracInitBlock
false
6,624
[ "MIT" ]
1
c87c0942420876941868c016211073dec4392e4d
https://github.com/earhian/imgclsmob/tree/c87c0942420876941868c016211073dec4392e4d
NasAvgPoolBlock
import torch import torch.nn as nn import torch.utils.data class NasAvgPoolBlock(nn.Module): """ NASNet specific 3x3 Average pooling layer with extra padding. Parameters: ---------- extra_padding : bool, default False Whether to use extra padding. """ def __init__(self, extra_padding=False): super(NasAvgPoolBlock, self).__init__() self.extra_padding = extra_padding self.pool = nn.AvgPool2d(kernel_size=3, stride=2, padding=1, count_include_pad=False) if self.extra_padding: self.pad = nn.ZeroPad2d(padding=(1, 0, 1, 0)) def forward(self, x): if self.extra_padding: x = self.pad(x) x = self.pool(x) if self.extra_padding: x = x[:, :, 1:, 1:].contiguous() return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 import torch.nn as nn import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_avg_pool2d_0(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 x1 = xindex // 2 % 2 x0 = xindex % 2 x3 = xindex // 2 x4 = xindex tmp0 = -1 + 2 * x1 tmp1 = tl.full([1], 0, tl.int64) tmp2 = tmp0 >= tmp1 tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tmp2 & tmp4 tmp6 = -1 + 2 * x0 tmp7 = tmp6 >= tmp1 tmp8 = tmp6 < tmp3 tmp9 = tmp7 & tmp8 tmp10 = tmp5 & tmp9 tmp11 = tl.load(in_ptr0 + (-5 + 2 * x0 + 8 * x3), tmp10 & xmask, eviction_policy='evict_last', other=0.0) tmp12 = 2 * x0 tmp13 = tmp12 >= tmp1 tmp14 = tmp12 < tmp3 tmp15 = tmp13 & tmp14 tmp16 = tmp5 & tmp15 tmp17 = tl.load(in_ptr0 + (-4 + 2 * x0 + 8 * x3), tmp16 & xmask, eviction_policy='evict_last', other=0.0) tmp18 = tmp17 + tmp11 tmp19 = 1 + 2 * x0 tmp20 = tmp19 >= tmp1 tmp21 = tmp19 < tmp3 tmp22 = tmp20 & tmp21 tmp23 = tmp5 & tmp22 tmp24 = tl.load(in_ptr0 + (-3 + 2 * x0 + 8 * x3), tmp23 & xmask, eviction_policy='evict_last', other=0.0) tmp25 = tmp24 + tmp18 tmp26 = 2 * x1 tmp27 = tmp26 >= tmp1 tmp28 = tmp26 < tmp3 tmp29 = tmp27 & tmp28 tmp30 = tmp29 & tmp9 tmp31 = tl.load(in_ptr0 + (-1 + 2 * x0 + 8 * x3), tmp30 & xmask, eviction_policy='evict_last', other=0.0) tmp32 = tmp31 + tmp25 tmp33 = tmp29 & tmp15 tmp34 = tl.load(in_ptr0 + (2 * x0 + 8 * x3), tmp33 & xmask, eviction_policy='evict_last', other=0.0) tmp35 = tmp34 + tmp32 tmp36 = tmp29 & tmp22 tmp37 = tl.load(in_ptr0 + (1 + 2 * x0 + 8 * x3), tmp36 & xmask, eviction_policy='evict_last', other=0.0) tmp38 = tmp37 + tmp35 tmp39 = 1 + 2 * x1 tmp40 = tmp39 >= tmp1 tmp41 = tmp39 < tmp3 tmp42 = tmp40 & tmp41 tmp43 = tmp42 & tmp9 tmp44 = tl.load(in_ptr0 + (3 + 2 * x0 + 8 * x3), tmp43 & xmask, eviction_policy='evict_last', other=0.0) tmp45 = tmp44 + tmp38 tmp46 = tmp42 & tmp15 tmp47 = tl.load(in_ptr0 + (4 + 2 * x0 + 8 * x3), tmp46 & xmask, eviction_policy='evict_last', other=0.0) tmp48 = tmp47 + tmp45 tmp49 = tmp42 & tmp22 tmp50 = tl.load(in_ptr0 + (5 + 2 * x0 + 8 * x3), tmp49 & xmask, eviction_policy='evict_last', other=0.0) tmp51 = tmp50 + tmp48 tmp52 = (0 * (0 >= -1 + 2 * x0) + (-1 + 2 * x0) * (-1 + 2 * x0 > 0)) * ( 0 * (0 >= -1 + 2 * x1) + (-1 + 2 * x1) * (-1 + 2 * x1 > 0)) + (4 * (4 <= 2 + 2 * x0) + (2 + 2 * x0) * (2 + 2 * x0 < 4)) * (4 * (4 <= 2 + 2 * x1) + (2 + 2 * x1) * (2 + 2 * x1 < 4)) + -1 * (0 * (0 >= -1 + 2 * x0) + (-1 + 2 * x0) * (-1 + 2 * x0 > 0)) * (4 * (4 <= 2 + 2 * x1) + (2 + 2 * x1) * (2 + 2 * x1 < 4)) + -1 * (0 * (0 >= -1 + 2 * x1) + ( -1 + 2 * x1) * (-1 + 2 * x1 > 0)) * (4 * (4 <= 2 + 2 * x0) + (2 + 2 * x0) * (2 + 2 * x0 < 4)) tmp53 = tmp51 / tmp52 tl.store(out_ptr0 + x4, tmp53, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32) get_raw_stream(0) triton_poi_fused_avg_pool2d_0[grid(64)](arg0_1, buf0, 64, XBLOCK=64, num_warps=1, num_stages=1) del arg0_1 return buf0, class NasAvgPoolBlockNew(nn.Module): """ NASNet specific 3x3 Average pooling layer with extra padding. Parameters: ---------- extra_padding : bool, default False Whether to use extra padding. """ def __init__(self, extra_padding=False): super(NasAvgPoolBlockNew, self).__init__() self.extra_padding = extra_padding self.pool = nn.AvgPool2d(kernel_size=3, stride=2, padding=1, count_include_pad=False) if self.extra_padding: self.pad = nn.ZeroPad2d(padding=(1, 0, 1, 0)) def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
earhian/imgclsmob
NasAvgPoolBlock
false
6,625
[ "MIT" ]
1
c87c0942420876941868c016211073dec4392e4d
https://github.com/earhian/imgclsmob/tree/c87c0942420876941868c016211073dec4392e4d
IBNbConvBlock
import torch import torch.nn as nn import torch.utils.data class IBNbConvBlock(nn.Module): """ IBN(b)-ResNet specific convolution block with Instance normalization and ReLU activation. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. kernel_size : int or tuple/list of 2 int Convolution window size. stride : int or tuple/list of 2 int Strides of the convolution. padding : int or tuple/list of 2 int Padding value for convolution layer. dilation : int or tuple/list of 2 int, default 1 Dilation value for convolution layer. groups : int, default 1 Number of groups. bias : bool, default False Whether the layer uses a bias vector. activate : bool, default True Whether activate the convolution block. """ def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation=1, groups=1, bias=False, activate=True): super(IBNbConvBlock, self).__init__() self.activate = activate self.conv = nn.Conv2d(in_channels=in_channels, out_channels= out_channels, kernel_size=kernel_size, stride=stride, padding= padding, dilation=dilation, groups=groups, bias=bias) self.inst_norm = nn.InstanceNorm2d(num_features=out_channels, affine=True) if self.activate: self.activ = nn.ReLU(inplace=True) def forward(self, x): x = self.conv(x) x = self.inst_norm(x) if self.activate: x = self.activ(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4, 'stride': 1, 'padding': 4}]
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 import torch.utils.data 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__native_batch_norm_legit_relu_repeat_threshold_backward_0( in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, out_ptr3, out_ptr4, out_ptr5, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 16 rnumel = 81 RBLOCK: tl.constexpr = 128 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel rindex = tl.arange(0, RBLOCK)[None, :] rmask = rindex < rnumel x0 = xindex r1 = rindex x2 = xindex % 4 tmp0 = tl.load(in_ptr0 + x0 % 4, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + (r1 + 81 * x0), rmask & xmask, other=0.0) tmp26 = tl.load(in_ptr2 + x2, xmask, eviction_policy='evict_last') tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tl.where(rmask & xmask, tmp2, 0) tmp5 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK]) tmp7 = tl.where(rmask & xmask, tmp5, 0) tmp8 = tl.sum(tmp7, 1)[:, None] tmp9 = tl.full([XBLOCK, 1], 81, tl.int32) tmp10 = tmp9.to(tl.float32) tmp11 = tmp8 / tmp10 tmp12 = tmp2 - tmp11 tmp13 = tmp12 * tmp12 tmp14 = tl.broadcast_to(tmp13, [XBLOCK, RBLOCK]) tmp16 = tl.where(rmask & xmask, tmp14, 0) tmp17 = tl.sum(tmp16, 1)[:, None] tmp18 = tmp1 - tmp11 tmp19 = 81.0 tmp20 = tmp17 / tmp19 tmp21 = 1e-05 tmp22 = tmp20 + tmp21 tmp23 = libdevice.rsqrt(tmp22) tmp24 = tmp18 * tmp23 tmp25 = tmp24 * tmp0 tmp27 = tmp25 + tmp26 tmp28 = tl.full([1, 1], 0, tl.int32) tmp29 = triton_helpers.maximum(tmp28, tmp27) tmp30 = 0.0 tmp31 = tmp29 <= tmp30 tl.store(out_ptr0 + x0, tmp0, xmask) tl.store(out_ptr3 + (r1 + 81 * x0), tmp29, rmask & xmask) tl.store(out_ptr4 + (r1 + 81 * x0), tmp31, rmask & xmask) tl.store(out_ptr5 + x0, tmp23, xmask) tl.store(out_ptr1 + x0, tmp11, 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, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_3, (4,), (1,)) assert_size_stride(primals_4, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_2, primals_1, stride=(1, 1), padding=(4, 4), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 4, 9, 9), (324, 81, 9, 1)) buf1 = empty_strided_cuda((16,), (1,), torch.float32) buf2 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32 ) buf6 = empty_strided_cuda((4, 4, 9, 9), (324, 81, 9, 1), torch.float32) buf7 = empty_strided_cuda((4, 4, 9, 9), (324, 81, 9, 1), torch.bool) buf5 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32 ) get_raw_stream(0) triton_per_fused__native_batch_norm_legit_relu_repeat_threshold_backward_0[ grid(16)](primals_3, buf0, primals_4, buf1, buf2, buf6, buf7, buf5, 16, 81, XBLOCK=1, num_warps=2, num_stages=1) del primals_3 del primals_4 return buf6, primals_1, primals_2, buf0, buf1, reinterpret_tensor(buf5, (16,), (1,), 0), buf7, reinterpret_tensor(buf2, (1, 16, 1, 1), (16, 1, 1, 1), 0) class IBNbConvBlockNew(nn.Module): """ IBN(b)-ResNet specific convolution block with Instance normalization and ReLU activation. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. kernel_size : int or tuple/list of 2 int Convolution window size. stride : int or tuple/list of 2 int Strides of the convolution. padding : int or tuple/list of 2 int Padding value for convolution layer. dilation : int or tuple/list of 2 int, default 1 Dilation value for convolution layer. groups : int, default 1 Number of groups. bias : bool, default False Whether the layer uses a bias vector. activate : bool, default True Whether activate the convolution block. """ def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation=1, groups=1, bias=False, activate=True): super(IBNbConvBlockNew, self).__init__() self.activate = activate self.conv = nn.Conv2d(in_channels=in_channels, out_channels= out_channels, kernel_size=kernel_size, stride=stride, padding= padding, dilation=dilation, groups=groups, bias=bias) self.inst_norm = nn.InstanceNorm2d(num_features=out_channels, affine=True) if self.activate: self.activ = nn.ReLU(inplace=True) def forward(self, input_0): primals_1 = self.conv.weight primals_3 = self.inst_norm.weight primals_4 = self.inst_norm.bias primals_2 = input_0 output = call([primals_1, primals_2, primals_3, primals_4]) return output[0]
earhian/imgclsmob
IBNbConvBlock
false
6,626
[ "MIT" ]
1
c87c0942420876941868c016211073dec4392e4d
https://github.com/earhian/imgclsmob/tree/c87c0942420876941868c016211073dec4392e4d
Discriminator
import torch import torch.nn as nn from numpy import * class Discriminator(nn.Module): """docstring for Discriminator""" def __init__(self, in_dim, out_dim): super(Discriminator, self).__init__() self.Linear1 = nn.Linear(in_dim, out_dim) self.Relu = nn.ReLU() self.Linear2 = nn.Linear(out_dim, 1) self.Sigmoid = nn.Sigmoid() def forward(self, input): x = self.Linear1(input) x = self.Relu(x) x = self.Linear2(x) x = self.Sigmoid(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_dim': 4, 'out_dim': 4}]
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 torch.nn as nn from numpy import * 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_relu_threshold_backward_0(in_out_ptr0, in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, 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 + x2, tmp4, xmask) tl.store(out_ptr0 + x2, tmp6, xmask) @triton.jit def triton_poi_fused_sigmoid_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 64 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 = tl.load(in_ptr0 + 0) tmp2 = tl.broadcast_to(tmp1, [XBLOCK]) tmp3 = tmp0 + tmp2 tmp4 = tl.sigmoid(tmp3) tl.store(in_out_ptr0 + x0, tmp4, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (1, 4), (4, 1)) assert_size_stride(primals_5, (1,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0), out=buf0) del primals_1 buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf0 buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) get_raw_stream(0) triton_poi_fused_relu_threshold_backward_0[grid(256)](buf1, primals_2, buf4, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 buf2 = empty_strided_cuda((64, 1), (1, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 1), (1, 4), 0), out=buf2) buf3 = reinterpret_tensor(buf2, (4, 4, 4, 1), (16, 4, 1, 1), 0) del buf2 triton_poi_fused_sigmoid_1[grid(64)](buf3, primals_5, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_5 return buf3, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), reinterpret_tensor(buf1, (64, 4), (4, 1), 0), buf3, primals_4, buf4 class DiscriminatorNew(nn.Module): """docstring for Discriminator""" def __init__(self, in_dim, out_dim): super(DiscriminatorNew, self).__init__() self.Linear1 = nn.Linear(in_dim, out_dim) self.Relu = nn.ReLU() self.Linear2 = nn.Linear(out_dim, 1) self.Sigmoid = nn.Sigmoid() def forward(self, input_0): primals_1 = self.Linear1.weight primals_2 = self.Linear1.bias primals_4 = self.Linear2.weight primals_5 = self.Linear2.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
ducviet00/HMER
Discriminator
false
6,627
[ "MIT" ]
1
0fa322ed35412737a24ec3955c9a3d96d1989bd4
https://github.com/ducviet00/HMER/tree/0fa322ed35412737a24ec3955c9a3d96d1989bd4
NasPathBranch
import torch import torch.nn as nn import torch.utils.data def conv1x1(in_channels, out_channels, stride=1, bias=False): """ Convolution 1x1 layer. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple/list of 2 int, default 1 Strides of the convolution. bias : bool, default False Whether the layer uses a bias vector. """ return nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride, bias=bias) def nasnet_avgpool1x1_s2(): """ NASNet specific 1x1 Average pooling layer with stride 2. """ return nn.AvgPool2d(kernel_size=1, stride=2, count_include_pad=False) class NasPathBranch(nn.Module): """ NASNet specific `path` branch (auxiliary block). Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. extra_padding : bool, default False Whether to use extra padding. """ def __init__(self, in_channels, out_channels, extra_padding=False): super(NasPathBranch, self).__init__() self.extra_padding = extra_padding self.avgpool = nasnet_avgpool1x1_s2() self.conv = conv1x1(in_channels=in_channels, out_channels=out_channels) if self.extra_padding: self.pad = nn.ZeroPad2d(padding=(0, 1, 0, 1)) def forward(self, x): if self.extra_padding: x = self.pad(x) x = x[:, :, 1:, 1:].contiguous() x = self.avgpool(x) x = self.conv(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'out_channels': 4}]
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 import torch.nn as nn import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_avg_pool2d_0(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 x0 = xindex % 2 x1 = xindex // 2 x2 = xindex tmp0 = tl.load(in_ptr0 + (2 * x0 + 8 * x1), xmask, eviction_policy= 'evict_last') tmp1 = 1.0 tmp2 = tmp0 * tmp1 tl.store(out_ptr0 + x2, tmp2, xmask) def call(args): primals_1, primals_2 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4, 4, 1, 1), (4, 1, 1, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32) get_raw_stream(0) triton_poi_fused_avg_pool2d_0[grid(64)](primals_1, buf0, 64, XBLOCK =64, num_warps=1, num_stages=1) del primals_1 buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1, 1), 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)) return buf1, primals_2, buf0 def conv1x1(in_channels, out_channels, stride=1, bias=False): """ Convolution 1x1 layer. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple/list of 2 int, default 1 Strides of the convolution. bias : bool, default False Whether the layer uses a bias vector. """ return nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride, bias=bias) def nasnet_avgpool1x1_s2(): """ NASNet specific 1x1 Average pooling layer with stride 2. """ return nn.AvgPool2d(kernel_size=1, stride=2, count_include_pad=False) class NasPathBranchNew(nn.Module): """ NASNet specific `path` branch (auxiliary block). Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. extra_padding : bool, default False Whether to use extra padding. """ def __init__(self, in_channels, out_channels, extra_padding=False): super(NasPathBranchNew, self).__init__() self.extra_padding = extra_padding self.avgpool = nasnet_avgpool1x1_s2() self.conv = conv1x1(in_channels=in_channels, out_channels=out_channels) if self.extra_padding: self.pad = nn.ZeroPad2d(padding=(0, 1, 0, 1)) def forward(self, input_0): primals_2 = self.conv.weight primals_1 = input_0 output = call([primals_1, primals_2]) return output[0]
earhian/imgclsmob
NasPathBranch
false
6,628
[ "MIT" ]
1
c87c0942420876941868c016211073dec4392e4d
https://github.com/earhian/imgclsmob/tree/c87c0942420876941868c016211073dec4392e4d
IBNbResInitBlock
import torch import torch.nn as nn import torch.utils.data def ibnb_conv7x7_block(in_channels, out_channels, stride=1, padding=3, bias =False, activate=True): """ 7x7 version of the IBN(b)-ResNet specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple/list of 2 int, default 1 Strides of the convolution. padding : int or tuple/list of 2 int, default 3 Padding value for convolution layer. bias : bool, default False Whether the layer uses a bias vector. activate : bool, default True Whether activate the convolution block. """ return IBNbConvBlock(in_channels=in_channels, out_channels=out_channels, kernel_size=7, stride=stride, padding=padding, bias=bias, activate= activate) class IBNbConvBlock(nn.Module): """ IBN(b)-ResNet specific convolution block with Instance normalization and ReLU activation. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. kernel_size : int or tuple/list of 2 int Convolution window size. stride : int or tuple/list of 2 int Strides of the convolution. padding : int or tuple/list of 2 int Padding value for convolution layer. dilation : int or tuple/list of 2 int, default 1 Dilation value for convolution layer. groups : int, default 1 Number of groups. bias : bool, default False Whether the layer uses a bias vector. activate : bool, default True Whether activate the convolution block. """ def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation=1, groups=1, bias=False, activate=True): super(IBNbConvBlock, self).__init__() self.activate = activate self.conv = nn.Conv2d(in_channels=in_channels, out_channels= out_channels, kernel_size=kernel_size, stride=stride, padding= padding, dilation=dilation, groups=groups, bias=bias) self.inst_norm = nn.InstanceNorm2d(num_features=out_channels, affine=True) if self.activate: self.activ = nn.ReLU(inplace=True) def forward(self, x): x = self.conv(x) x = self.inst_norm(x) if self.activate: x = self.activ(x) return x class IBNbResInitBlock(nn.Module): """ IBN(b)-ResNet specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. """ def __init__(self, in_channels, out_channels): super(IBNbResInitBlock, self).__init__() self.conv = ibnb_conv7x7_block(in_channels=in_channels, out_channels=out_channels, stride=2) self.pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) def forward(self, x): x = self.conv(x) x = self.pool(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'out_channels': 4}]
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 import torch.utils.data 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_repeat_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 x0 = xindex tmp0 = tl.load(in_ptr0 + x0 % 4, xmask) tl.store(out_ptr0 + x0, tmp0, xmask) @triton.jit def triton_poi_fused__native_batch_norm_legit_1(in_ptr0, out_ptr0, out_ptr1, 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_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp6 = tmp4 + tmp5 tmp7 = 4.0 tmp8 = tmp6 / tmp7 tmp9 = tmp0 - tmp8 tmp10 = tmp9 * tmp9 tmp11 = tmp1 - tmp8 tmp12 = tmp11 * tmp11 tmp13 = tmp10 + tmp12 tmp14 = tmp3 - tmp8 tmp15 = tmp14 * tmp14 tmp16 = tmp13 + tmp15 tmp17 = tmp5 - tmp8 tmp18 = tmp17 * tmp17 tmp19 = tmp16 + tmp18 tmp20 = tmp19 / tmp7 tmp21 = 1e-05 tmp22 = tmp20 + tmp21 tmp23 = libdevice.rsqrt(tmp22) tl.store(out_ptr0 + x0, tmp8, xmask) tl.store(out_ptr1 + x0, tmp23, xmask) @triton.jit def triton_poi_fused_relu_2(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, 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 x4 = xindex // 4 x1 = xindex // 4 % 4 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr1 + x4, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + x4, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr3 + x4, xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr4 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 - tmp1 tmp4 = tmp2 * tmp3 tmp6 = tmp4 * tmp5 tmp8 = tmp6 + tmp7 tmp9 = tl.full([1], 0, tl.int32) tmp10 = triton_helpers.maximum(tmp9, tmp8) tl.store(out_ptr0 + x3, tmp10, xmask) @triton.jit def triton_poi_fused_max_pool2d_with_indices_3(in_ptr0, out_ptr0, out_ptr1, 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.full([1], -1, tl.int64) tmp1 = tl.full([1], 0, tl.int64) tmp2 = tmp0 >= tmp1 tmp3 = tl.full([1], 2, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tmp2 & tmp4 tmp6 = tmp5 & tmp5 tmp7 = tl.load(in_ptr0 + (-3 + 4 * x0), tmp6 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp8 = tmp1 >= tmp1 tmp9 = tmp1 < tmp3 tmp10 = tmp8 & tmp9 tmp11 = tmp5 & tmp10 tmp12 = tl.load(in_ptr0 + (-2 + 4 * x0), tmp11 & xmask, eviction_policy ='evict_last', other=float('-inf')) tmp13 = triton_helpers.maximum(tmp12, tmp7) tmp14 = tl.full([1], 1, tl.int64) tmp15 = tmp14 >= tmp1 tmp16 = tmp14 < tmp3 tmp17 = tmp15 & tmp16 tmp18 = tmp5 & tmp17 tmp19 = tl.load(in_ptr0 + (-1 + 4 * x0), tmp18 & xmask, eviction_policy ='evict_last', other=float('-inf')) tmp20 = triton_helpers.maximum(tmp19, tmp13) tmp21 = tmp10 & tmp5 tmp22 = tl.load(in_ptr0 + (-1 + 4 * x0), tmp21 & xmask, eviction_policy ='evict_last', other=float('-inf')) tmp23 = triton_helpers.maximum(tmp22, tmp20) tmp24 = tmp10 & tmp10 tmp25 = tl.load(in_ptr0 + 4 * x0, tmp24 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp26 = triton_helpers.maximum(tmp25, tmp23) tmp27 = tmp10 & tmp17 tmp28 = tl.load(in_ptr0 + (1 + 4 * x0), tmp27 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp29 = triton_helpers.maximum(tmp28, tmp26) tmp30 = tmp17 & tmp5 tmp31 = tl.load(in_ptr0 + (1 + 4 * x0), tmp30 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp32 = triton_helpers.maximum(tmp31, tmp29) tmp33 = tmp17 & tmp10 tmp34 = tl.load(in_ptr0 + (2 + 4 * x0), tmp33 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp35 = triton_helpers.maximum(tmp34, tmp32) tmp36 = tmp17 & tmp17 tmp37 = tl.load(in_ptr0 + (3 + 4 * x0), tmp36 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp38 = triton_helpers.maximum(tmp37, tmp35) tmp39 = tmp12 > tmp7 tmp40 = tl.full([1], 1, tl.int8) tmp41 = tl.full([1], 0, tl.int8) tmp42 = tl.where(tmp39, tmp40, tmp41) tmp43 = tmp19 > tmp13 tmp44 = tl.full([1], 2, tl.int8) tmp45 = tl.where(tmp43, tmp44, tmp42) tmp46 = tmp22 > tmp20 tmp47 = tl.full([1], 3, tl.int8) tmp48 = tl.where(tmp46, tmp47, tmp45) tmp49 = tmp25 > tmp23 tmp50 = tl.full([1], 4, tl.int8) tmp51 = tl.where(tmp49, tmp50, tmp48) tmp52 = tmp28 > tmp26 tmp53 = tl.full([1], 5, tl.int8) tmp54 = tl.where(tmp52, tmp53, tmp51) tmp55 = tmp31 > tmp29 tmp56 = tl.full([1], 6, tl.int8) tmp57 = tl.where(tmp55, tmp56, tmp54) tmp58 = tmp34 > tmp32 tmp59 = tl.full([1], 7, tl.int8) tmp60 = tl.where(tmp58, tmp59, tmp57) tmp61 = tmp37 > tmp35 tmp62 = tl.full([1], 8, tl.int8) tmp63 = tl.where(tmp61, tmp62, tmp60) tl.store(out_ptr0 + x0, tmp38, xmask) tl.store(out_ptr1 + x0, tmp63, xmask) def call(args): primals_1, primals_2, primals_3, primals_4 = args args.clear() assert_size_stride(primals_1, (4, 4, 7, 7), (196, 49, 7, 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,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_2, primals_1, stride=(2, 2), padding=(3, 3), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 4, 2, 2), (16, 4, 2, 1)) buf1 = empty_strided_cuda((16,), (1,), torch.float32) get_raw_stream(0) triton_poi_fused_repeat_0[grid(16)](primals_3, buf1, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_3 buf2 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32 ) buf3 = empty_strided_cuda((1, 16, 1, 1), (16, 1, 16, 16), torch.float32 ) triton_poi_fused__native_batch_norm_legit_1[grid(16)](buf0, buf2, buf3, 16, XBLOCK=16, num_warps=1, num_stages=1) buf4 = empty_strided_cuda((4, 4, 2, 2), (16, 4, 2, 1), torch.float32) triton_poi_fused_relu_2[grid(64)](buf0, buf2, buf3, buf1, primals_4, buf4, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf2 del primals_4 buf5 = reinterpret_tensor(buf3, (4, 4, 1, 1), (4, 1, 1, 1), 0) del buf3 buf6 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.int8) triton_poi_fused_max_pool2d_with_indices_3[grid(16)](buf4, buf5, buf6, 16, XBLOCK=16, num_warps=1, num_stages=1) return buf5, primals_1, primals_2, buf0, buf1, buf4, buf6 def ibnb_conv7x7_block(in_channels, out_channels, stride=1, padding=3, bias =False, activate=True): """ 7x7 version of the IBN(b)-ResNet specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple/list of 2 int, default 1 Strides of the convolution. padding : int or tuple/list of 2 int, default 3 Padding value for convolution layer. bias : bool, default False Whether the layer uses a bias vector. activate : bool, default True Whether activate the convolution block. """ return IBNbConvBlock(in_channels=in_channels, out_channels=out_channels, kernel_size=7, stride=stride, padding=padding, bias=bias, activate= activate) class IBNbConvBlock(nn.Module): """ IBN(b)-ResNet specific convolution block with Instance normalization and ReLU activation. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. kernel_size : int or tuple/list of 2 int Convolution window size. stride : int or tuple/list of 2 int Strides of the convolution. padding : int or tuple/list of 2 int Padding value for convolution layer. dilation : int or tuple/list of 2 int, default 1 Dilation value for convolution layer. groups : int, default 1 Number of groups. bias : bool, default False Whether the layer uses a bias vector. activate : bool, default True Whether activate the convolution block. """ def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation=1, groups=1, bias=False, activate=True): super(IBNbConvBlock, self).__init__() self.activate = activate self.conv = nn.Conv2d(in_channels=in_channels, out_channels= out_channels, kernel_size=kernel_size, stride=stride, padding= padding, dilation=dilation, groups=groups, bias=bias) self.inst_norm = nn.InstanceNorm2d(num_features=out_channels, affine=True) if self.activate: self.activ = nn.ReLU(inplace=True) def forward(self, x): x = self.conv(x) x = self.inst_norm(x) if self.activate: x = self.activ(x) return x class IBNbResInitBlockNew(nn.Module): """ IBN(b)-ResNet specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. """ def __init__(self, in_channels, out_channels): super(IBNbResInitBlockNew, self).__init__() self.conv = ibnb_conv7x7_block(in_channels=in_channels, out_channels=out_channels, stride=2) self.pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) def forward(self, input_0): primals_1 = self.conv.conv.weight primals_3 = self.conv.inst_norm.weight primals_4 = self.conv.inst_norm.bias primals_2 = input_0 output = call([primals_1, primals_2, primals_3, primals_4]) return output[0]
earhian/imgclsmob
IBNbResInitBlock
false
6,629
[ "MIT" ]
1
c87c0942420876941868c016211073dec4392e4d
https://github.com/earhian/imgclsmob/tree/c87c0942420876941868c016211073dec4392e4d
BCEFocalLoss
import torch import torch.nn as nn class BCEFocalLoss(nn.Module): """Implementation of Focal Loss for Binary Classification Problems. Focal loss was proposed in [Focal Loss for Dense Object Detection](https://arxiv.org/abs/1708.02002). """ def __init__(self, gamma=0, eps=1e-07, reduction='mean'): """Constructor Method for FocalLoss class. Args: gamma : The focal parameter. Defaults to 0. eps : Constant for computational stability. reduction: The reduction parameter for Cross Entropy Loss. """ super(BCEFocalLoss, self).__init__() self.gamma = gamma self.reduction = reduction self.eps = eps self.bce = torch.nn.BCEWithLogitsLoss(reduction='none') def forward(self, logits: 'torch.Tensor', targets: 'torch.Tensor' ) ->torch.Tensor: """Forward method. Args: logits: The raw logits from the network of shape (N,*) where C = number of classes , * = extra dims targets: The targets Returns: The computed loss value """ targets = targets.view(logits.shape) logp = self.bce(logits, targets) p = torch.exp(-logp) loss = (1 - p) ** self.gamma * logp return loss.mean() if self.reduction == 'mean' else loss.sum( ) if self.reduction == 'sum' else loss def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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, 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 @triton.jit def triton_per_fused_binary_cross_entropy_with_logits_exp_mean_mul_neg_pow_rsub_0( in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp3 = tl.load(in_ptr1 + r0, None) tmp1 = 1.0 tmp2 = tmp1 - tmp0 tmp4 = tmp2 * tmp3 tmp5 = 0.0 tmp6 = triton_helpers.minimum(tmp5, tmp3) tmp7 = tl_math.abs(tmp3) tmp8 = -tmp7 tmp9 = tl_math.exp(tmp8) tmp10 = libdevice.log1p(tmp9) tmp11 = tmp6 - tmp10 tmp12 = tmp4 - tmp11 tmp13 = -tmp12 tmp14 = tl_math.exp(tmp13) tmp1 - tmp14 tmp16 = tmp1 * tmp12 tmp17 = tl.broadcast_to(tmp16, [RBLOCK]) tmp19 = triton_helpers.promote_to_tensor(tl.sum(tmp17, 0)) tmp20 = 256.0 tmp21 = tmp19 / tmp20 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp21, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf1 = buf0 del buf0 get_raw_stream(0) triton_per_fused_binary_cross_entropy_with_logits_exp_mean_mul_neg_pow_rsub_0[ grid(1)](buf1, arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 return buf1, class BCEFocalLossNew(nn.Module): """Implementation of Focal Loss for Binary Classification Problems. Focal loss was proposed in [Focal Loss for Dense Object Detection](https://arxiv.org/abs/1708.02002). """ def __init__(self, gamma=0, eps=1e-07, reduction='mean'): """Constructor Method for FocalLoss class. Args: gamma : The focal parameter. Defaults to 0. eps : Constant for computational stability. reduction: The reduction parameter for Cross Entropy Loss. """ super(BCEFocalLossNew, self).__init__() self.gamma = gamma self.reduction = reduction self.eps = eps self.bce = torch.nn.BCEWithLogitsLoss(reduction='none') def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
earlbabson/torchflare
BCEFocalLoss
false
6,630
[ "Apache-2.0" ]
1
15db06d313a53a3ec4640869335ba87730562b28
https://github.com/earlbabson/torchflare/tree/15db06d313a53a3ec4640869335ba87730562b28
LeNet
import torch import torch.nn as nn class LeNet(nn.Module): def __init__(self): super().__init__() self.conv_1 = nn.Conv2d(3, 6, kernel_size=5, padding=2) self.sigmoid = nn.Sigmoid() self.avgpool = nn.AvgPool2d(kernel_size=5, stride=2) self.conv_2 = nn.Conv2d(6, 16, kernel_size=5, stride=2) self.fc_1 = nn.Linear(16 * 5 * 5, 120) self.fc_2 = nn.Linear(120, 84) self.fc_3 = nn.Linear(84, 7) def get_resnet_layer(self, block, n_blocks, channels, stride=1): layers = [] if self.in_channels != block.expansion * channels: downsample = True else: downsample = False layers.append(block(self.in_channels, channels, stride, downsample)) for i in range(1, n_blocks): layers.append(block(block.expansion * channels, channels)) self.in_channels = block.expansion * channels return nn.Sequential(*layers) def forward(self, x): x = self.conv_1(x) x = self.sigmoid(x) x = self.avgpool(x) x = self.conv_2(x) x = self.sigmoid(x) x = self.avgpool(x) x = nn.Flatten()(x) x = self.fc_1(x) x = self.sigmoid(x) x = self.fc_2(x) x = self.sigmoid(x) x = self.fc_3(x) h = x.view(x.shape[0], -1) return x, h def get_inputs(): return [torch.rand([4, 3, 64, 64])] 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 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_poi_fused_convolution_sigmoid_0(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) x3 = xindex x1 = xindex // 4096 % 6 tmp0 = tl.load(in_out_ptr0 + x3, None) tmp1 = tl.load(in_ptr0 + x1, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.sigmoid(tmp2) tl.store(in_out_ptr0 + x3, tmp3, None) @triton.jit def triton_poi_fused_avg_pool2d_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 21600 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 30 x1 = xindex // 30 % 30 x2 = xindex // 900 x3 = xindex tmp0 = tl.load(in_ptr0 + (2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (2 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (3 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr0 + (4 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp9 = tl.load(in_ptr0 + (64 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr0 + (65 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp13 = tl.load(in_ptr0 + (66 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp15 = tl.load(in_ptr0 + (67 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp17 = tl.load(in_ptr0 + (68 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp19 = tl.load(in_ptr0 + (128 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp21 = tl.load(in_ptr0 + (129 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp23 = tl.load(in_ptr0 + (130 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp25 = tl.load(in_ptr0 + (131 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp27 = tl.load(in_ptr0 + (132 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp29 = tl.load(in_ptr0 + (192 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp31 = tl.load(in_ptr0 + (193 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp33 = tl.load(in_ptr0 + (194 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp35 = tl.load(in_ptr0 + (195 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp37 = tl.load(in_ptr0 + (196 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp39 = tl.load(in_ptr0 + (256 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp41 = tl.load(in_ptr0 + (257 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp43 = tl.load(in_ptr0 + (258 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp45 = tl.load(in_ptr0 + (259 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp47 = tl.load(in_ptr0 + (260 + 2 * x0 + 128 * x1 + 4096 * x2), xmask, eviction_policy='evict_last') tmp2 = tmp1 + tmp0 tmp4 = tmp3 + tmp2 tmp6 = tmp5 + tmp4 tmp8 = tmp7 + tmp6 tmp10 = tmp9 + tmp8 tmp12 = tmp11 + tmp10 tmp14 = tmp13 + tmp12 tmp16 = tmp15 + tmp14 tmp18 = tmp17 + tmp16 tmp20 = tmp19 + tmp18 tmp22 = tmp21 + tmp20 tmp24 = tmp23 + tmp22 tmp26 = tmp25 + tmp24 tmp28 = tmp27 + tmp26 tmp30 = tmp29 + tmp28 tmp32 = tmp31 + tmp30 tmp34 = tmp33 + tmp32 tmp36 = tmp35 + tmp34 tmp38 = tmp37 + tmp36 tmp40 = tmp39 + tmp38 tmp42 = tmp41 + tmp40 tmp44 = tmp43 + tmp42 tmp46 = tmp45 + tmp44 tmp48 = tmp47 + tmp46 tmp49 = 0.04 tmp50 = tmp48 * tmp49 tl.store(out_ptr0 + x3, tmp50, xmask) @triton.jit def triton_poi_fused_convolution_sigmoid_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 10816 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 169 % 16 x2 = xindex // 2704 x4 = xindex % 2704 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.sigmoid(tmp2) tl.store(out_ptr0 + (x4 + 2720 * x2), tmp3, xmask) @triton.jit def triton_poi_fused_avg_pool2d_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 1600 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 5 x1 = xindex // 5 % 5 x2 = xindex // 25 % 16 x3 = xindex // 400 x4 = xindex tmp0 = tl.load(in_ptr0 + (2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (2 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (3 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr0 + (4 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3), xmask, eviction_policy='evict_last') tmp9 = tl.load(in_ptr0 + (13 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3), xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr0 + (14 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3 ), xmask, eviction_policy='evict_last') tmp13 = tl.load(in_ptr0 + (15 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3 ), xmask, eviction_policy='evict_last') tmp15 = tl.load(in_ptr0 + (16 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3 ), xmask, eviction_policy='evict_last') tmp17 = tl.load(in_ptr0 + (17 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3 ), xmask, eviction_policy='evict_last') tmp19 = tl.load(in_ptr0 + (26 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3 ), xmask, eviction_policy='evict_last') tmp21 = tl.load(in_ptr0 + (27 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3 ), xmask, eviction_policy='evict_last') tmp23 = tl.load(in_ptr0 + (28 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3 ), xmask, eviction_policy='evict_last') tmp25 = tl.load(in_ptr0 + (29 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3 ), xmask, eviction_policy='evict_last') tmp27 = tl.load(in_ptr0 + (30 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3 ), xmask, eviction_policy='evict_last') tmp29 = tl.load(in_ptr0 + (39 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3 ), xmask, eviction_policy='evict_last') tmp31 = tl.load(in_ptr0 + (40 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3 ), xmask, eviction_policy='evict_last') tmp33 = tl.load(in_ptr0 + (41 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3 ), xmask, eviction_policy='evict_last') tmp35 = tl.load(in_ptr0 + (42 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3 ), xmask, eviction_policy='evict_last') tmp37 = tl.load(in_ptr0 + (43 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3 ), xmask, eviction_policy='evict_last') tmp39 = tl.load(in_ptr0 + (52 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3 ), xmask, eviction_policy='evict_last') tmp41 = tl.load(in_ptr0 + (53 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3 ), xmask, eviction_policy='evict_last') tmp43 = tl.load(in_ptr0 + (54 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3 ), xmask, eviction_policy='evict_last') tmp45 = tl.load(in_ptr0 + (55 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3 ), xmask, eviction_policy='evict_last') tmp47 = tl.load(in_ptr0 + (56 + 2 * x0 + 26 * x1 + 169 * x2 + 2720 * x3 ), xmask, eviction_policy='evict_last') tmp2 = tmp1 + tmp0 tmp4 = tmp3 + tmp2 tmp6 = tmp5 + tmp4 tmp8 = tmp7 + tmp6 tmp10 = tmp9 + tmp8 tmp12 = tmp11 + tmp10 tmp14 = tmp13 + tmp12 tmp16 = tmp15 + tmp14 tmp18 = tmp17 + tmp16 tmp20 = tmp19 + tmp18 tmp22 = tmp21 + tmp20 tmp24 = tmp23 + tmp22 tmp26 = tmp25 + tmp24 tmp28 = tmp27 + tmp26 tmp30 = tmp29 + tmp28 tmp32 = tmp31 + tmp30 tmp34 = tmp33 + tmp32 tmp36 = tmp35 + tmp34 tmp38 = tmp37 + tmp36 tmp40 = tmp39 + tmp38 tmp42 = tmp41 + tmp40 tmp44 = tmp43 + tmp42 tmp46 = tmp45 + tmp44 tmp48 = tmp47 + tmp46 tmp49 = 0.04 tmp50 = tmp48 * tmp49 tl.store(out_ptr0 + x4, tmp50, xmask) @triton.jit def triton_poi_fused_sigmoid_4(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 480 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 120 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.sigmoid(tmp2) tl.store(in_out_ptr0 + x2, tmp3, xmask) @triton.jit def triton_poi_fused_sigmoid_5(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 336 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 84 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.sigmoid(tmp2) tl.store(in_out_ptr0 + x2, tmp3, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11) = args args.clear() assert_size_stride(primals_1, (6, 3, 5, 5), (75, 25, 5, 1)) assert_size_stride(primals_2, (6,), (1,)) assert_size_stride(primals_3, (4, 3, 64, 64), (12288, 4096, 64, 1)) assert_size_stride(primals_4, (16, 6, 5, 5), (150, 25, 5, 1)) assert_size_stride(primals_5, (16,), (1,)) assert_size_stride(primals_6, (120, 400), (400, 1)) assert_size_stride(primals_7, (120,), (1,)) assert_size_stride(primals_8, (84, 120), (120, 1)) assert_size_stride(primals_9, (84,), (1,)) assert_size_stride(primals_10, (7, 84), (84, 1)) assert_size_stride(primals_11, (7,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1, 1), padding=(2, 2), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 6, 64, 64), (24576, 4096, 64, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_sigmoid_0[grid(98304)](buf1, primals_2, 98304, XBLOCK=1024, num_warps=4, num_stages=1) del primals_2 buf2 = empty_strided_cuda((4, 6, 30, 30), (5400, 900, 30, 1), torch .float32) triton_poi_fused_avg_pool2d_1[grid(21600)](buf1, buf2, 21600, XBLOCK=256, num_warps=4, num_stages=1) buf3 = extern_kernels.convolution(buf2, primals_4, stride=(2, 2), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf3, (4, 16, 13, 13), (2704, 169, 13, 1)) buf4 = empty_strided_cuda((4, 16, 13, 13), (2720, 169, 13, 1), torch.float32) triton_poi_fused_convolution_sigmoid_2[grid(10816)](buf3, primals_5, buf4, 10816, XBLOCK=256, num_warps=4, num_stages=1) del buf3 del primals_5 buf5 = empty_strided_cuda((4, 16, 5, 5), (400, 25, 5, 1), torch.float32 ) triton_poi_fused_avg_pool2d_3[grid(1600)](buf4, buf5, 1600, XBLOCK= 128, num_warps=4, num_stages=1) buf6 = empty_strided_cuda((4, 120), (120, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf5, (4, 400), (400, 1), 0), reinterpret_tensor(primals_6, (400, 120), (1, 400), 0), out=buf6) buf7 = buf6 del buf6 triton_poi_fused_sigmoid_4[grid(480)](buf7, primals_7, 480, XBLOCK= 256, num_warps=4, num_stages=1) del primals_7 buf8 = empty_strided_cuda((4, 84), (84, 1), torch.float32) extern_kernels.mm(buf7, reinterpret_tensor(primals_8, (120, 84), (1, 120), 0), out=buf8) buf9 = buf8 del buf8 triton_poi_fused_sigmoid_5[grid(336)](buf9, primals_9, 336, XBLOCK= 128, num_warps=4, num_stages=1) del primals_9 buf10 = empty_strided_cuda((4, 7), (7, 1), torch.float32) extern_kernels.addmm(primals_11, buf9, reinterpret_tensor( primals_10, (84, 7), (1, 84), 0), alpha=1, beta=1, out=buf10) del primals_11 return (buf10, buf10, primals_1, primals_3, primals_4, buf1, buf2, buf4, reinterpret_tensor(buf5, (4, 400), (400, 1), 0), buf7, buf9, primals_10, primals_8, primals_6) class LeNetNew(nn.Module): def __init__(self): super().__init__() self.conv_1 = nn.Conv2d(3, 6, kernel_size=5, padding=2) self.sigmoid = nn.Sigmoid() self.avgpool = nn.AvgPool2d(kernel_size=5, stride=2) self.conv_2 = nn.Conv2d(6, 16, kernel_size=5, stride=2) self.fc_1 = nn.Linear(16 * 5 * 5, 120) self.fc_2 = nn.Linear(120, 84) self.fc_3 = nn.Linear(84, 7) def get_resnet_layer(self, block, n_blocks, channels, stride=1): layers = [] if self.in_channels != block.expansion * channels: downsample = True else: downsample = False layers.append(block(self.in_channels, channels, stride, downsample)) for i in range(1, n_blocks): layers.append(block(block.expansion * channels, channels)) self.in_channels = block.expansion * channels return nn.Sequential(*layers) def forward(self, input_0): primals_1 = self.conv_1.weight primals_2 = self.conv_1.bias primals_4 = self.conv_2.weight primals_5 = self.conv_2.bias primals_6 = self.fc_1.weight primals_7 = self.fc_1.bias primals_8 = self.fc_2.weight primals_9 = self.fc_2.bias primals_10 = self.fc_3.weight primals_11 = self.fc_3.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11]) return output[0], output[1]
ducnguyenhuynh/via-trafficsign-classification
LeNet
false
6,631
[ "MIT" ]
1
e65fccc1ee377603334453eacfc3f65619dc0714
https://github.com/ducnguyenhuynh/via-trafficsign-classification/tree/e65fccc1ee377603334453eacfc3f65619dc0714
FocalLoss
import torch import torch.nn as nn class FocalLoss(nn.Module): """Implementation of Focal Loss. Focal loss was proposed in [Focal Loss for Dense Object Detection](https://arxiv.org/abs/1708.02002). """ def __init__(self, gamma=0, eps=1e-07, reduction='mean'): """Constructor Method for FocalLoss class. Args: gamma : The focal parameter. Defaults to 0. eps : Constant for computational stability. reduction: The reduction parameter for Cross Entropy Loss. """ super(FocalLoss, self).__init__() self.gamma = gamma self.reduction = reduction self.eps = eps self.ce = torch.nn.CrossEntropyLoss(reduction='none') def forward(self, logits: 'torch.Tensor', targets: 'torch.Tensor' ) ->torch.Tensor: """Forward method. Args: logits: The raw logits from the network of shape (N,C,*) where C = number of classes , * = extra dims targets: The targets of shape (N , *). Returns: The computed loss value """ logp = self.ce(logits, targets) p = torch.exp(-logp) loss = (1 - p) ** self.gamma * logp return loss.mean() if self.reduction == 'mean' else loss.sum( ) if self.reduction == 'sum' else loss def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused__log_softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x0 = xindex % 16 x2 = xindex // 64 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp0 - tmp7 tl.store(out_ptr0 + x3, tmp8, xmask) @triton.jit def triton_per_fused__log_softmax_exp_mean_mul_neg_pow_rsub_sum_1(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 64 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex % 16 r1 = rindex // 16 tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None) tmp2 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None) tmp5 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None) tmp8 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None) tmp13 = tl.load(in_ptr1 + (r0 + 64 * r1), None) tmp16 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None) tmp20 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None) tmp24 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None) tmp1 = tl_math.exp(tmp0) tmp3 = tl_math.exp(tmp2) tmp4 = tmp1 + tmp3 tmp6 = tl_math.exp(tmp5) tmp7 = tmp4 + tmp6 tmp9 = tl_math.exp(tmp8) tmp10 = tmp7 + tmp9 tmp11 = tl_math.log(tmp10) tmp12 = tmp0 - tmp11 tmp14 = tmp12 * tmp13 tmp15 = tmp2 - tmp11 tmp17 = tmp15 * tmp16 tmp18 = tmp14 + tmp17 tmp19 = tmp5 - tmp11 tmp21 = tmp19 * tmp20 tmp22 = tmp18 + tmp21 tmp23 = tmp8 - tmp11 tmp25 = tmp23 * tmp24 tmp26 = tmp22 + tmp25 tmp27 = -tmp26 tmp28 = -tmp27 tmp29 = tl_math.exp(tmp28) tmp30 = 1.0 tmp30 - tmp29 tmp32 = tmp30 * tmp27 tmp33 = tl.broadcast_to(tmp32, [XBLOCK, RBLOCK]) tmp35 = tl.sum(tmp33, 1)[:, None] tmp36 = 64.0 tmp37 = tmp35 / tmp36 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp37, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused__log_softmax_0[grid(256)](arg1_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg1_1 buf2 = empty_strided_cuda((), (), torch.float32) buf3 = buf2 del buf2 triton_per_fused__log_softmax_exp_mean_mul_neg_pow_rsub_sum_1[grid(1)]( buf3, buf0, arg0_1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1) del arg0_1 del buf0 return buf3, class FocalLossNew(nn.Module): """Implementation of Focal Loss. Focal loss was proposed in [Focal Loss for Dense Object Detection](https://arxiv.org/abs/1708.02002). """ def __init__(self, gamma=0, eps=1e-07, reduction='mean'): """Constructor Method for FocalLoss class. Args: gamma : The focal parameter. Defaults to 0. eps : Constant for computational stability. reduction: The reduction parameter for Cross Entropy Loss. """ super(FocalLossNew, self).__init__() self.gamma = gamma self.reduction = reduction self.eps = eps self.ce = torch.nn.CrossEntropyLoss(reduction='none') def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
earlbabson/torchflare
FocalLoss
false
6,632
[ "Apache-2.0" ]
1
15db06d313a53a3ec4640869335ba87730562b28
https://github.com/earlbabson/torchflare/tree/15db06d313a53a3ec4640869335ba87730562b28
EncoderUnit
import math import torch from torch import nn class ScaledDotProductAttention(nn.Module): """ Scaled Dot-Product Attention Layer Attributes ---------- softmax : nn.Functional softmax function applied at the last dimension """ def __init__(self, dropout=0.1): super(ScaledDotProductAttention, self).__init__() self.softmax = nn.Softmax(dim=-1) self.dropout = nn.Dropout(dropout) def forward(self, Q, K, V, mask=None): """ Parameters ---------- Q : 4d tensor (batch_size, h, seq_len, d_K) K : 4d tensor (batch_size, h, seq_len, d_K) V : 4d tensor (batch_size, h, seq_len, d_V) mask : 2d tensor (seq_len, seq_len) 2d binary tensor, where 1 means connection should be blocked and 0 means values can be fed forward to softmax Returns ------- 4d tensor (batch_size, h, seq_len, d_V) """ scaled = torch.matmul(Q, K.transpose_(2, 3)) scaled = scaled / math.sqrt(K.shape[3]) if mask is not None: scaled.masked_fill_(mask, float('-inf')) scaled = self.softmax(scaled) scaled = self.dropout(scaled) attn = torch.matmul(scaled, V) return attn class MultiHeadAttention(nn.Module): """ Multi-Head Attention Layer Attributes ---------- h : int number of parallel heads d_K : int dimension of features in both query and key d_V : int dimension of features in value d_model : int dimension of token embedding spd_attn: ScaledDotProductattention layer sub module to apply scaled dot product W_Q : 2d tensor (d_model, d_K * h) learned parameters used to linearly project query to Q W_K : 2d tensor (d_model, d_K * h) learned parameters used to linearly project key to K W_V : 2d tensor (d_model, d_V * h) learned parameters used to linearly project val to V W_O : 2d tensor (d_V * h, d_model) learned parameters used to linearly project scaled attention to the output tensor with the same dimension as input """ def __init__(self, h, d_model, d_K, d_V, dropout=0.1): super(MultiHeadAttention, self).__init__() self.h = h self.d_K = d_K self.d_V = d_V self.d_model = d_model self.sdp_attn = ScaledDotProductAttention(dropout=dropout) self.W_Q = nn.Parameter(torch.Tensor(d_model, d_K * h)) self.W_K = nn.Parameter(torch.Tensor(d_model, d_K * h)) self.W_V = nn.Parameter(torch.Tensor(d_model, d_V * h)) self.W_O = nn.Parameter(torch.Tensor(d_V * h, d_model)) self.dropout = nn.Dropout(dropout) self.reset_parameters() def reset_parameters(self): slope = math.sqrt(5) nn.init.kaiming_uniform_(self.W_Q, a=slope) nn.init.kaiming_uniform_(self.W_K, a=slope) nn.init.kaiming_uniform_(self.W_V, a=slope) nn.init.kaiming_uniform_(self.W_O, a=slope) def forward(self, query, key, val, mask=None): """ Parameters ---------- query : 3d tensor (batch_size, seq_len, d_model) embedded query sequence key : 3d tensor (batch_size, seq_len, d_model) embedded key sequence val : 3d tensor (batch_size, seq_len, d_model) embedded value sequence mask : 2d tensor (seq_len, seq_len) 2d binary tensor, where 1 means pass, 0 means block Returns ------- 3d tensor (batch_size, seq_len, d_model) """ h, d_K, d_V, _d_model = self.h, self.d_K, self.d_V, self.d_model W_Q, W_K, W_V, W_O = self.W_Q, self.W_K, self.W_V, self.W_O bs_q, l_q = query.shape[0], query.shape[1] bs_k, l_k = key.shape[0], key.shape[1] bs_v, l_v = val.shape[0], val.shape[1] Q = torch.matmul(query, W_Q) K = torch.matmul(key, W_K) V = torch.matmul(val, W_V) Q = Q.view(bs_q, l_q, h, d_K) K = K.view(bs_k, l_k, h, d_K) V = V.view(bs_v, l_v, h, d_V) Q.transpose_(1, 2) K.transpose_(1, 2) V.transpose_(1, 2) head = self.sdp_attn(Q, K, V, mask) head.transpose_(1, 2) head = head.reshape(bs_q, l_q, h * d_V) res = torch.matmul(head, W_O) return self.dropout(res) class FeedForwardNetwork(nn.Module): """ Position-wise Feed-Forward Network Apply the following operation f(x) = max(0, xW1 + b1) * W2 + b2 Attributes ---------- l1 : nn.Linear (in_features=d_model, out_features=d_ff) l2 : nn.Linear (in_features=d_ff, out_features=d_model) """ def __init__(self, d_model, d_ff, dropout=0.1): """ Parameters ---------- d_model : int embedding length d_ff : int size of intermediate activation """ super(FeedForwardNetwork, self).__init__() self.l1 = nn.Linear(d_model, d_ff) self.l2 = nn.Linear(d_ff, d_model) self.dropout = nn.Dropout(dropout) def forward(self, x): x = self.l2(torch.relu(self.l1(x))) return self.dropout(x) class EncoderUnit(nn.Module): """ Encoder Unit - build block of encoder Attributes ---------- attn : MultiHeadAttention norm1 : LayerNorm ffn : FeedForwardNetwork norm2 : LayerNorm """ def __init__(self, h, d_model, d_K, d_V, d_ff, dropout=0.1): """ Parameters ---------- h : int number of attention heads d_model : int size of embedding d_K : int number of features in query and key d_V : int number of features in value d_ff : int dimension of the feed-forward network """ super(EncoderUnit, self).__init__() self.attn = MultiHeadAttention(h, d_model, d_K, d_V) self.norm1 = nn.LayerNorm(d_model) self.ffn = FeedForwardNetwork(d_model, d_ff) self.norm2 = nn.LayerNorm(d_model) def forward(self, seq): """ Parameters ---------- seq : 3d tensor (batch_size, seq_len, d_model) Returns ------- 3d tensor (batch_size, seq_len, d_model) """ a1 = self.attn(seq, seq, seq) a1 = self.norm1(seq + a1) a2 = self.ffn(a1) a2 = self.norm2(a1 + a2) return a2 def get_inputs(): return [torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'h': 4, 'd_model': 4, 'd_K': 4, 'd_V': 4, 'd_ff': 4}]
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 math from torch import 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_poi_fused_view_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tl.store(out_ptr0 + x0, tmp0, xmask) @triton.jit def triton_poi_fused_add_native_layer_norm_1(in_ptr0, in_ptr1, out_ptr0, out_ptr1, 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_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + 4 * x0, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp12 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp2 = tmp0 + tmp1 tmp5 = tmp3 + tmp4 tmp6 = tmp2 + tmp5 tmp9 = tmp7 + tmp8 tmp10 = tmp6 + tmp9 tmp13 = tmp11 + tmp12 tmp14 = tmp10 + tmp13 tmp15 = 4.0 tmp16 = tmp14 / tmp15 tmp17 = tmp2 - tmp16 tmp18 = tmp17 * tmp17 tmp19 = tmp5 - tmp16 tmp20 = tmp19 * tmp19 tmp21 = tmp18 + tmp20 tmp22 = tmp9 - tmp16 tmp23 = tmp22 * tmp22 tmp24 = tmp21 + tmp23 tmp25 = tmp13 - tmp16 tmp26 = tmp25 * tmp25 tmp27 = tmp24 + tmp26 tmp28 = tmp27 / tmp15 tl.store(out_ptr0 + x0, tmp16, xmask) tl.store(out_ptr1 + x0, tmp28, xmask) @triton.jit def triton_poi_fused_add_native_layer_norm_2(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x2, xmask) tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last') tmp10 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last') tmp12 = tl.load(in_ptr5 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp4 = tmp2 - tmp3 tmp6 = 1e-05 tmp7 = tmp5 + tmp6 tmp8 = libdevice.rsqrt(tmp7) tmp9 = tmp4 * tmp8 tmp11 = tmp9 * tmp10 tmp13 = tmp11 + tmp12 tl.store(out_ptr0 + x2, tmp13, xmask) @triton.jit def triton_poi_fused_relu_threshold_backward_3(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 x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, 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 + x2, tmp4, xmask) tl.store(out_ptr0 + x2, tmp6, xmask) @triton.jit def triton_poi_fused_add_4(in_out_ptr0, in_ptr0, in_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_out_ptr0 + x2, xmask) tmp2 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp4 = tmp0 + tmp3 tl.store(in_out_ptr0 + x2, tmp4, xmask) @triton.jit def triton_poi_fused_native_layer_norm_5(in_ptr0, out_ptr0, out_ptr1, 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_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp6 = tmp4 + tmp5 tmp7 = 4.0 tmp8 = tmp6 / tmp7 tmp9 = tmp0 - tmp8 tmp10 = tmp9 * tmp9 tmp11 = tmp1 - tmp8 tmp12 = tmp11 * tmp11 tmp13 = tmp10 + tmp12 tmp14 = tmp3 - tmp8 tmp15 = tmp14 * tmp14 tmp16 = tmp13 + tmp15 tmp17 = tmp5 - tmp8 tmp18 = tmp17 * tmp17 tmp19 = tmp16 + tmp18 tmp20 = tmp19 / tmp7 tmp21 = 1e-05 tmp22 = tmp20 + tmp21 tmp23 = libdevice.rsqrt(tmp22) tl.store(out_ptr0 + x0, tmp8, xmask) tl.store(out_ptr1 + x0, tmp23, xmask) @triton.jit def triton_poi_fused_native_layer_norm_6(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 4 x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 - tmp1 tmp4 = tmp2 * tmp3 tmp6 = tmp4 * tmp5 tmp8 = tmp6 + tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13) = args args.clear() assert_size_stride(primals_1, (4, 16), (16, 1)) assert_size_stride(primals_2, (4, 16), (16, 1)) assert_size_stride(primals_3, (4, 16), (16, 1)) assert_size_stride(primals_4, (16, 4), (4, 1)) assert_size_stride(primals_5, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_6, (4,), (1,)) assert_size_stride(primals_7, (4,), (1,)) assert_size_stride(primals_8, (4, 4), (4, 1)) assert_size_stride(primals_9, (4,), (1,)) assert_size_stride(primals_10, (4, 4), (4, 1)) assert_size_stride(primals_11, (4,), (1,)) assert_size_stride(primals_12, (4,), (1,)) assert_size_stride(primals_13, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((16, 16), (16, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_5, (16, 4), (4, 1), 0), primals_1, out=buf0) del primals_1 buf1 = empty_strided_cuda((16, 16), (16, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_5, (16, 4), (4, 1), 0), primals_2, out=buf1) del primals_2 buf2 = empty_strided_cuda((16, 16), (16, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_5, (16, 4), (4, 1), 0), primals_3, out=buf2) del primals_3 buf3 = torch.ops.aten._scaled_dot_product_efficient_attention.default( reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 4, 16, 1), 0), reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 4, 16, 1), 0), reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 4, 16, 1), 0), None, True, scale=0.5) buf4 = buf3[0] buf5 = buf3[1] buf6 = buf3[2] buf7 = buf3[3] del buf3 buf8 = empty_strided_cuda((16, 16), (16, 1), torch.float32) get_raw_stream(0) triton_poi_fused_view_0[grid(256)](buf4, buf8, 256, XBLOCK=128, num_warps=4, num_stages=1) buf9 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(buf8, primals_4, out=buf9) buf10 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32) buf11 = empty_strided_cuda((4, 4, 1), (4, 1, 16), torch.float32) triton_poi_fused_add_native_layer_norm_1[grid(16)](primals_5, buf9, buf10, buf11, 16, XBLOCK=16, num_warps=1, num_stages=1) buf12 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_add_native_layer_norm_2[grid(64)](primals_5, buf9, buf10, buf11, primals_6, primals_7, buf12, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_7 buf13 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf12, (16, 4), (4, 1), 0), reinterpret_tensor(primals_8, (4, 4), (1, 4), 0), out=buf13) buf14 = reinterpret_tensor(buf13, (4, 4, 4), (16, 4, 1), 0) del buf13 buf20 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.bool) triton_poi_fused_relu_threshold_backward_3[grid(64)](buf14, primals_9, buf20, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_9 buf15 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf14, (16, 4), (4, 1), 0), reinterpret_tensor(primals_10, (4, 4), (1, 4), 0), out=buf15) buf16 = reinterpret_tensor(buf15, (4, 4, 4), (16, 4, 1), 0) del buf15 triton_poi_fused_add_4[grid(64)](buf16, buf12, primals_11, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_11 buf17 = buf11 del buf11 buf18 = buf10 del buf10 triton_poi_fused_native_layer_norm_5[grid(16)](buf16, buf17, buf18, 16, XBLOCK=16, num_warps=1, num_stages=1) buf19 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_native_layer_norm_6[grid(64)](buf16, buf17, buf18, primals_12, primals_13, buf19, 64, XBLOCK=64, num_warps=1, num_stages=1) del buf17 del buf18 del primals_13 return buf19, primals_5, primals_6, primals_12, reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 4, 16, 1), 0), reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 4, 16, 1), 0), reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 4, 16, 1), 0), buf4, buf5, buf6, buf7, buf9, reinterpret_tensor(buf12, (16, 4), (4, 1), 0), reinterpret_tensor(buf14, (16, 4), (4, 1), 0 ), buf16, primals_10, buf20, primals_8, reinterpret_tensor(buf8, ( 16, 16), (1, 16), 0), reinterpret_tensor(primals_4, (4, 16), (1, 4), 0) class ScaledDotProductAttention(nn.Module): """ Scaled Dot-Product Attention Layer Attributes ---------- softmax : nn.Functional softmax function applied at the last dimension """ def __init__(self, dropout=0.1): super(ScaledDotProductAttention, self).__init__() self.softmax = nn.Softmax(dim=-1) self.dropout = nn.Dropout(dropout) def forward(self, Q, K, V, mask=None): """ Parameters ---------- Q : 4d tensor (batch_size, h, seq_len, d_K) K : 4d tensor (batch_size, h, seq_len, d_K) V : 4d tensor (batch_size, h, seq_len, d_V) mask : 2d tensor (seq_len, seq_len) 2d binary tensor, where 1 means connection should be blocked and 0 means values can be fed forward to softmax Returns ------- 4d tensor (batch_size, h, seq_len, d_V) """ scaled = torch.matmul(Q, K.transpose_(2, 3)) scaled = scaled / math.sqrt(K.shape[3]) if mask is not None: scaled.masked_fill_(mask, float('-inf')) scaled = self.softmax(scaled) scaled = self.dropout(scaled) attn = torch.matmul(scaled, V) return attn class MultiHeadAttention(nn.Module): """ Multi-Head Attention Layer Attributes ---------- h : int number of parallel heads d_K : int dimension of features in both query and key d_V : int dimension of features in value d_model : int dimension of token embedding spd_attn: ScaledDotProductattention layer sub module to apply scaled dot product W_Q : 2d tensor (d_model, d_K * h) learned parameters used to linearly project query to Q W_K : 2d tensor (d_model, d_K * h) learned parameters used to linearly project key to K W_V : 2d tensor (d_model, d_V * h) learned parameters used to linearly project val to V W_O : 2d tensor (d_V * h, d_model) learned parameters used to linearly project scaled attention to the output tensor with the same dimension as input """ def __init__(self, h, d_model, d_K, d_V, dropout=0.1): super(MultiHeadAttention, self).__init__() self.h = h self.d_K = d_K self.d_V = d_V self.d_model = d_model self.sdp_attn = ScaledDotProductAttention(dropout=dropout) self.W_Q = nn.Parameter(torch.Tensor(d_model, d_K * h)) self.W_K = nn.Parameter(torch.Tensor(d_model, d_K * h)) self.W_V = nn.Parameter(torch.Tensor(d_model, d_V * h)) self.W_O = nn.Parameter(torch.Tensor(d_V * h, d_model)) self.dropout = nn.Dropout(dropout) self.reset_parameters() def reset_parameters(self): slope = math.sqrt(5) nn.init.kaiming_uniform_(self.W_Q, a=slope) nn.init.kaiming_uniform_(self.W_K, a=slope) nn.init.kaiming_uniform_(self.W_V, a=slope) nn.init.kaiming_uniform_(self.W_O, a=slope) def forward(self, query, key, val, mask=None): """ Parameters ---------- query : 3d tensor (batch_size, seq_len, d_model) embedded query sequence key : 3d tensor (batch_size, seq_len, d_model) embedded key sequence val : 3d tensor (batch_size, seq_len, d_model) embedded value sequence mask : 2d tensor (seq_len, seq_len) 2d binary tensor, where 1 means pass, 0 means block Returns ------- 3d tensor (batch_size, seq_len, d_model) """ h, d_K, d_V, _d_model = self.h, self.d_K, self.d_V, self.d_model W_Q, W_K, W_V, W_O = self.W_Q, self.W_K, self.W_V, self.W_O bs_q, l_q = query.shape[0], query.shape[1] bs_k, l_k = key.shape[0], key.shape[1] bs_v, l_v = val.shape[0], val.shape[1] Q = torch.matmul(query, W_Q) K = torch.matmul(key, W_K) V = torch.matmul(val, W_V) Q = Q.view(bs_q, l_q, h, d_K) K = K.view(bs_k, l_k, h, d_K) V = V.view(bs_v, l_v, h, d_V) Q.transpose_(1, 2) K.transpose_(1, 2) V.transpose_(1, 2) head = self.sdp_attn(Q, K, V, mask) head.transpose_(1, 2) head = head.reshape(bs_q, l_q, h * d_V) res = torch.matmul(head, W_O) return self.dropout(res) class FeedForwardNetwork(nn.Module): """ Position-wise Feed-Forward Network Apply the following operation f(x) = max(0, xW1 + b1) * W2 + b2 Attributes ---------- l1 : nn.Linear (in_features=d_model, out_features=d_ff) l2 : nn.Linear (in_features=d_ff, out_features=d_model) """ def __init__(self, d_model, d_ff, dropout=0.1): """ Parameters ---------- d_model : int embedding length d_ff : int size of intermediate activation """ super(FeedForwardNetwork, self).__init__() self.l1 = nn.Linear(d_model, d_ff) self.l2 = nn.Linear(d_ff, d_model) self.dropout = nn.Dropout(dropout) def forward(self, x): x = self.l2(torch.relu(self.l1(x))) return self.dropout(x) class EncoderUnitNew(nn.Module): """ Encoder Unit - build block of encoder Attributes ---------- attn : MultiHeadAttention norm1 : LayerNorm ffn : FeedForwardNetwork norm2 : LayerNorm """ def __init__(self, h, d_model, d_K, d_V, d_ff, dropout=0.1): """ Parameters ---------- h : int number of attention heads d_model : int size of embedding d_K : int number of features in query and key d_V : int number of features in value d_ff : int dimension of the feed-forward network """ super(EncoderUnitNew, self).__init__() self.attn = MultiHeadAttention(h, d_model, d_K, d_V) self.norm1 = nn.LayerNorm(d_model) self.ffn = FeedForwardNetwork(d_model, d_ff) self.norm2 = nn.LayerNorm(d_model) def forward(self, input_0): primals_1 = self.attn.W_Q primals_2 = self.attn.W_K primals_3 = self.attn.W_V primals_4 = self.attn.W_O primals_6 = self.norm1.weight primals_7 = self.norm1.bias primals_8 = self.ffn.l1.weight primals_9 = self.ffn.l1.bias primals_10 = self.ffn.l2.weight primals_11 = self.ffn.l2.bias primals_12 = self.norm2.weight primals_13 = self.norm2.bias primals_5 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13]) return output[0]
dugusword/transformer
EncoderUnit
false
6,633
[ "MIT" ]
1
7aa10968f0e60d545bbd17f1f8c1dfb7ee88c62b
https://github.com/dugusword/transformer/tree/7aa10968f0e60d545bbd17f1f8c1dfb7ee88c62b
SqueezeInitBlock
import torch import torch.nn as nn import torch.utils.data class SqueezeInitBlock(nn.Module): """ SqueezeNet specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. kernel_size : int or tuple/list of 2 int Convolution window size. """ def __init__(self, in_channels, out_channels, kernel_size): super(SqueezeInitBlock, self).__init__() self.conv = nn.Conv2d(in_channels=in_channels, out_channels= out_channels, kernel_size=kernel_size, stride=2) self.activ = nn.ReLU(inplace=True) def forward(self, x): x = self.conv(x) x = self.activ(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'out_channels': 4, 'kernel_size': 4}]
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 torch.nn as nn import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_convolution_relu_threshold_backward_0(in_out_ptr0, 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 x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, 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 + x2, tmp4, xmask) tl.store(out_ptr0 + x2, tmp6, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(2, 2), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 4, 1, 1), (4, 1, 1, 1)) buf1 = buf0 del buf0 buf2 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.bool) get_raw_stream(0) triton_poi_fused_convolution_relu_threshold_backward_0[grid(16)](buf1, primals_2, buf2, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_2 return buf1, primals_1, primals_3, buf2 class SqueezeInitBlockNew(nn.Module): """ SqueezeNet specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. kernel_size : int or tuple/list of 2 int Convolution window size. """ def __init__(self, in_channels, out_channels, kernel_size): super(SqueezeInitBlockNew, self).__init__() self.conv = nn.Conv2d(in_channels=in_channels, out_channels= out_channels, kernel_size=kernel_size, stride=2) self.activ = nn.ReLU(inplace=True) def forward(self, input_0): primals_1 = self.conv.weight primals_2 = self.conv.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
earhian/imgclsmob
SqueezeInitBlock
false
6,634
[ "MIT" ]
1
c87c0942420876941868c016211073dec4392e4d
https://github.com/earhian/imgclsmob/tree/c87c0942420876941868c016211073dec4392e4d
WRNBottleneck
import torch import torch.nn as nn import torch.utils.data def wrn_conv1x1(in_channels, out_channels, stride, activate): """ 1x1 version of the WRN specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple/list of 2 int Strides of the convolution. activate : bool Whether activate the convolution block. """ return WRNConv(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride, padding=0, activate=activate) def wrn_conv3x3(in_channels, out_channels, stride, activate): """ 3x3 version of the WRN specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple/list of 2 int Strides of the convolution. activate : bool Whether activate the convolution block. """ return WRNConv(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=stride, padding=1, activate=activate) class WRNConv(nn.Module): """ WRN specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. kernel_size : int or tuple/list of 2 int Convolution window size. stride : int or tuple/list of 2 int Strides of the convolution. padding : int or tuple/list of 2 int Padding value for convolution layer. activate : bool Whether activate the convolution block. """ def __init__(self, in_channels, out_channels, kernel_size, stride, padding, activate): super(WRNConv, self).__init__() self.activate = activate self.conv = nn.Conv2d(in_channels=in_channels, out_channels= out_channels, kernel_size=kernel_size, stride=stride, padding= padding, bias=True) if self.activate: self.activ = nn.ReLU(inplace=True) def forward(self, x): x = self.conv(x) if self.activate: x = self.activ(x) return x class WRNBottleneck(nn.Module): """ WRN bottleneck block for residual path in WRN unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple/list of 2 int Strides of the convolution. width_factor : float Wide scale factor for width of layers. """ def __init__(self, in_channels, out_channels, stride, width_factor): super(WRNBottleneck, self).__init__() mid_channels = int(round(out_channels // 4 * width_factor)) self.conv1 = wrn_conv1x1(in_channels=in_channels, out_channels= mid_channels, stride=1, activate=True) self.conv2 = wrn_conv3x3(in_channels=mid_channels, out_channels= mid_channels, stride=stride, activate=True) self.conv3 = wrn_conv1x1(in_channels=mid_channels, out_channels= out_channels, stride=1, activate=False) def forward(self, x): x = self.conv1(x) x = self.conv2(x) x = self.conv3(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'out_channels': 4, 'stride': 1, 'width_factor': 4}]
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 torch.nn as nn import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride @triton.jit def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 16 % 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) tl.store(in_out_ptr0 + x3, tmp4, xmask) @triton.jit def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 16 % 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, primals_5, primals_6, primals_7) = args args.clear() assert_size_stride(primals_1, (4, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (4, 4, 3, 3), (36, 9, 3, 1)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (4, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_7, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_relu_0[grid(256)](buf1, primals_2, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 buf2 = extern_kernels.convolution(buf1, primals_4, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf2, (4, 4, 4, 4), (64, 16, 4, 1)) buf3 = buf2 del buf2 triton_poi_fused_convolution_relu_0[grid(256)](buf3, primals_5, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_5 buf4 = extern_kernels.convolution(buf3, primals_6, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf4, (4, 4, 4, 4), (64, 16, 4, 1)) buf5 = buf4 del buf4 triton_poi_fused_convolution_1[grid(256)](buf5, primals_7, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_7 return buf5, primals_1, primals_3, primals_4, primals_6, buf1, buf3 def wrn_conv1x1(in_channels, out_channels, stride, activate): """ 1x1 version of the WRN specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple/list of 2 int Strides of the convolution. activate : bool Whether activate the convolution block. """ return WRNConv(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride, padding=0, activate=activate) def wrn_conv3x3(in_channels, out_channels, stride, activate): """ 3x3 version of the WRN specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple/list of 2 int Strides of the convolution. activate : bool Whether activate the convolution block. """ return WRNConv(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=stride, padding=1, activate=activate) class WRNConv(nn.Module): """ WRN specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. kernel_size : int or tuple/list of 2 int Convolution window size. stride : int or tuple/list of 2 int Strides of the convolution. padding : int or tuple/list of 2 int Padding value for convolution layer. activate : bool Whether activate the convolution block. """ def __init__(self, in_channels, out_channels, kernel_size, stride, padding, activate): super(WRNConv, self).__init__() self.activate = activate self.conv = nn.Conv2d(in_channels=in_channels, out_channels= out_channels, kernel_size=kernel_size, stride=stride, padding= padding, bias=True) if self.activate: self.activ = nn.ReLU(inplace=True) def forward(self, x): x = self.conv(x) if self.activate: x = self.activ(x) return x class WRNBottleneckNew(nn.Module): """ WRN bottleneck block for residual path in WRN unit. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple/list of 2 int Strides of the convolution. width_factor : float Wide scale factor for width of layers. """ def __init__(self, in_channels, out_channels, stride, width_factor): super(WRNBottleneckNew, self).__init__() mid_channels = int(round(out_channels // 4 * width_factor)) self.conv1 = wrn_conv1x1(in_channels=in_channels, out_channels= mid_channels, stride=1, activate=True) self.conv2 = wrn_conv3x3(in_channels=mid_channels, out_channels= mid_channels, stride=stride, activate=True) self.conv3 = wrn_conv1x1(in_channels=mid_channels, out_channels= out_channels, stride=1, activate=False) def forward(self, input_0): primals_1 = self.conv1.conv.weight primals_2 = self.conv1.conv.bias primals_4 = self.conv2.conv.weight primals_5 = self.conv2.conv.bias primals_6 = self.conv3.conv.weight primals_7 = self.conv3.conv.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0]
earhian/imgclsmob
WRNBottleneck
false
6,635
[ "MIT" ]
1
c87c0942420876941868c016211073dec4392e4d
https://github.com/earhian/imgclsmob/tree/c87c0942420876941868c016211073dec4392e4d
SSE
import torch import torch.nn as nn class SSE(nn.Module): """SSE : Channel Squeeze and Spatial Excitation block. Paper : <https://arxiv.org/abs/1803.02579> Adapted from <https://www.kaggle.com/c/tgs-salt-identification-challenge/discussion/66178> """ def __init__(self, in_channels): """Constructor method for SSE class. Args: in_channels : The number of input channels in the feature map. """ super(SSE, self).__init__() self.in_channels = in_channels self.conv = nn.Conv2d(in_channels=self.in_channels, out_channels=1, kernel_size=1, stride=1) def forward(self, x) ->torch.Tensor: """Forward Method. Args: x: The input tensor of shape (batch, channels, height, width) Returns: Tensor of same shape """ x_inp = x x = self.conv(x) x = torch.sigmoid(x) x = torch.mul(x_inp, x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_channels': 4}]
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 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 @triton.jit def triton_poi_fused_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 64 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 = tl.load(in_ptr0 + 0) tmp2 = tl.broadcast_to(tmp1, [XBLOCK]) tmp3 = tmp0 + tmp2 tl.store(in_out_ptr0 + x0, tmp3, xmask) @triton.jit def triton_poi_fused_mul_sigmoid_1(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x0 = xindex % 16 x2 = xindex // 64 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr1 + (x0 + 16 * x2), xmask, eviction_policy= 'evict_last') tmp2 = tl.sigmoid(tmp1) tmp3 = tmp0 * tmp2 tl.store(out_ptr0 + x3, tmp3, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (1, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_3, (1,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 1, 4, 4), (16, 16, 4, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_0[grid(64)](buf1, primals_3, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_3 buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_mul_sigmoid_1[grid(256)](primals_1, buf1, buf2, 256, XBLOCK=256, num_warps=4, num_stages=1) return buf2, primals_1, primals_2, buf1 class SSENew(nn.Module): """SSE : Channel Squeeze and Spatial Excitation block. Paper : <https://arxiv.org/abs/1803.02579> Adapted from <https://www.kaggle.com/c/tgs-salt-identification-challenge/discussion/66178> """ def __init__(self, in_channels): """Constructor method for SSE class. Args: in_channels : The number of input channels in the feature map. """ super(SSENew, self).__init__() self.in_channels = in_channels self.conv = nn.Conv2d(in_channels=self.in_channels, out_channels=1, kernel_size=1, stride=1) def forward(self, input_0): primals_2 = self.conv.weight primals_3 = self.conv.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
earlbabson/torchflare
SSE
false
6,636
[ "Apache-2.0" ]
1
15db06d313a53a3ec4640869335ba87730562b28
https://github.com/earlbabson/torchflare/tree/15db06d313a53a3ec4640869335ba87730562b28
WRNInitBlock
import torch import torch.nn as nn import torch.utils.data class WRNConv(nn.Module): """ WRN specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. kernel_size : int or tuple/list of 2 int Convolution window size. stride : int or tuple/list of 2 int Strides of the convolution. padding : int or tuple/list of 2 int Padding value for convolution layer. activate : bool Whether activate the convolution block. """ def __init__(self, in_channels, out_channels, kernel_size, stride, padding, activate): super(WRNConv, self).__init__() self.activate = activate self.conv = nn.Conv2d(in_channels=in_channels, out_channels= out_channels, kernel_size=kernel_size, stride=stride, padding= padding, bias=True) if self.activate: self.activ = nn.ReLU(inplace=True) def forward(self, x): x = self.conv(x) if self.activate: x = self.activ(x) return x class WRNInitBlock(nn.Module): """ WRN specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. """ def __init__(self, in_channels, out_channels): super(WRNInitBlock, self).__init__() self.conv = WRNConv(in_channels=in_channels, out_channels= out_channels, kernel_size=7, stride=2, padding=3, activate=True) self.pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) def forward(self, x): x = self.conv(x) x = self.pool(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'out_channels': 4}]
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 torch.nn as nn import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_convolution_relu_0(in_out_ptr0, in_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) tl.store(in_out_ptr0 + x3, tmp4, xmask) @triton.jit def triton_poi_fused_max_pool2d_with_indices_1(in_ptr0, out_ptr0, out_ptr1, 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.full([1], -1, tl.int64) tmp1 = tl.full([1], 0, tl.int64) tmp2 = tmp0 >= tmp1 tmp3 = tl.full([1], 2, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tmp2 & tmp4 tmp6 = tmp5 & tmp5 tmp7 = tl.load(in_ptr0 + (-3 + 4 * x0), tmp6 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp8 = tmp1 >= tmp1 tmp9 = tmp1 < tmp3 tmp10 = tmp8 & tmp9 tmp11 = tmp5 & tmp10 tmp12 = tl.load(in_ptr0 + (-2 + 4 * x0), tmp11 & xmask, eviction_policy ='evict_last', other=float('-inf')) tmp13 = triton_helpers.maximum(tmp12, tmp7) tmp14 = tl.full([1], 1, tl.int64) tmp15 = tmp14 >= tmp1 tmp16 = tmp14 < tmp3 tmp17 = tmp15 & tmp16 tmp18 = tmp5 & tmp17 tmp19 = tl.load(in_ptr0 + (-1 + 4 * x0), tmp18 & xmask, eviction_policy ='evict_last', other=float('-inf')) tmp20 = triton_helpers.maximum(tmp19, tmp13) tmp21 = tmp10 & tmp5 tmp22 = tl.load(in_ptr0 + (-1 + 4 * x0), tmp21 & xmask, eviction_policy ='evict_last', other=float('-inf')) tmp23 = triton_helpers.maximum(tmp22, tmp20) tmp24 = tmp10 & tmp10 tmp25 = tl.load(in_ptr0 + 4 * x0, tmp24 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp26 = triton_helpers.maximum(tmp25, tmp23) tmp27 = tmp10 & tmp17 tmp28 = tl.load(in_ptr0 + (1 + 4 * x0), tmp27 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp29 = triton_helpers.maximum(tmp28, tmp26) tmp30 = tmp17 & tmp5 tmp31 = tl.load(in_ptr0 + (1 + 4 * x0), tmp30 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp32 = triton_helpers.maximum(tmp31, tmp29) tmp33 = tmp17 & tmp10 tmp34 = tl.load(in_ptr0 + (2 + 4 * x0), tmp33 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp35 = triton_helpers.maximum(tmp34, tmp32) tmp36 = tmp17 & tmp17 tmp37 = tl.load(in_ptr0 + (3 + 4 * x0), tmp36 & xmask, eviction_policy= 'evict_last', other=float('-inf')) tmp38 = triton_helpers.maximum(tmp37, tmp35) tmp39 = tmp12 > tmp7 tmp40 = tl.full([1], 1, tl.int8) tmp41 = tl.full([1], 0, tl.int8) tmp42 = tl.where(tmp39, tmp40, tmp41) tmp43 = tmp19 > tmp13 tmp44 = tl.full([1], 2, tl.int8) tmp45 = tl.where(tmp43, tmp44, tmp42) tmp46 = tmp22 > tmp20 tmp47 = tl.full([1], 3, tl.int8) tmp48 = tl.where(tmp46, tmp47, tmp45) tmp49 = tmp25 > tmp23 tmp50 = tl.full([1], 4, tl.int8) tmp51 = tl.where(tmp49, tmp50, tmp48) tmp52 = tmp28 > tmp26 tmp53 = tl.full([1], 5, tl.int8) tmp54 = tl.where(tmp52, tmp53, tmp51) tmp55 = tmp31 > tmp29 tmp56 = tl.full([1], 6, tl.int8) tmp57 = tl.where(tmp55, tmp56, tmp54) tmp58 = tmp34 > tmp32 tmp59 = tl.full([1], 7, tl.int8) tmp60 = tl.where(tmp58, tmp59, tmp57) tmp61 = tmp37 > tmp35 tmp62 = tl.full([1], 8, tl.int8) tmp63 = tl.where(tmp61, tmp62, tmp60) tl.store(out_ptr0 + x0, tmp38, xmask) tl.store(out_ptr1 + x0, tmp63, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 7, 7), (196, 49, 7, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(2, 2), padding=(3, 3), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 4, 2, 2), (16, 4, 2, 1)) buf1 = buf0 del buf0 get_raw_stream(0) triton_poi_fused_convolution_relu_0[grid(64)](buf1, primals_2, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_2 buf2 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.float32) buf3 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 1, 1), torch.int8) triton_poi_fused_max_pool2d_with_indices_1[grid(16)](buf1, buf2, buf3, 16, XBLOCK=16, num_warps=1, num_stages=1) return buf2, primals_1, primals_3, buf1, buf3 class WRNConv(nn.Module): """ WRN specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. kernel_size : int or tuple/list of 2 int Convolution window size. stride : int or tuple/list of 2 int Strides of the convolution. padding : int or tuple/list of 2 int Padding value for convolution layer. activate : bool Whether activate the convolution block. """ def __init__(self, in_channels, out_channels, kernel_size, stride, padding, activate): super(WRNConv, self).__init__() self.activate = activate self.conv = nn.Conv2d(in_channels=in_channels, out_channels= out_channels, kernel_size=kernel_size, stride=stride, padding= padding, bias=True) if self.activate: self.activ = nn.ReLU(inplace=True) def forward(self, x): x = self.conv(x) if self.activate: x = self.activ(x) return x class WRNInitBlockNew(nn.Module): """ WRN specific initial block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. """ def __init__(self, in_channels, out_channels): super(WRNInitBlockNew, self).__init__() self.conv = WRNConv(in_channels=in_channels, out_channels= out_channels, kernel_size=7, stride=2, padding=3, activate=True) self.pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) def forward(self, input_0): primals_1 = self.conv.conv.weight primals_2 = self.conv.conv.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
earhian/imgclsmob
WRNInitBlock
false
6,637
[ "MIT" ]
1
c87c0942420876941868c016211073dec4392e4d
https://github.com/earhian/imgclsmob/tree/c87c0942420876941868c016211073dec4392e4d
TripletLoss
import torch import torch.nn.functional as F import torch.nn as nn def cosine_dist(x, y): """Computes Cosine Distance.""" x = F.normalize(x, dim=1) y = F.normalize(y, dim=1) dist = 2 - 2 * torch.mm(x, y.t()) return dist def euclidean_dist(x, y): """Computes Euclidean distance.""" m, n = x.size(0), y.size(0) xx = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n) yy = torch.pow(x, 2).sum(1, keepdim=True).expand(m, m).t() dist = xx + yy - 2 * torch.matmul(x, y.t()) dist = dist.clamp(min=1e-12).sqrt() return dist def hard_example_mining(distance_matrix, pos_idxs, neg_idxs): """For each anchor, find the hardest positive and negative sample. Args: distance_matrix: pair wise distance between samples, shape [N, M] pos_idxs: positive index with shape [N, M] neg_idxs: negative index with shape [N, M] Returns: dist_ap: pytorch Variable, distance(anchor, positive); shape [N] dist_an: pytorch Variable, distance(anchor, negative); shape [N] p_inds: pytorch LongTensor, with shape [N]; indices of selected hard positive samples; 0 <= p_inds[i] <= N - 1 n_inds: pytorch LongTensor, with shape [N]; indices of selected hard negative samples; 0 <= n_inds[i] <= N - 1 Note: Only consider the case in which all targets have same num of samples, thus we can cope with all anchors in parallel. """ assert len(distance_matrix.size()) == 2 dist_ap, _ = torch.max(distance_matrix * pos_idxs, dim=1) dist_an, _ = torch.min(distance_matrix * neg_idxs + pos_idxs * 99999999.0, dim=1) return dist_ap, dist_an def softmax_weights(dist, mask): max_v = torch.max(dist * mask, dim=1, keepdim=True)[0] difference = dist - max_v z = torch.sum(torch.exp(difference) * mask, dim=1, keepdim=True) + 1e-06 weights = torch.exp(difference) * mask / z return weights def weighted_example_mining(distance_matrix, pos_idxs, neg_idxs): """For each anchor, find the weighted positive and negative sample. Args: distance_matrix: pytorch Variable, pair wise distance between samples, shape [N, N] pos_idxs:positive index with shape [N, M] neg_idxs: negative index with shape [N, M] Returns: dist_ap: pytorch Variable, distance(anchor, positive); shape [N] dist_an: pytorch Variable, distance(anchor, negative); shape [N] """ assert len(distance_matrix.size()) == 2 dist_ap = distance_matrix * pos_idxs dist_an = distance_matrix * neg_idxs weights_ap = softmax_weights(dist_ap, pos_idxs) weights_an = softmax_weights(-dist_an, neg_idxs) dist_ap = torch.sum(dist_ap * weights_ap, dim=1) dist_an = torch.sum(dist_an * weights_an, dim=1) return dist_ap, dist_an class TripletLoss(nn.Module): """Computes Triplet loss.""" def __init__(self, normalize_features: 'bool'=True, margin: 'float'= None, hard_mining: 'bool'=True): """Constructor method for TripletLoss. Args: normalize_features: Whether to normalize the features. Default = True margin: The value for margin. Default = None. hard_mining: Whether to use hard sample mining. Default = True. """ super(TripletLoss, self).__init__() self.normalize_features = normalize_features self.margin = margin self.hard_mining = hard_mining def forward(self, embedding: 'torch.Tensor', targets: 'torch.Tensor' ) ->torch.Tensor: """Forward Method. Args: embedding: The output of the network. targets: The targets. Returns: The computed Triplet Loss. """ distance_matrix = cosine_dist(embedding, embedding ) if self.normalize_features else euclidean_dist(embedding, embedding) n = distance_matrix.size(0) pos_idxs = targets.view(n, 1).expand(n, n).eq(targets.view(n, 1). expand(n, n).t()).float() neg_idxs = targets.view(n, 1).expand(n, n).ne(targets.view(n, 1). expand(n, n).t()).float() if self.hard_mining: dist_ap, dist_an = hard_example_mining(distance_matrix= distance_matrix, pos_idxs=pos_idxs, neg_idxs=neg_idxs) else: dist_ap, dist_an = weighted_example_mining(distance_matrix= distance_matrix, pos_idxs=pos_idxs, neg_idxs=neg_idxs) y = dist_an.new().resize_as_(dist_an).fill_(1) if self.margin is not None and self.margin > 0: loss = F.margin_ranking_loss(dist_an, dist_ap, y, margin=self. margin) else: loss = F.soft_margin_loss(dist_an - dist_ap, y) if loss == float('Inf'): loss = F.margin_ranking_loss(dist_an, dist_ap, y, margin=0.3) return loss def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 1])] 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 libdevice import torch.nn.functional as F 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_poi_fused_div_0(in_ptr0, out_ptr0, out_ptr1, 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) tl.store(out_ptr1 + x2, tmp15, xmask) @triton.jit def triton_poi_fused_max_min_1(in_ptr0, in_ptr1, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 4 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr1 + x0, xmask) tmp5 = tl.load(in_ptr1 + 0) tmp6 = tl.broadcast_to(tmp5, [XBLOCK]) tmp10 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp13 = tl.load(in_ptr1 + 1) tmp14 = tl.broadcast_to(tmp13, [XBLOCK]) tmp19 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp22 = tl.load(in_ptr1 + 2) tmp23 = tl.broadcast_to(tmp22, [XBLOCK]) tmp28 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last' ) tmp31 = tl.load(in_ptr1 + 3) tmp32 = tl.broadcast_to(tmp31, [XBLOCK]) tmp1 = 2.0 tmp2 = tmp0 * tmp1 tmp3 = tmp1 - tmp2 tmp7 = tmp4 == tmp6 tmp8 = tmp7.to(tl.float32) tmp9 = tmp3 * tmp8 tmp11 = tmp10 * tmp1 tmp12 = tmp1 - tmp11 tmp15 = tmp4 == tmp14 tmp16 = tmp15.to(tl.float32) tmp17 = tmp12 * tmp16 tmp18 = triton_helpers.maximum(tmp9, tmp17) tmp20 = tmp19 * tmp1 tmp21 = tmp1 - tmp20 tmp24 = tmp4 == tmp23 tmp25 = tmp24.to(tl.float32) tmp26 = tmp21 * tmp25 tmp27 = triton_helpers.maximum(tmp18, tmp26) tmp29 = tmp28 * tmp1 tmp30 = tmp1 - tmp29 tmp33 = tmp4 == tmp32 tmp34 = tmp33.to(tl.float32) tmp35 = tmp30 * tmp34 tmp36 = triton_helpers.maximum(tmp27, tmp35) tmp37 = tmp4 != tmp6 tmp38 = tmp37.to(tl.float32) tmp39 = tmp3 * tmp38 tmp40 = 99999999.0 tmp41 = tmp8 * tmp40 tmp42 = tmp39 + tmp41 tmp43 = tmp4 != tmp14 tmp44 = tmp43.to(tl.float32) tmp45 = tmp12 * tmp44 tmp46 = tmp16 * tmp40 tmp47 = tmp45 + tmp46 tmp48 = triton_helpers.minimum(tmp42, tmp47) tmp49 = tmp4 != tmp23 tmp50 = tmp49.to(tl.float32) tmp51 = tmp21 * tmp50 tmp52 = tmp25 * tmp40 tmp53 = tmp51 + tmp52 tmp54 = triton_helpers.minimum(tmp48, tmp53) tmp55 = tmp4 != tmp32 tmp56 = tmp55.to(tl.float32) tmp57 = tmp30 * tmp56 tmp58 = tmp34 * tmp40 tmp59 = tmp57 + tmp58 tmp60 = triton_helpers.minimum(tmp54, tmp59) tl.store(out_ptr0 + x0, tmp36, xmask) tl.store(out_ptr1 + x0, tmp60, 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, 1), (1, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32) buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_div_0[grid(16)](arg0_1, buf0, buf1, 16, XBLOCK=16, num_warps=1, num_stages=1) del arg0_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 = empty_strided_cuda((4,), (1,), torch.float32) buf4 = empty_strided_cuda((4,), (1,), torch.float32) triton_poi_fused_max_min_1[grid(4)](buf2, arg1_1, buf3, buf4, 4, XBLOCK=4, num_warps=1, num_stages=1) del arg1_1 del buf2 buf5 = empty_strided_cuda((0,), (1,), torch.float32) return buf5, buf4, buf3 def cosine_dist(x, y): """Computes Cosine Distance.""" x = F.normalize(x, dim=1) y = F.normalize(y, dim=1) dist = 2 - 2 * torch.mm(x, y.t()) return dist def euclidean_dist(x, y): """Computes Euclidean distance.""" m, n = x.size(0), y.size(0) xx = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n) yy = torch.pow(x, 2).sum(1, keepdim=True).expand(m, m).t() dist = xx + yy - 2 * torch.matmul(x, y.t()) dist = dist.clamp(min=1e-12).sqrt() return dist def hard_example_mining(distance_matrix, pos_idxs, neg_idxs): """For each anchor, find the hardest positive and negative sample. Args: distance_matrix: pair wise distance between samples, shape [N, M] pos_idxs: positive index with shape [N, M] neg_idxs: negative index with shape [N, M] Returns: dist_ap: pytorch Variable, distance(anchor, positive); shape [N] dist_an: pytorch Variable, distance(anchor, negative); shape [N] p_inds: pytorch LongTensor, with shape [N]; indices of selected hard positive samples; 0 <= p_inds[i] <= N - 1 n_inds: pytorch LongTensor, with shape [N]; indices of selected hard negative samples; 0 <= n_inds[i] <= N - 1 Note: Only consider the case in which all targets have same num of samples, thus we can cope with all anchors in parallel. """ assert len(distance_matrix.size()) == 2 dist_ap, _ = torch.max(distance_matrix * pos_idxs, dim=1) dist_an, _ = torch.min(distance_matrix * neg_idxs + pos_idxs * 99999999.0, dim=1) return dist_ap, dist_an def softmax_weights(dist, mask): max_v = torch.max(dist * mask, dim=1, keepdim=True)[0] difference = dist - max_v z = torch.sum(torch.exp(difference) * mask, dim=1, keepdim=True) + 1e-06 weights = torch.exp(difference) * mask / z return weights def weighted_example_mining(distance_matrix, pos_idxs, neg_idxs): """For each anchor, find the weighted positive and negative sample. Args: distance_matrix: pytorch Variable, pair wise distance between samples, shape [N, N] pos_idxs:positive index with shape [N, M] neg_idxs: negative index with shape [N, M] Returns: dist_ap: pytorch Variable, distance(anchor, positive); shape [N] dist_an: pytorch Variable, distance(anchor, negative); shape [N] """ assert len(distance_matrix.size()) == 2 dist_ap = distance_matrix * pos_idxs dist_an = distance_matrix * neg_idxs weights_ap = softmax_weights(dist_ap, pos_idxs) weights_an = softmax_weights(-dist_an, neg_idxs) dist_ap = torch.sum(dist_ap * weights_ap, dim=1) dist_an = torch.sum(dist_an * weights_an, dim=1) return dist_ap, dist_an class TripletLossNew(nn.Module): """Computes Triplet loss.""" def __init__(self, normalize_features: 'bool'=True, margin: 'float'= None, hard_mining: 'bool'=True): """Constructor method for TripletLoss. Args: normalize_features: Whether to normalize the features. Default = True margin: The value for margin. Default = None. hard_mining: Whether to use hard sample mining. Default = True. """ super(TripletLossNew, self).__init__() self.normalize_features = normalize_features self.margin = margin self.hard_mining = hard_mining def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
earlbabson/torchflare
TripletLoss
false
6,638
[ "Apache-2.0" ]
1
15db06d313a53a3ec4640869335ba87730562b28
https://github.com/earlbabson/torchflare/tree/15db06d313a53a3ec4640869335ba87730562b28
DiceLoss
import torch import torch.nn as nn def calculate_segmentation_statistics(outputs: 'torch.Tensor', targets: 'torch.Tensor', class_dim: 'int'=1, threshold=None): """Compute calculate segmentation statistics. Args: outputs: torch.Tensor. targets: torch.Tensor. threshold: threshold for binarization of predictions. class_dim: indicates class dimension (K). Returns: True positives , false positives , false negatives for segmentation task. """ num_dims = len(outputs.shape) assert num_dims > 2, 'Found only two dimensions, shape should be [bs , C , ...]' assert outputs.shape == targets.shape, 'shape mismatch' if threshold is not None: outputs = (outputs > threshold).float() dims = [dim for dim in range(num_dims) if dim != class_dim] true_positives = torch.sum(outputs * targets, dim=dims) false_positives = torch.sum(outputs * (1 - targets), dim=dims) false_negatives = torch.sum(targets * (1 - outputs), dim=dims) return true_positives, false_positives, false_negatives class MetricMeter: """Base Class to structuring your metrics.""" def accumulate(self, outputs, targets): """Method to accumulate outputs and targets per the batch.""" raise NotImplementedError def compute(self): """Method to compute the metric on epoch end.""" raise NotImplementedError def reset(self): """Method to reset the accumulation lists.""" raise NotImplementedError class DiceScore(MetricMeter): """Class to compute Dice Score.""" def __init__(self, threshold: 'float'=None, class_dim: 'int'=1): """Constructor method for DiceScore. Args: threshold: threshold for binarization of predictions class_dim: indicates class dimension (K) Note: Supports only binary cases """ self.threshold = threshold self.class_dim = class_dim self.eps = 1e-20 self._outputs = [] self._targets = [] self.reset() def handle(self) ->str: """Method to get the class name. Returns: The class name """ return self.__class__.__name__.lower() def accumulate(self, outputs: 'torch.Tensor', targets: 'torch.Tensor'): """Class to accumulate the outputs and targets. Args: outputs: [N, K, ...] tensor that for each of the N samples indicates the probability of the sample belonging to each of the K num_classes. targets: binary [N, K, ...] tensor that encodes which of the K num_classes are associated with the N-th sample. """ self._outputs.append(outputs) self._targets.append(targets) def compute(self) ->torch.Tensor: """Computes the dice score. Returns: The computed Dice score. """ self._outputs = torch.cat(self._outputs) self._targets = torch.cat(self._targets) tp, fp, fn = calculate_segmentation_statistics(outputs=self. _outputs, targets=self._targets, threshold=self.threshold, class_dim=self.class_dim) union = tp + fp + fn score = (2 * tp + self.eps * (union == 0).float()) / (2 * tp + fp + fn + self.eps) return torch.mean(score) def reset(self): """Resets the accumulation lists.""" self._outputs = [] self._targets = [] class DiceLoss(nn.Module): """Implementation of Dice Loss.""" def __init__(self, class_dim=1): """Constructor method for Dice Loss. Args: class_dim: The dimension indication class. """ super(DiceLoss, self).__init__() self.dice = DiceScore(threshold=None, class_dim=class_dim) def forward(self, outputs: 'torch.Tensor', targets: 'torch.Tensor' ) ->torch.Tensor: """Forward method. Args: outputs: outputs from the net after applying activations. targets: The targets. Returns: The computed loss value. """ self.dice.reset() self.dice.accumulate(outputs=outputs, targets=targets) return 1 - self.dice.compute() def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 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 @triton.jit def triton_poi_fused_cat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tl.store(out_ptr0 + x0, tmp0, xmask) @triton.jit def triton_per_fused_mul_rsub_sum_1(in_ptr0, in_ptr1, out_ptr0, out_ptr1, out_ptr2, 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 % 16 r2 = rindex // 16 x0 = xindex tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0 + 64 * r2), xmask, other=0.0) tmp1 = tl.load(in_ptr1 + (r1 + 16 * x0 + 64 * r2), xmask, other=0.0) tmp2 = tmp0 * tmp1 tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK]) tmp5 = tl.where(xmask, tmp3, 0) tmp6 = tl.sum(tmp5, 1)[:, None] tmp7 = 1.0 tmp8 = tmp7 - tmp1 tmp9 = tmp0 * tmp8 tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK]) tmp12 = tl.where(xmask, tmp10, 0) tmp13 = tl.sum(tmp12, 1)[:, None] tmp14 = tmp7 - tmp0 tmp15 = tmp1 * tmp14 tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK]) tmp18 = tl.where(xmask, tmp16, 0) tmp19 = tl.sum(tmp18, 1)[:, None] tl.store(out_ptr0 + x0, tmp6, xmask) tl.store(out_ptr1 + x0, tmp13, xmask) tl.store(out_ptr2 + x0, tmp19, xmask) @triton.jit def triton_per_fused__to_copy_add_div_eq_mean_mul_rsub_2(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 4 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp3 = tl.load(in_ptr1 + r0, None) tmp5 = tl.load(in_ptr2 + r0, None) tmp1 = 2.0 tmp2 = tmp0 * tmp1 tmp4 = tmp0 + tmp3 tmp6 = tmp4 + tmp5 tmp7 = 0.0 tmp8 = tmp6 == tmp7 tmp9 = tmp8.to(tl.float32) tmp10 = 1e-20 tmp11 = tmp9 * tmp10 tmp12 = tmp2 + tmp11 tmp13 = tmp2 + tmp3 tmp14 = tmp13 + tmp5 tmp15 = tmp14 + tmp10 tmp16 = tmp12 / tmp15 tmp17 = tl.broadcast_to(tmp16, [XBLOCK, RBLOCK]) tmp19 = tl.sum(tmp17, 1)[:, None] tmp20 = 4.0 tmp21 = tmp19 / tmp20 tmp22 = 1.0 tmp23 = tmp22 - tmp21 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp23, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_cat_0[grid(256)](arg1_1, buf1, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg1_1 buf2 = empty_strided_cuda((4,), (1,), torch.float32) buf3 = empty_strided_cuda((4,), (1,), torch.float32) buf4 = empty_strided_cuda((4,), (1,), torch.float32) triton_per_fused_mul_rsub_sum_1[grid(4)](buf0, buf1, buf2, buf3, buf4, 4, 64, XBLOCK=1, num_warps=2, num_stages=1) buf5 = empty_strided_cuda((), (), torch.float32) buf6 = buf5 del buf5 triton_per_fused__to_copy_add_div_eq_mean_mul_rsub_2[grid(1)](buf6, buf2, buf3, buf4, 1, 4, XBLOCK=1, num_warps=2, num_stages=1) del buf2 del buf3 del buf4 return buf6, buf1, buf0 def calculate_segmentation_statistics(outputs: 'torch.Tensor', targets: 'torch.Tensor', class_dim: 'int'=1, threshold=None): """Compute calculate segmentation statistics. Args: outputs: torch.Tensor. targets: torch.Tensor. threshold: threshold for binarization of predictions. class_dim: indicates class dimension (K). Returns: True positives , false positives , false negatives for segmentation task. """ num_dims = len(outputs.shape) assert num_dims > 2, 'Found only two dimensions, shape should be [bs , C , ...]' assert outputs.shape == targets.shape, 'shape mismatch' if threshold is not None: outputs = (outputs > threshold).float() dims = [dim for dim in range(num_dims) if dim != class_dim] true_positives = torch.sum(outputs * targets, dim=dims) false_positives = torch.sum(outputs * (1 - targets), dim=dims) false_negatives = torch.sum(targets * (1 - outputs), dim=dims) return true_positives, false_positives, false_negatives class MetricMeter: """Base Class to structuring your metrics.""" def accumulate(self, outputs, targets): """Method to accumulate outputs and targets per the batch.""" raise NotImplementedError def compute(self): """Method to compute the metric on epoch end.""" raise NotImplementedError def reset(self): """Method to reset the accumulation lists.""" raise NotImplementedError class DiceScore(MetricMeter): """Class to compute Dice Score.""" def __init__(self, threshold: 'float'=None, class_dim: 'int'=1): """Constructor method for DiceScore. Args: threshold: threshold for binarization of predictions class_dim: indicates class dimension (K) Note: Supports only binary cases """ self.threshold = threshold self.class_dim = class_dim self.eps = 1e-20 self._outputs = [] self._targets = [] self.reset() def handle(self) ->str: """Method to get the class name. Returns: The class name """ return self.__class__.__name__.lower() def accumulate(self, outputs: 'torch.Tensor', targets: 'torch.Tensor'): """Class to accumulate the outputs and targets. Args: outputs: [N, K, ...] tensor that for each of the N samples indicates the probability of the sample belonging to each of the K num_classes. targets: binary [N, K, ...] tensor that encodes which of the K num_classes are associated with the N-th sample. """ self._outputs.append(outputs) self._targets.append(targets) def compute(self) ->torch.Tensor: """Computes the dice score. Returns: The computed Dice score. """ self._outputs = torch.cat(self._outputs) self._targets = torch.cat(self._targets) tp, fp, fn = calculate_segmentation_statistics(outputs=self. _outputs, targets=self._targets, threshold=self.threshold, class_dim=self.class_dim) union = tp + fp + fn score = (2 * tp + self.eps * (union == 0).float()) / (2 * tp + fp + fn + self.eps) return torch.mean(score) def reset(self): """Resets the accumulation lists.""" self._outputs = [] self._targets = [] class DiceLossNew(nn.Module): """Implementation of Dice Loss.""" def __init__(self, class_dim=1): """Constructor method for Dice Loss. Args: class_dim: The dimension indication class. """ super(DiceLossNew, self).__init__() self.dice = DiceScore(threshold=None, class_dim=class_dim) def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
earlbabson/torchflare
DiceLoss
false
6,639
[ "Apache-2.0" ]
1
15db06d313a53a3ec4640869335ba87730562b28
https://github.com/earlbabson/torchflare/tree/15db06d313a53a3ec4640869335ba87730562b28
Classifier
import torch import torch.nn as nn class Classifier(nn.Module): def __init__(self, z_dim, hidden_dim, class_dim): super().__init__() self.fc1 = nn.Linear(z_dim, hidden_dim) self.fc2 = nn.Linear(hidden_dim, class_dim) self.softplus = nn.Softplus() self.softmax = nn.Softmax(dim=1) def forward(self, z): hidden = self.softplus(self.fc1(z)) scores = self.softmax(self.fc2(hidden)) return scores def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'z_dim': 4, 'hidden_dim': 4, 'class_dim': 4}]
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, 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_poi_fused_softplus_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 1.0 tmp2 = tmp0 * tmp1 tmp3 = 20.0 tmp4 = tmp2 > tmp3 tmp5 = tl_math.exp(tmp2) tmp6 = libdevice.log1p(tmp5) tmp7 = tmp6 * tmp1 tmp8 = tl.where(tmp4, tmp0, tmp7) tl.store(out_ptr0 + x0, tmp8, xmask) @triton.jit def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x0 = xindex % 16 x2 = xindex // 64 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp3 = triton_helpers.maximum(tmp1, tmp2) tmp5 = triton_helpers.maximum(tmp3, tmp4) tmp7 = triton_helpers.maximum(tmp5, tmp6) tmp8 = tmp0 - tmp7 tmp9 = tl_math.exp(tmp8) tl.store(out_ptr0 + x3, tmp9, xmask) @triton.jit def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x0 = xindex % 16 x2 = xindex // 64 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy= 'evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tl.store(out_ptr0 + x3, tmp8, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0 ), alpha=1, beta=1, out=buf0) del primals_1 del primals_2 buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_softplus_0[grid(256)](buf0, buf1, 256, XBLOCK=256, num_warps=4, num_stages=1) buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_5, reinterpret_tensor(buf1, (64, 4), ( 4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf2) del primals_5 buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused__softmax_1[grid(256)](buf2, buf3, 256, XBLOCK=128, num_warps=4, num_stages=1) buf4 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf2 triton_poi_fused__softmax_2[grid(256)](buf3, buf4, 256, XBLOCK=256, num_warps=4, num_stages=1) del buf3 return buf4, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), buf0, reinterpret_tensor(buf1, (64, 4), (4, 1), 0), buf4, primals_4 class ClassifierNew(nn.Module): def __init__(self, z_dim, hidden_dim, class_dim): super().__init__() self.fc1 = nn.Linear(z_dim, hidden_dim) self.fc2 = nn.Linear(hidden_dim, class_dim) self.softplus = nn.Softplus() self.softmax = nn.Softmax(dim=1) def forward(self, input_0): primals_1 = self.fc1.weight primals_2 = self.fc1.bias primals_4 = self.fc2.weight primals_5 = self.fc2.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
einbandi/samplednn
Classifier
false
6,640
[ "MIT" ]
1
3525e46ab5096a569dde40e5a10d6ee05128ec7d
https://github.com/einbandi/samplednn/tree/3525e46ab5096a569dde40e5a10d6ee05128ec7d
IOULoss
import torch import torch.nn as nn def calculate_segmentation_statistics(outputs: 'torch.Tensor', targets: 'torch.Tensor', class_dim: 'int'=1, threshold=None): """Compute calculate segmentation statistics. Args: outputs: torch.Tensor. targets: torch.Tensor. threshold: threshold for binarization of predictions. class_dim: indicates class dimension (K). Returns: True positives , false positives , false negatives for segmentation task. """ num_dims = len(outputs.shape) assert num_dims > 2, 'Found only two dimensions, shape should be [bs , C , ...]' assert outputs.shape == targets.shape, 'shape mismatch' if threshold is not None: outputs = (outputs > threshold).float() dims = [dim for dim in range(num_dims) if dim != class_dim] true_positives = torch.sum(outputs * targets, dim=dims) false_positives = torch.sum(outputs * (1 - targets), dim=dims) false_negatives = torch.sum(targets * (1 - outputs), dim=dims) return true_positives, false_positives, false_negatives class MetricMeter: """Base Class to structuring your metrics.""" def accumulate(self, outputs, targets): """Method to accumulate outputs and targets per the batch.""" raise NotImplementedError def compute(self): """Method to compute the metric on epoch end.""" raise NotImplementedError def reset(self): """Method to reset the accumulation lists.""" raise NotImplementedError class IOU(MetricMeter): """Class which computes intersection over union.""" def __init__(self, threshold: 'float'=None, class_dim: 'int'=1): """Constructor method for IOU. Args: threshold: threshold for binarization of predictions class_dim: indicates class dimension (K) Note: Supports only binary cases """ self.threshold = threshold self.class_dim = class_dim self.eps = 1e-20 self._outputs = [] self._targets = [] self.reset() def handle(self) ->str: """Method to get the class name. Returns: The class name """ return self.__class__.__name__.lower() def accumulate(self, outputs: 'torch.Tensor', targets: 'torch.Tensor'): """Method to accumulate the outputs and targets. Args: outputs: [N, K, ...] tensor that for each of the N samples indicates the probability of the sample belonging to each of the K num_classes. targets: binary [N, K, ...] tensor that encodes which of the K num_classes are associated with the N-th sample. """ self._outputs.append(outputs) self._targets.append(targets) def compute(self) ->torch.Tensor: """Method to Compute IOU. Returns: The computed iou. """ self._outputs = torch.cat(self._outputs) self._targets = torch.cat(self._targets) tp, fp, fn = calculate_segmentation_statistics(outputs=self. _outputs, targets=self._targets, threshold=self.threshold, class_dim=self.class_dim) union = tp + fp + fn score = (tp + self.eps * (union == 0).float()) / (tp + fp + fn + self.eps) return torch.mean(score) def reset(self): """Method to reset the accumulation lists.""" self._outputs = [] self._targets = [] class IOULoss(nn.Module): """Computes intersection over union Loss. IOULoss = 1 - iou_score """ def __init__(self, class_dim=1): """Constructor method for IOULoss. Args: class_dim: indicates class dimension (K) for outputs and targets tensors (default = 1) """ super(IOULoss, self).__init__() self.iou = IOU(threshold=None, class_dim=class_dim) def forward(self, outputs: 'torch.Tensor', targets: 'torch.Tensor' ) ->torch.Tensor: """Forward Method. Args: outputs: outputs from the net after applying activations. targets: The targets. Returns: The computed loss value. """ self.iou.reset() self.iou.accumulate(outputs=outputs, targets=targets) return 1 - self.iou.compute() def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 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 @triton.jit def triton_poi_fused_cat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tl.store(out_ptr0 + x0, tmp0, xmask) @triton.jit def triton_per_fused_mul_rsub_sum_1(in_ptr0, in_ptr1, out_ptr0, out_ptr1, out_ptr2, 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 % 16 r2 = rindex // 16 x0 = xindex tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0 + 64 * r2), xmask, other=0.0) tmp1 = tl.load(in_ptr1 + (r1 + 16 * x0 + 64 * r2), xmask, other=0.0) tmp2 = tmp0 * tmp1 tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK]) tmp5 = tl.where(xmask, tmp3, 0) tmp6 = tl.sum(tmp5, 1)[:, None] tmp7 = 1.0 tmp8 = tmp7 - tmp1 tmp9 = tmp0 * tmp8 tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK]) tmp12 = tl.where(xmask, tmp10, 0) tmp13 = tl.sum(tmp12, 1)[:, None] tmp14 = tmp7 - tmp0 tmp15 = tmp1 * tmp14 tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK]) tmp18 = tl.where(xmask, tmp16, 0) tmp19 = tl.sum(tmp18, 1)[:, None] tl.store(out_ptr0 + x0, tmp6, xmask) tl.store(out_ptr1 + x0, tmp13, xmask) tl.store(out_ptr2 + x0, tmp19, xmask) @triton.jit def triton_per_fused__to_copy_add_div_eq_mean_mul_rsub_2(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr): RBLOCK: tl.constexpr = 4 xoffset = tl.program_id(0) * XBLOCK xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[None, :] tl.full([XBLOCK, RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tl.load(in_ptr1 + r0, None) tmp3 = tl.load(in_ptr2 + r0, None) tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp5 = 0.0 tmp6 = tmp4 == tmp5 tmp7 = tmp6.to(tl.float32) tmp8 = 1e-20 tmp9 = tmp7 * tmp8 tmp10 = tmp0 + tmp9 tmp11 = tmp4 + tmp8 tmp12 = tmp10 / tmp11 tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK]) tmp15 = tl.sum(tmp13, 1)[:, None] tmp16 = 4.0 tmp17 = tmp15 / tmp16 tmp18 = 1.0 tmp19 = tmp18 - tmp17 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp19, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(256)](arg0_1, buf0, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_cat_0[grid(256)](arg1_1, buf1, 256, XBLOCK=128, num_warps=4, num_stages=1) del arg1_1 buf2 = empty_strided_cuda((4,), (1,), torch.float32) buf3 = empty_strided_cuda((4,), (1,), torch.float32) buf4 = empty_strided_cuda((4,), (1,), torch.float32) triton_per_fused_mul_rsub_sum_1[grid(4)](buf0, buf1, buf2, buf3, buf4, 4, 64, XBLOCK=1, num_warps=2, num_stages=1) buf5 = empty_strided_cuda((), (), torch.float32) buf6 = buf5 del buf5 triton_per_fused__to_copy_add_div_eq_mean_mul_rsub_2[grid(1)](buf6, buf2, buf3, buf4, 1, 4, XBLOCK=1, num_warps=2, num_stages=1) del buf2 del buf3 del buf4 return buf6, buf1, buf0 def calculate_segmentation_statistics(outputs: 'torch.Tensor', targets: 'torch.Tensor', class_dim: 'int'=1, threshold=None): """Compute calculate segmentation statistics. Args: outputs: torch.Tensor. targets: torch.Tensor. threshold: threshold for binarization of predictions. class_dim: indicates class dimension (K). Returns: True positives , false positives , false negatives for segmentation task. """ num_dims = len(outputs.shape) assert num_dims > 2, 'Found only two dimensions, shape should be [bs , C , ...]' assert outputs.shape == targets.shape, 'shape mismatch' if threshold is not None: outputs = (outputs > threshold).float() dims = [dim for dim in range(num_dims) if dim != class_dim] true_positives = torch.sum(outputs * targets, dim=dims) false_positives = torch.sum(outputs * (1 - targets), dim=dims) false_negatives = torch.sum(targets * (1 - outputs), dim=dims) return true_positives, false_positives, false_negatives class MetricMeter: """Base Class to structuring your metrics.""" def accumulate(self, outputs, targets): """Method to accumulate outputs and targets per the batch.""" raise NotImplementedError def compute(self): """Method to compute the metric on epoch end.""" raise NotImplementedError def reset(self): """Method to reset the accumulation lists.""" raise NotImplementedError class IOU(MetricMeter): """Class which computes intersection over union.""" def __init__(self, threshold: 'float'=None, class_dim: 'int'=1): """Constructor method for IOU. Args: threshold: threshold for binarization of predictions class_dim: indicates class dimension (K) Note: Supports only binary cases """ self.threshold = threshold self.class_dim = class_dim self.eps = 1e-20 self._outputs = [] self._targets = [] self.reset() def handle(self) ->str: """Method to get the class name. Returns: The class name """ return self.__class__.__name__.lower() def accumulate(self, outputs: 'torch.Tensor', targets: 'torch.Tensor'): """Method to accumulate the outputs and targets. Args: outputs: [N, K, ...] tensor that for each of the N samples indicates the probability of the sample belonging to each of the K num_classes. targets: binary [N, K, ...] tensor that encodes which of the K num_classes are associated with the N-th sample. """ self._outputs.append(outputs) self._targets.append(targets) def compute(self) ->torch.Tensor: """Method to Compute IOU. Returns: The computed iou. """ self._outputs = torch.cat(self._outputs) self._targets = torch.cat(self._targets) tp, fp, fn = calculate_segmentation_statistics(outputs=self. _outputs, targets=self._targets, threshold=self.threshold, class_dim=self.class_dim) union = tp + fp + fn score = (tp + self.eps * (union == 0).float()) / (tp + fp + fn + self.eps) return torch.mean(score) def reset(self): """Method to reset the accumulation lists.""" self._outputs = [] self._targets = [] class IOULossNew(nn.Module): """Computes intersection over union Loss. IOULoss = 1 - iou_score """ def __init__(self, class_dim=1): """Constructor method for IOULoss. Args: class_dim: indicates class dimension (K) for outputs and targets tensors (default = 1) """ super(IOULossNew, self).__init__() self.iou = IOU(threshold=None, class_dim=class_dim) def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
earlbabson/torchflare
IOULoss
false
6,641
[ "Apache-2.0" ]
1
15db06d313a53a3ec4640869335ba87730562b28
https://github.com/earlbabson/torchflare/tree/15db06d313a53a3ec4640869335ba87730562b28
MeshEdgeEmbeddingLayer
import torch import torch.utils.data import torch from torch import nn class MeshEdgeEmbeddingLayer(nn.Module): """ Very important - who said that a-c is meaningfull at first layer... """ def __init__(self, input_size, embedding_size, bias=True): super(MeshEdgeEmbeddingLayer, self).__init__() self.lin = nn.Linear(input_size, embedding_size, bias=bias) def forward(self, x): x = x.squeeze(-1) x = x.permute(0, 2, 1) return self.lin(x).permute(0, 2, 1) def get_inputs(): return [torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'input_size': 4, 'embedding_size': 4}]
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 import torch.utils.data import torch from torch import 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_poi_fused_clone_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 16 xnumel = 4 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y0 = yindex % 4 y1 = yindex // 4 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) @triton.jit def triton_poi_fused_add_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(in_out_ptr0 + x2, tmp2, xmask) def call(args): primals_1, primals_2, primals_3 = args args.clear() assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_2, (4, 4), (4, 1)) assert_size_stride(primals_3, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_clone_0[grid(16, 4)](primals_1, buf0, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) del primals_1 buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf0, (16, 4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf1) del primals_2 buf2 = reinterpret_tensor(buf1, (4, 4, 4), (16, 4, 1), 0) del buf1 triton_poi_fused_add_1[grid(64)](buf2, primals_3, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_3 return reinterpret_tensor(buf2, (4, 4, 4), (16, 1, 4), 0 ), reinterpret_tensor(buf0, (16, 4), (4, 1), 0) class MeshEdgeEmbeddingLayerNew(nn.Module): """ Very important - who said that a-c is meaningfull at first layer... """ def __init__(self, input_size, embedding_size, bias=True): super(MeshEdgeEmbeddingLayerNew, self).__init__() self.lin = nn.Linear(input_size, embedding_size, bias=bias) def forward(self, input_0): primals_2 = self.lin.weight primals_3 = self.lin.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3]) return output[0]
eldadp100/The-Mesh-Transformer
MeshEdgeEmbeddingLayer
false
6,642
[ "MIT" ]
1
b3ab18f774251feff1093040dfdcf7b836a43505
https://github.com/eldadp100/The-Mesh-Transformer/tree/b3ab18f774251feff1093040dfdcf7b836a43505
Decoder
import torch import torch.nn as nn class Decoder(nn.Module): def __init__(self, z_dim, hidden_dim, input_dim): super().__init__() self.fc1 = nn.Linear(z_dim, hidden_dim) self.fc21 = nn.Linear(hidden_dim, input_dim) self.softplus = nn.Softplus() self.sigmoid = nn.Sigmoid() def forward(self, z): hidden = self.softplus(self.fc1(z)) loc_img = self.sigmoid(self.fc21(hidden)) return loc_img def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'z_dim': 4, 'hidden_dim': 4, 'input_dim': 4}]
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 libdevice, 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_poi_fused_softplus_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 1.0 tmp2 = tmp0 * tmp1 tmp3 = 20.0 tmp4 = tmp2 > tmp3 tmp5 = tl_math.exp(tmp2) tmp6 = libdevice.log1p(tmp5) tmp7 = tmp6 * tmp1 tmp8 = tl.where(tmp4, tmp0, tmp7) tl.store(out_ptr0 + x0, tmp8, xmask) @triton.jit def triton_poi_fused_sigmoid_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.sigmoid(tmp2) tl.store(in_out_ptr0 + x2, tmp3, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0 ), alpha=1, beta=1, out=buf0) del primals_1 del primals_2 buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_softplus_0[grid(256)](buf0, buf1, 256, XBLOCK=256, num_warps=4, num_stages=1) buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf1, (64, 4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf2) buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf2 triton_poi_fused_sigmoid_1[grid(256)](buf3, primals_5, 256, XBLOCK= 128, num_warps=4, num_stages=1) del primals_5 return buf3, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), buf0, reinterpret_tensor(buf1, (64, 4), (4, 1), 0), buf3, primals_4 class DecoderNew(nn.Module): def __init__(self, z_dim, hidden_dim, input_dim): super().__init__() self.fc1 = nn.Linear(z_dim, hidden_dim) self.fc21 = nn.Linear(hidden_dim, input_dim) self.softplus = nn.Softplus() self.sigmoid = nn.Sigmoid() def forward(self, input_0): primals_1 = self.fc1.weight primals_2 = self.fc1.bias primals_4 = self.fc21.weight primals_5 = self.fc21.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
einbandi/samplednn
Decoder
false
6,643
[ "MIT" ]
1
3525e46ab5096a569dde40e5a10d6ee05128ec7d
https://github.com/einbandi/samplednn/tree/3525e46ab5096a569dde40e5a10d6ee05128ec7d
AuxiliaryConvolutions
import torch from torch import nn import torch.nn.functional as F from itertools import product as product import torch.optim import torch.utils.data class AuxiliaryConvolutions(nn.Module): """ Additional convolutions to produce higher-level feature maps. """ def __init__(self): super(AuxiliaryConvolutions, self).__init__() self.conv8_1 = nn.Conv2d(1024, 256, kernel_size=1, padding=0) self.conv8_2 = nn.Conv2d(256, 512, kernel_size=3, stride=2, padding=1) self.conv9_1 = nn.Conv2d(512, 128, kernel_size=1, padding=0) self.conv9_2 = nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1) self.conv10_1 = nn.Conv2d(256, 128, kernel_size=1, padding=0) self.conv10_2 = nn.Conv2d(128, 256, kernel_size=3, padding=0) self.conv11_1 = nn.Conv2d(256, 128, kernel_size=1, padding=0) self.conv11_2 = nn.Conv2d(128, 256, kernel_size=3, padding=0) self.init_conv2d() def init_conv2d(self): """ Initialize convolution parameters. """ for c in self.children(): if isinstance(c, nn.Conv2d): nn.init.xavier_uniform_(c.weight) nn.init.constant_(c.bias, 0.0) def forward(self, conv7_feats): """ Forward propagation. :param conv7_feats: lower-level conv7 feature map, a tensor of dimensions (N, 1024, 19, 19) :return: higher-level feature maps conv8_2, conv9_2, conv10_2, and conv11_2 """ out = F.relu(self.conv8_1(conv7_feats)) out = F.relu(self.conv8_2(out)) conv8_2_feats = out out = F.relu(self.conv9_1(out)) out = F.relu(self.conv9_2(out)) conv9_2_feats = out out = F.relu(self.conv10_1(out)) out = F.relu(self.conv10_2(out)) conv10_2_feats = out out = F.relu(self.conv11_1(out)) conv11_2_feats = F.relu(self.conv11_2(out)) return conv8_2_feats, conv9_2_feats, conv10_2_feats, conv11_2_feats def get_inputs(): return [torch.rand([4, 1024, 64, 64])] 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 import nn from itertools import product as product import torch.optim import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): 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] tl.full([XBLOCK, YBLOCK], True, tl.int1) x2 = xindex y3 = yindex y0 = yindex % 1024 y1 = yindex // 1024 tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), None) tl.store(out_ptr0 + (y0 + 1024 * x2 + 4194304 * y1), tmp0, None) @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 % 256 y1 = yindex // 256 tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last' ) tl.store(out_ptr0 + (y0 + 256 * x2 + 2304 * y1), tmp0, xmask) @triton.jit def triton_poi_fused_2(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): xnumel = 9 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 % 128 y1 = yindex // 128 tmp0 = tl.load(in_ptr0 + (x2 + 9 * y3), xmask, eviction_policy='evict_last' ) tl.store(out_ptr0 + (y0 + 128 * x2 + 1152 * y1), tmp0, xmask) @triton.jit def triton_poi_fused_convolution_relu_3(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 % 256 tmp0 = tl.load(in_out_ptr0 + x2, None) tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, None) @triton.jit def triton_poi_fused_convolution_relu_4(in_ptr0, in_ptr1, out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): xnumel = 1024 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 y0 = yindex % 512 y1 = yindex // 512 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 512 * x2 + 524288 * y1), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + y0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1, 1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(out_ptr0 + (x2 + 1024 * y3), tmp4, xmask) tl.store(out_ptr1 + (y0 + 512 * x2 + 524288 * y1), tmp4, xmask) @triton.jit def triton_poi_fused_convolution_relu_5(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 % 128 tmp0 = tl.load(in_out_ptr0 + x2, None) tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, None) @triton.jit def triton_poi_fused_convolution_relu_6(in_ptr0, in_ptr1, out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): xnumel = 256 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 y0 = yindex % 256 y1 = yindex // 256 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 256 * x2 + 65536 * y1), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + y0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1, 1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(out_ptr0 + (x2 + 256 * y3), tmp4, xmask) tl.store(out_ptr1 + (y0 + 256 * x2 + 65536 * y1), tmp4, xmask) @triton.jit def triton_poi_fused_convolution_relu_7(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 % 128 tmp0 = tl.load(in_out_ptr0 + x2, None) tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, None) @triton.jit def triton_poi_fused_convolution_relu_8(in_ptr0, in_ptr1, out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): xnumel = 196 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 y0 = yindex % 256 y1 = yindex // 256 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 256 * x2 + 50176 * y1), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + y0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1, 1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(out_ptr0 + (x2 + 196 * y3), tmp4, xmask) tl.store(out_ptr1 + (y0 + 256 * x2 + 50176 * y1), tmp4, xmask) @triton.jit def triton_poi_fused_convolution_relu_9(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 % 128 tmp0 = tl.load(in_out_ptr0 + x2, None) tmp1 = tl.load(in_ptr0 + x0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, None) @triton.jit def triton_poi_fused_convolution_relu_threshold_backward_10(in_ptr0, in_ptr1, out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr): xnumel = 144 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 y0 = yindex % 256 y1 = yindex // 256 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 256 * x2 + 36864 * y1), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + y0, None, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1, 1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp5 = 0.0 tmp6 = tmp4 <= tmp5 tl.store(out_ptr0 + (x2 + 144 * y3), tmp4, xmask) tl.store(out_ptr1 + (y0 + 256 * x2 + 36864 * y1), tmp6, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13, primals_14, primals_15, primals_16, primals_17) = args args.clear() assert_size_stride(primals_1, (256, 1024, 1, 1), (1024, 1, 1, 1)) assert_size_stride(primals_2, (256,), (1,)) assert_size_stride(primals_3, (4, 1024, 64, 64), (4194304, 4096, 64, 1)) assert_size_stride(primals_4, (512, 256, 3, 3), (2304, 9, 3, 1)) assert_size_stride(primals_5, (512,), (1,)) assert_size_stride(primals_6, (128, 512, 1, 1), (512, 1, 1, 1)) assert_size_stride(primals_7, (128,), (1,)) assert_size_stride(primals_8, (256, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_9, (256,), (1,)) assert_size_stride(primals_10, (128, 256, 1, 1), (256, 1, 1, 1)) assert_size_stride(primals_11, (128,), (1,)) assert_size_stride(primals_12, (256, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_13, (256,), (1,)) assert_size_stride(primals_14, (128, 256, 1, 1), (256, 1, 1, 1)) assert_size_stride(primals_15, (128,), (1,)) assert_size_stride(primals_16, (256, 128, 3, 3), (1152, 9, 3, 1)) assert_size_stride(primals_17, (256,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 1024, 64, 64), (4194304, 1, 65536, 1024), torch.float32) get_raw_stream(0) triton_poi_fused_0[grid(4096, 4096)](primals_3, buf0, 4096, 4096, XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1) del primals_3 buf1 = empty_strided_cuda((512, 256, 3, 3), (2304, 1, 768, 256), torch.float32) triton_poi_fused_1[grid(131072, 9)](primals_4, buf1, 131072, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_4 buf2 = empty_strided_cuda((256, 128, 3, 3), (1152, 1, 384, 128), torch.float32) triton_poi_fused_2[grid(32768, 9)](primals_8, buf2, 32768, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_8 buf3 = empty_strided_cuda((256, 128, 3, 3), (1152, 1, 384, 128), torch.float32) triton_poi_fused_2[grid(32768, 9)](primals_12, buf3, 32768, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_12 buf4 = empty_strided_cuda((256, 128, 3, 3), (1152, 1, 384, 128), torch.float32) triton_poi_fused_2[grid(32768, 9)](primals_16, buf4, 32768, 9, XBLOCK=16, YBLOCK=64, num_warps=4, num_stages=1) del primals_16 buf5 = extern_kernels.convolution(buf0, primals_1, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf5, (4, 256, 64, 64), (1048576, 1, 16384, 256)) buf6 = buf5 del buf5 triton_poi_fused_convolution_relu_3[grid(4194304)](buf6, primals_2, 4194304, XBLOCK=512, num_warps=8, num_stages=1) del primals_2 buf7 = extern_kernels.convolution(buf6, buf1, stride=(2, 2), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf7, (4, 512, 32, 32), (524288, 1, 16384, 512)) buf8 = empty_strided_cuda((4, 512, 32, 32), (524288, 1024, 32, 1), torch.float32) buf9 = empty_strided_cuda((4, 512, 32, 32), (524288, 1, 16384, 512), torch.float32) triton_poi_fused_convolution_relu_4[grid(2048, 1024)](buf7, primals_5, buf8, buf9, 2048, 1024, XBLOCK=64, YBLOCK=64, num_warps=8, num_stages=1) del buf7 del primals_5 buf10 = extern_kernels.convolution(buf9, primals_6, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf10, (4, 128, 32, 32), (131072, 1, 4096, 128)) del buf9 buf11 = buf10 del buf10 triton_poi_fused_convolution_relu_5[grid(524288)](buf11, primals_7, 524288, XBLOCK=1024, num_warps=4, num_stages=1) del primals_7 buf12 = extern_kernels.convolution(buf11, buf2, stride=(2, 2), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf12, (4, 256, 16, 16), (65536, 1, 4096, 256)) buf13 = empty_strided_cuda((4, 256, 16, 16), (65536, 256, 16, 1), torch.float32) buf14 = empty_strided_cuda((4, 256, 16, 16), (65536, 1, 4096, 256), torch.float32) triton_poi_fused_convolution_relu_6[grid(1024, 256)](buf12, primals_9, buf13, buf14, 1024, 256, XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1) del buf12 del primals_9 buf15 = extern_kernels.convolution(buf14, primals_10, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf15, (4, 128, 16, 16), (32768, 1, 2048, 128)) del buf14 buf16 = buf15 del buf15 triton_poi_fused_convolution_relu_7[grid(131072)](buf16, primals_11, 131072, XBLOCK=512, num_warps=8, num_stages=1) del primals_11 buf17 = extern_kernels.convolution(buf16, buf3, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf17, (4, 256, 14, 14), (50176, 1, 3584, 256)) buf18 = empty_strided_cuda((4, 256, 14, 14), (50176, 196, 14, 1), torch.float32) buf19 = empty_strided_cuda((4, 256, 14, 14), (50176, 1, 3584, 256), torch.float32) triton_poi_fused_convolution_relu_8[grid(1024, 196)](buf17, primals_13, buf18, buf19, 1024, 196, XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1) del buf17 del primals_13 buf20 = extern_kernels.convolution(buf19, primals_14, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf20, (4, 128, 14, 14), (25088, 1, 1792, 128)) del buf19 buf21 = buf20 del buf20 triton_poi_fused_convolution_relu_9[grid(100352)](buf21, primals_15, 100352, XBLOCK=512, num_warps=8, num_stages=1) del primals_15 buf22 = extern_kernels.convolution(buf21, buf4, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf22, (4, 256, 12, 12), (36864, 1, 3072, 256)) buf23 = empty_strided_cuda((4, 256, 12, 12), (36864, 144, 12, 1), torch.float32) buf24 = empty_strided_cuda((4, 256, 12, 12), (36864, 1, 3072, 256), torch.bool) triton_poi_fused_convolution_relu_threshold_backward_10[grid(1024, 144) ](buf22, primals_17, buf23, buf24, 1024, 144, XBLOCK=32, YBLOCK =32, num_warps=4, num_stages=1) del buf22 del primals_17 return (buf8, buf13, buf18, buf23, primals_1, buf0, buf1, primals_6, buf2, primals_10, buf3, primals_14, buf4, buf6, buf8, buf11, buf13, buf16, buf18, buf21, buf24) class AuxiliaryConvolutionsNew(nn.Module): """ Additional convolutions to produce higher-level feature maps. """ def __init__(self): super(AuxiliaryConvolutionsNew, self).__init__() self.conv8_1 = nn.Conv2d(1024, 256, kernel_size=1, padding=0) self.conv8_2 = nn.Conv2d(256, 512, kernel_size=3, stride=2, padding=1) self.conv9_1 = nn.Conv2d(512, 128, kernel_size=1, padding=0) self.conv9_2 = nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1) self.conv10_1 = nn.Conv2d(256, 128, kernel_size=1, padding=0) self.conv10_2 = nn.Conv2d(128, 256, kernel_size=3, padding=0) self.conv11_1 = nn.Conv2d(256, 128, kernel_size=1, padding=0) self.conv11_2 = nn.Conv2d(128, 256, kernel_size=3, padding=0) self.init_conv2d() def init_conv2d(self): """ Initialize convolution parameters. """ for c in self.children(): if isinstance(c, nn.Conv2d): nn.init.xavier_uniform_(c.weight) nn.init.constant_(c.bias, 0.0) def forward(self, input_0): primals_1 = self.conv8_1.weight primals_2 = self.conv8_1.bias primals_4 = self.conv8_2.weight primals_5 = self.conv8_2.bias primals_6 = self.conv9_1.weight primals_7 = self.conv9_1.bias primals_8 = self.conv9_2.weight primals_9 = self.conv9_2.bias primals_10 = self.conv10_1.weight primals_11 = self.conv10_1.bias primals_12 = self.conv10_2.weight primals_13 = self.conv10_2.bias primals_14 = self.conv11_1.weight primals_15 = self.conv11_1.bias primals_16 = self.conv11_2.weight primals_17 = self.conv11_2.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9, primals_10, primals_11, primals_12, primals_13, primals_14, primals_15, primals_16, primals_17]) return output[0], output[1], output[2], output[3]
dee-walia20/SSD-Implementation-using-Pytorch
AuxiliaryConvolutions
false
6,644
[ "MIT" ]
1
2a7dcdcea2787f4bffd45f335819f08af2b525dd
https://github.com/dee-walia20/SSD-Implementation-using-Pytorch/tree/2a7dcdcea2787f4bffd45f335819f08af2b525dd
GELU
import torch import torch.nn as nn class GELU(nn.Module): def forward(self, x): return torch.sigmoid(1.702 * x) * x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 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 @triton.jit def triton_poi_fused_mul_sigmoid_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = 1.702 tmp2 = tmp0 * tmp1 tmp3 = tl.sigmoid(tmp2) tmp4 = tmp3 * tmp0 tl.store(out_ptr0 + x0, tmp4, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_mul_sigmoid_0[grid(256)](arg0_1, buf0, 256, XBLOCK =256, num_warps=4, num_stages=1) del arg0_1 return buf0, class GELUNew(nn.Module): def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
endaaman/augmix
GELU
false
6,645
[ "Apache-2.0" ]
1
11c86a126c7b261ca178a715763763ca22b20b81
https://github.com/endaaman/augmix/tree/11c86a126c7b261ca178a715763763ca22b20b81
Noise_injector
import torch import torch.nn as nn def truncated_normal_(tensor, mean=0, std=1): size = tensor.shape tmp = tensor.new_empty(size + (4,)).normal_() valid = (tmp < 2) & (tmp > -2) ind = valid.max(-1, keepdim=True)[1] tensor.data.copy_(tmp.gather(-1, ind).squeeze(-1)) tensor.data.mul_(std).add_(mean) def init_weights_orthogonal_normal(m): if type(m) == nn.Conv2d or type(m) == nn.ConvTranspose2d: nn.init.orthogonal_(m.weight) truncated_normal_(m.bias, mean=0, std=0.001) def weights_init(m): classname = m.__class__.__name__ if type(m) == nn.Conv2d or type(m) == nn.ConvTranspose2d: m.weight.data.normal_(0.0, 0.02) if classname.find('Linear') != -1: nn.init.xavier_uniform_(m.weight.data) m.bias.data.fill_(0) class Noise_injector(nn.Module): def __init__(self, n_hidden, z_dim, num_channels, n_channels_out, device='cpu'): super(Noise_injector, self).__init__() self.num_channels = num_channels self.n_channels_out = n_channels_out self.n_hidden = n_hidden self.z_dim = z_dim self.device = device self.residual = nn.Linear(self.z_dim, self.n_hidden) self.scale = nn.Linear(self.z_dim, self.n_hidden) self.last_layer = nn.Conv2d(self.n_hidden, self.n_channels_out, kernel_size=1) self.residual.apply(weights_init) self.scale.apply(weights_init) self.last_layer.apply(init_weights_orthogonal_normal) def forward(self, feature_map, z): """ Z is B x Z_dim and feature_map is B x C x H x W. So broadcast Z to batch_sizexlatent_dimxHxW. Behavior is exactly the same as tf.tile (verified) """ residual = self.residual(z).view(z.shape[0], self.n_hidden, 1, 1) scale = self.scale(z).view(z.shape[0], self.n_hidden, 1, 1) feature_map = (feature_map + residual) * (scale + 1e-05) return self.last_layer(feature_map) def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {'n_hidden': 4, 'z_dim': 4, 'num_channels': 4, 'n_channels_out': 4}]
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 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_poi_fused_add_mul_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 16 x1 = xindex // 16 x2 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp4 = 1e-05 tmp5 = tmp3 + tmp4 tmp6 = tmp2 * tmp5 tl.store(out_ptr0 + x2, tmp6, xmask) @triton.jit def triton_poi_fused_convolution_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 16 % 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, primals_5, primals_6, primals_7, primals_8) = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4), (4, 1)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (1,)) assert_size_stride(primals_6, (4, 4), (4, 1)) assert_size_stride(primals_7, (4, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_8, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_2, primals_3, reinterpret_tensor( primals_1, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf0) del primals_1 del primals_2 buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_5, primals_3, reinterpret_tensor( primals_4, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf1) del primals_4 del primals_5 buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_mul_0[grid(256)](primals_6, buf0, buf1, buf2, 256, XBLOCK=128, num_warps=4, num_stages=1) buf3 = extern_kernels.convolution(buf2, primals_7, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf3, (4, 4, 4, 4), (64, 16, 4, 1)) buf4 = buf3 del buf3 triton_poi_fused_convolution_1[grid(256)](buf4, primals_8, 256, XBLOCK=256, num_warps=4, num_stages=1) del primals_8 return buf4, primals_3, primals_6, primals_7, buf0, buf1, buf2 def truncated_normal_(tensor, mean=0, std=1): size = tensor.shape tmp = tensor.new_empty(size + (4,)).normal_() valid = (tmp < 2) & (tmp > -2) ind = valid.max(-1, keepdim=True)[1] tensor.data.copy_(tmp.gather(-1, ind).squeeze(-1)) tensor.data.mul_(std).add_(mean) def init_weights_orthogonal_normal(m): if type(m) == nn.Conv2d or type(m) == nn.ConvTranspose2d: nn.init.orthogonal_(m.weight) truncated_normal_(m.bias, mean=0, std=0.001) def weights_init(m): classname = m.__class__.__name__ if type(m) == nn.Conv2d or type(m) == nn.ConvTranspose2d: m.weight.data.normal_(0.0, 0.02) if classname.find('Linear') != -1: nn.init.xavier_uniform_(m.weight.data) m.bias.data.fill_(0) class Noise_injectorNew(nn.Module): def __init__(self, n_hidden, z_dim, num_channels, n_channels_out, device='cpu'): super(Noise_injectorNew, self).__init__() self.num_channels = num_channels self.n_channels_out = n_channels_out self.n_hidden = n_hidden self.z_dim = z_dim self.device = device self.residual = nn.Linear(self.z_dim, self.n_hidden) self.scale = nn.Linear(self.z_dim, self.n_hidden) self.last_layer = nn.Conv2d(self.n_hidden, self.n_channels_out, kernel_size=1) self.residual.apply(weights_init) self.scale.apply(weights_init) self.last_layer.apply(init_weights_orthogonal_normal) def forward(self, input_0, input_1): primals_1 = self.residual.weight primals_2 = self.residual.bias primals_3 = self.scale.weight primals_5 = self.scale.bias primals_7 = self.last_layer.weight primals_8 = self.last_layer.bias primals_4 = input_0 primals_6 = input_1 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8]) return output[0]
dkgupta90/CARMSS
Noise_injector
false
6,646
[ "Apache-2.0" ]
1
1f397caa39b9f504951285eff150857f7d86a7c3
https://github.com/dkgupta90/CARMSS/tree/1f397caa39b9f504951285eff150857f7d86a7c3
VoxelFeatureExtractor
import torch from torch import nn class VoxelFeatureExtractor(nn.Module): """Computes mean of non-zero points within voxel.""" def forward(self, feature, occupancy): """ :feature FloatTensor of shape (N, K, C) :return FloatTensor of shape (N, C) """ denominator = occupancy.type_as(feature).view(-1, 1) feature = (feature.sum(1) / denominator).contiguous() return feature def get_inputs(): return [torch.rand([4, 4]), torch.rand([4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 import nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_div_sum_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 4 x1 = xindex // 4 x2 = xindex tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp4 = tmp2 + tmp3 tmp6 = tmp4 + tmp5 tmp8 = tmp6 / tmp7 tl.store(out_ptr0 + x2, tmp8, 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((16, 4), (4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_div_sum_0[grid(64)](arg1_1, arg0_1, buf0, 64, XBLOCK=64, num_warps=1, num_stages=1) del arg0_1 del arg1_1 return buf0, class VoxelFeatureExtractorNew(nn.Module): """Computes mean of non-zero points within voxel.""" def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
eraofelix/PV-RCNN
VoxelFeatureExtractor
false
6,647
[ "MIT" ]
1
6361ec99cc1c92120263ef56b2c2b003c2cd7264
https://github.com/eraofelix/PV-RCNN/tree/6361ec99cc1c92120263ef56b2c2b003c2cd7264
QModReLU
import torch import torch.nn.functional as F import torch.fx class QModReLU(torch.nn.Module): """ Quaternion ModeReLU """ def __init__(self, bias=0): super().__init__() self.bias = torch.nn.Parameter(torch.Tensor([bias])) def forward(self, x): norm = x.norm() return F.relu(norm + self.bias) * (x / norm) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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.fx assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_add_div_linalg_vector_norm_mul_relu_threshold_backward_0( in_out_ptr0, in_ptr0, in_ptr1, out_ptr0, out_ptr1, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp6 = tl.load(in_ptr1 + 0) tmp7 = tl.broadcast_to(tmp6, [1]) tmp13 = tl.broadcast_to(tmp6, [RBLOCK]) tmp1 = tmp0 * tmp0 tmp2 = tl.broadcast_to(tmp1, [RBLOCK]) tmp4 = triton_helpers.promote_to_tensor(tl.sum(tmp2, 0)) tmp5 = libdevice.sqrt(tmp4) tmp8 = tmp5 + tmp7 tmp9 = tl.full([1], 0, tl.int32) tmp10 = triton_helpers.maximum(tmp9, tmp8) tmp11 = 0.0 tmp12 = tmp10 <= tmp11 tmp14 = tmp5 + tmp13 tmp15 = triton_helpers.maximum(tmp9, tmp14) tmp16 = tmp0 / tmp5 tmp17 = tmp15 * tmp16 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp5, None) tl.store(out_ptr0 + tl.full([1], 0, tl.int32), tmp12, None) tl.store(out_ptr1 + tl.broadcast_to(r0, [RBLOCK]), tmp17, None) def call(args): primals_1, primals_2 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (1,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf1 = buf0 del buf0 buf3 = empty_strided_cuda((1,), (1,), torch.bool) buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_per_fused_add_div_linalg_vector_norm_mul_relu_threshold_backward_0[ grid(1)](buf1, primals_1, primals_2, buf3, buf2, 1, 256, num_warps=2, num_stages=1) del primals_2 return buf2, primals_1, buf1, buf3 class QModReLUNew(torch.nn.Module): """ Quaternion ModeReLU """ def __init__(self, bias=0): super().__init__() self.bias = torch.nn.Parameter(torch.Tensor([bias])) def forward(self, input_0): primals_2 = self.bias primals_1 = input_0 output = call([primals_1, primals_2]) return output[0]
eleGAN23/HI2I
QModReLU
false
6,648
[ "MIT" ]
1
7730ee0963614290099b011c113048ef6d1b149c
https://github.com/eleGAN23/HI2I/tree/7730ee0963614290099b011c113048ef6d1b149c
DecoderNet
import torch import torch.nn.functional as F import torch.nn as nn class DecoderNet(nn.Module): """ The decoder takes an interpolated feature vector and turn it into the output signal. This net is intended to be very lightweight, it has only one hidden layer. """ def __init__(self, feature_size, signal_dimension, hidden_layer_size=64): """ @param feature_size dimension of an input feature vector (C) @param signal_dimension number of component in the output signal e.g. 3 or 4 for an image, 1 for a signed distance field, etc. @param hidden_layer_size number of neurons in the hidden layer """ super().__init__() self.fc1 = nn.Linear(feature_size, hidden_layer_size) self.fc2 = nn.Linear(hidden_layer_size, signal_dimension) def forward(self, x): x = self.fc1(x) x = F.relu(x) x = self.fc2(x) return x * 0.5 + 0.5 def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'feature_size': 4, 'signal_dimension': 4}]
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 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_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0, out_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 % 64 tmp0 = tl.load(in_out_ptr0 + x2, None) tmp1 = tl.load(in_ptr0 + x0, None, 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 + x2, tmp4, None) tl.store(out_ptr0 + x2, tmp6, None) @triton.jit def triton_poi_fused_add_mul_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = 0.5 tmp4 = tmp2 * tmp3 tmp5 = tmp4 + tmp3 tl.store(in_out_ptr0 + x2, tmp5, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (64, 4), (4, 1)) assert_size_stride(primals_2, (64,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (4, 64), (64, 1)) assert_size_stride(primals_5, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 64), (64, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 64), (1, 4), 0), out=buf0) del primals_1 buf1 = reinterpret_tensor(buf0, (4, 4, 4, 64), (1024, 256, 64, 1), 0) del buf0 buf4 = empty_strided_cuda((4, 4, 4, 64), (1024, 256, 64, 1), torch.bool ) get_raw_stream(0) triton_poi_fused_relu_threshold_backward_0[grid(4096)](buf1, primals_2, buf4, 4096, XBLOCK=128, num_warps=4, num_stages=1) del primals_2 buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(buf1, (64, 64), (64, 1), 0), reinterpret_tensor(primals_4, (64, 4), (1, 64), 0), out=buf2) buf3 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf2 triton_poi_fused_add_mul_1[grid(256)](buf3, primals_5, 256, XBLOCK= 128, num_warps=4, num_stages=1) del primals_5 return buf3, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), reinterpret_tensor(buf1, (64, 64), (64, 1), 0), primals_4, buf4 class DecoderNetNew(nn.Module): """ The decoder takes an interpolated feature vector and turn it into the output signal. This net is intended to be very lightweight, it has only one hidden layer. """ def __init__(self, feature_size, signal_dimension, hidden_layer_size=64): """ @param feature_size dimension of an input feature vector (C) @param signal_dimension number of component in the output signal e.g. 3 or 4 for an image, 1 for a signed distance field, etc. @param hidden_layer_size number of neurons in the hidden layer """ super().__init__() self.fc1 = nn.Linear(feature_size, hidden_layer_size) self.fc2 = nn.Linear(hidden_layer_size, signal_dimension) def forward(self, input_0): primals_1 = self.fc1.weight primals_2 = self.fc1.bias primals_4 = self.fc2.weight primals_5 = self.fc2.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
eliemichel/ReACORN
DecoderNet
false
6,649
[ "MIT" ]
1
74501551ecb387352271674efb2ed6240d234df6
https://github.com/eliemichel/ReACORN/tree/74501551ecb387352271674efb2ed6240d234df6
AlexOutputBlock
import torch import torch.nn as nn import torch.utils.data class AlexDense(nn.Module): """ AlexNet specific dense block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. """ def __init__(self, in_channels, out_channels): super(AlexDense, self).__init__() self.fc = nn.Linear(in_features=in_channels, out_features=out_channels) self.activ = nn.ReLU(inplace=True) self.dropout = nn.Dropout(p=0.5) def forward(self, x): x = self.fc(x) x = self.activ(x) x = self.dropout(x) return x class AlexOutputBlock(nn.Module): """ AlexNet specific output block. Parameters: ---------- in_channels : int Number of input channels. classes : int Number of classification classes. """ def __init__(self, in_channels, classes): super(AlexOutputBlock, self).__init__() mid_channels = 4096 self.fc1 = AlexDense(in_channels=in_channels, out_channels=mid_channels ) self.fc2 = AlexDense(in_channels=mid_channels, out_channels= mid_channels) self.fc3 = nn.Linear(in_features=mid_channels, out_features=classes) def forward(self, x): x = self.fc1(x) x = self.fc2(x) x = self.fc3(x) return x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_channels': 4, 'classes': 4}]
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 torch.nn as nn import torch.utils.data 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_relu_threshold_backward_0(in_out_ptr0, in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x4 = xindex x0 = xindex % 4096 tmp0 = tl.load(in_out_ptr0 + x4, None) tmp1 = tl.load(in_ptr0 + x0, None, 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 + x4, tmp4, None) tl.store(out_ptr0 + x4, tmp6, None) @triton.jit def triton_poi_fused_view_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x0 = xindex % 4096 x1 = xindex // 4096 x2 = xindex tmp0 = tl.load(in_ptr0 + (x0 + 4096 * x1 + 16384 * (x1 % 4 // 4) + 65536 * ((4 * (x1 // 4 % 4) + x1 % 4) // 16)), None) tl.store(out_ptr0 + x2, tmp0, None) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7) = args args.clear() assert_size_stride(primals_1, (4096, 4), (4, 1)) assert_size_stride(primals_2, (4096,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (4096, 4096), (4096, 1)) assert_size_stride(primals_5, (4096,), (1,)) assert_size_stride(primals_6, (4, 4096), (4096, 1)) assert_size_stride(primals_7, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 4096), (4096, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4096), (1, 4), 0), out=buf0) del primals_1 buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4096), (65536, 16384, 4096, 1), 0) del buf0 buf8 = empty_strided_cuda((4, 4, 4, 4096), (65536, 16384, 4096, 1), torch.bool) get_raw_stream(0) triton_poi_fused_relu_threshold_backward_0[grid(262144)](buf1, primals_2, buf8, 262144, XBLOCK=512, num_warps=8, num_stages=1) del primals_2 buf2 = empty_strided_cuda((64, 4096), (4096, 1), torch.float32) triton_poi_fused_view_1[grid(262144)](buf1, buf2, 262144, XBLOCK= 512, num_warps=8, num_stages=1) buf3 = reinterpret_tensor(buf1, (64, 4096), (4096, 1), 0) del buf1 extern_kernels.mm(buf2, reinterpret_tensor(primals_4, (4096, 4096), (1, 4096), 0), out=buf3) buf4 = reinterpret_tensor(buf3, (4, 4, 4, 4096), (65536, 16384, 4096, 1), 0) del buf3 buf7 = empty_strided_cuda((4, 4, 4, 4096), (65536, 16384, 4096, 1), torch.bool) triton_poi_fused_relu_threshold_backward_0[grid(262144)](buf4, primals_5, buf7, 262144, XBLOCK=512, num_warps=8, num_stages=1) del primals_5 buf5 = empty_strided_cuda((64, 4096), (4096, 1), torch.float32) triton_poi_fused_view_1[grid(262144)](buf4, buf5, 262144, XBLOCK= 512, num_warps=8, num_stages=1) del buf4 buf6 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_7, buf5, reinterpret_tensor(primals_6, (4096, 4), (1, 4096), 0), alpha=1, beta=1, out=buf6) del primals_7 return reinterpret_tensor(buf6, (4, 4, 4, 4), (64, 16, 4, 1), 0 ), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), buf2, buf5, primals_6, buf7, primals_4, buf8 class AlexDense(nn.Module): """ AlexNet specific dense block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. """ def __init__(self, in_channels, out_channels): super(AlexDense, self).__init__() self.fc = nn.Linear(in_features=in_channels, out_features=out_channels) self.activ = nn.ReLU(inplace=True) self.dropout = nn.Dropout(p=0.5) def forward(self, x): x = self.fc(x) x = self.activ(x) x = self.dropout(x) return x class AlexOutputBlockNew(nn.Module): """ AlexNet specific output block. Parameters: ---------- in_channels : int Number of input channels. classes : int Number of classification classes. """ def __init__(self, in_channels, classes): super(AlexOutputBlockNew, self).__init__() mid_channels = 4096 self.fc1 = AlexDense(in_channels=in_channels, out_channels=mid_channels ) self.fc2 = AlexDense(in_channels=mid_channels, out_channels= mid_channels) self.fc3 = nn.Linear(in_features=mid_channels, out_features=classes) def forward(self, input_0): primals_1 = self.fc1.fc.weight primals_2 = self.fc1.fc.bias primals_4 = self.fc2.fc.weight primals_5 = self.fc2.fc.bias primals_6 = self.fc3.weight primals_7 = self.fc3.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7]) return output[0]
earhian/imgclsmob
AlexOutputBlock
false
6,650
[ "MIT" ]
1
c87c0942420876941868c016211073dec4392e4d
https://github.com/earhian/imgclsmob/tree/c87c0942420876941868c016211073dec4392e4d
SelfAttentionLayer
import math import torch import torch.utils.data import torch from torch import nn import torch.nn.functional as F class SelfAttentionLayer(nn.Module): def __init__(self, elem_size, embd_size): super(SelfAttentionLayer, self).__init__() self.embd_size = embd_size self.query_lin = nn.Linear(elem_size, embd_size) self.key_lin = nn.Linear(elem_size, embd_size) self.softmax = nn.Softmax(dim=1) def forward(self, x): if len(x.shape) == 3: x = x.unsqueeze(1) _N, _num_patches, _seq_size, elem_size = x.shape Q = F.relu(self.query_lin(x)) K = F.relu(self.key_lin(x)) attention_mat = torch.matmul(Q, K.permute(0, 1, 3, 2)) / math.sqrt( elem_size) attention_mat = F.softmax(attention_mat, dim=-1) new_values = torch.matmul(attention_mat, x) out = new_values out = x + out return out, attention_mat def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'elem_size': 4, 'embd_size': 4}]
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 torch.utils.data import torch from torch import 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_poi_fused_relu_threshold_backward_0(in_out_ptr0, in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, 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 + x2, tmp4, xmask) tl.store(out_ptr0 + x2, tmp6, xmask) @triton.jit def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 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) tmp3 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp1 = 1.0 tmp2 = tmp0 * tmp1 tmp4 = tmp3 * tmp1 tmp6 = tmp5 * tmp1 tmp7 = triton_helpers.maximum(tmp4, tmp6) tmp9 = tmp8 * tmp1 tmp10 = triton_helpers.maximum(tmp7, tmp9) tmp12 = tmp11 * tmp1 tmp13 = triton_helpers.maximum(tmp10, tmp12) tmp14 = tmp2 - tmp13 tmp15 = 0.5 tmp16 = tmp14 * tmp15 tmp17 = tl_math.exp(tmp16) tl.store(out_ptr0 + x2, tmp17, xmask) @triton.jit def triton_poi_fused__softmax_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr ): xnumel = 256 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') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) @triton.jit def triton_poi_fused_add_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = tl.load(in_out_ptr0 + x0, xmask) tmp2 = tmp0 + tmp1 tl.store(in_out_ptr0 + x0, tmp2, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (4, 4), (4, 1)) assert_size_stride(primals_3, (4,), (1,)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0) del primals_2 buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_1, (64, 4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1) del primals_4 buf2 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf0 buf10 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) get_raw_stream(0) triton_poi_fused_relu_threshold_backward_0[grid(256)](buf2, primals_3, buf10, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_3 buf3 = reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf1 buf9 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool) triton_poi_fused_relu_threshold_backward_0[grid(256)](buf3, primals_5, buf9, 256, XBLOCK=128, num_warps=4, num_stages=1) del primals_5 buf4 = empty_strided_cuda((16, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(reinterpret_tensor(buf2, (16, 4, 4), (16, 4, 1), 0), reinterpret_tensor(buf3, (16, 4, 4), (16, 1, 4), 0), out=buf4) buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused__softmax_1[grid(256)](buf4, buf5, 256, XBLOCK=256, num_warps=4, num_stages=1) buf6 = reinterpret_tensor(buf4, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf4 triton_poi_fused__softmax_2[grid(256)](buf5, buf6, 256, XBLOCK=256, num_warps=4, num_stages=1) buf7 = reinterpret_tensor(buf5, (16, 4, 4), (16, 4, 1), 0) del buf5 extern_kernels.bmm(reinterpret_tensor(buf6, (16, 4, 4), (16, 4, 1), 0), reinterpret_tensor(primals_1, (16, 4, 4), (16, 4, 1), 0), out=buf7) buf8 = reinterpret_tensor(buf7, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf7 triton_poi_fused_add_3[grid(256)](buf8, primals_1, 256, XBLOCK=128, num_warps=4, num_stages=1) return buf8, buf6, primals_1, buf6, reinterpret_tensor(buf2, (16, 4, 4), (16, 1, 4), 0), reinterpret_tensor(buf3, (16, 4, 4), (16, 4, 1), 0 ), buf9, buf10 class SelfAttentionLayerNew(nn.Module): def __init__(self, elem_size, embd_size): super(SelfAttentionLayerNew, self).__init__() self.embd_size = embd_size self.query_lin = nn.Linear(elem_size, embd_size) self.key_lin = nn.Linear(elem_size, embd_size) self.softmax = nn.Softmax(dim=1) def forward(self, input_0): primals_2 = self.query_lin.weight primals_3 = self.query_lin.bias primals_4 = self.key_lin.weight primals_5 = self.key_lin.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0], output[1]
eldadp100/The-Mesh-Transformer
SelfAttentionLayer
false
6,651
[ "MIT" ]
1
b3ab18f774251feff1093040dfdcf7b836a43505
https://github.com/eldadp100/The-Mesh-Transformer/tree/b3ab18f774251feff1093040dfdcf7b836a43505
BatchNorm2D_noparam
import torch import torch.nn as nn class BatchNorm2D_noparam(nn.Module): def __init__(self, eps=1e-08): super(BatchNorm2D_noparam, self).__init__() self.eps = eps def forward(self, x): _bs, _c, _h, _w = x.shape mean = torch.mean(x, (0, 2, 3), keepdim=True) var = torch.var(x, (0, 2, 3), keepdim=True) out = (x - mean) / (var + self.eps) return out def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 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 @triton.jit def triton_per_fused_mean_var_0(in_ptr0, out_ptr0, out_ptr1, 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 % 16 r2 = rindex // 16 x0 = xindex tmp0 = tl.load(in_ptr0 + (r1 + 16 * x0 + 64 * r2), xmask, other=0.0) tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp3 = tl.where(xmask, tmp1, 0) tmp4 = tl.sum(tmp3, 1)[:, None] tmp6 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK]) tmp8 = tl.where(xmask, tmp6, 0) tmp9 = tl.sum(tmp8, 1)[:, None] tmp10 = tl.full([XBLOCK, 1], 64, tl.int32) tmp11 = tmp10.to(tl.float32) tmp12 = tmp9 / tmp11 tmp13 = tmp1 - tmp12 tmp14 = tmp13 * tmp13 tmp15 = tl.broadcast_to(tmp14, [XBLOCK, RBLOCK]) tmp17 = tl.where(xmask, tmp15, 0) tmp18 = tl.sum(tmp17, 1)[:, None] tl.store(out_ptr0 + x0, tmp4, xmask) tl.store(out_ptr1 + x0, tmp18, xmask) @triton.jit def triton_poi_fused_add_div_mean_sub_var_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 16 % 4 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last') tmp2 = 64.0 tmp3 = tmp1 / tmp2 tmp4 = tmp0 - tmp3 tmp6 = 63.0 tmp7 = tmp5 / tmp6 tmp8 = 1e-08 tmp9 = tmp7 + tmp8 tmp10 = tmp4 / tmp9 tl.store(out_ptr0 + x3, tmp10, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((1, 4, 1, 1), (4, 1, 4, 4), torch.float32) buf2 = empty_strided_cuda((1, 4, 1, 1), (4, 1, 4, 4), torch.float32) get_raw_stream(0) triton_per_fused_mean_var_0[grid(4)](arg0_1, buf0, buf2, 4, 64, XBLOCK=1, num_warps=2, num_stages=1) buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_add_div_mean_sub_var_1[grid(256)](arg0_1, buf0, buf2, buf4, 256, XBLOCK=256, num_warps=4, num_stages=1) del arg0_1 del buf0 del buf2 return buf4, class BatchNorm2D_noparamNew(nn.Module): def __init__(self, eps=1e-08): super(BatchNorm2D_noparamNew, self).__init__() self.eps = eps def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
ericlearning/General-I2I
BatchNorm2D_noparam
false
6,652
[ "MIT" ]
1
ba7c5d6a582bdf2e7b53c0e20c31e9097b1883a9
https://github.com/ericlearning/General-I2I/tree/ba7c5d6a582bdf2e7b53c0e20c31e9097b1883a9
CReLU
import torch import torch.nn as nn import torch.nn.functional as F class CReLU(nn.ReLU): def __init__(self): super(CReLU, self).__init__() def forward(self, input): return torch.cat((F.relu(input, self.inplace), F.relu(-input, self. inplace)), 1) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 torch.nn as nn assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_cat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 512 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 16 % 8 x0 = xindex % 16 x2 = xindex // 128 x3 = xindex tmp0 = x1 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 4, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x0 + 16 * x1 + 64 * x2), tmp4 & xmask, other=0.0) tmp6 = tl.full([1], 0, tl.int32) tmp7 = triton_helpers.maximum(tmp6, tmp5) tmp8 = tl.full(tmp7.shape, 0.0, tmp7.dtype) tmp9 = tl.where(tmp4, tmp7, tmp8) tmp10 = tmp0 >= tmp3 tl.full([1], 8, tl.int64) tmp13 = tl.load(in_ptr0 + (x0 + 16 * (-4 + x1) + 64 * x2), tmp10 & xmask, other=0.0) tmp14 = -tmp13 tmp15 = triton_helpers.maximum(tmp6, tmp14) tmp16 = tl.full(tmp15.shape, 0.0, tmp15.dtype) tmp17 = tl.where(tmp10, tmp15, tmp16) tmp18 = tl.where(tmp4, tmp9, tmp17) tl.store(out_ptr0 + x3, tmp18, xmask) def call(args): arg0_1, = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 8, 4, 4), (128, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(512)](arg0_1, buf0, 512, XBLOCK=128, num_warps=4, num_stages=1) del arg0_1 return buf0, class CReLUNew(nn.ReLU): def __init__(self): super(CReLUNew, self).__init__() def forward(self, input_0): arg0_1 = input_0 output = call([arg0_1]) return output[0]
ethancaballero/multi-agent-reinforcement-learning-for-emergent-communication
CReLU
false
6,653
[ "MIT" ]
1
426edaa1ee58b467dfc0f46fe1f83ceea26f2ed7
https://github.com/ethancaballero/multi-agent-reinforcement-learning-for-emergent-communication/tree/426edaa1ee58b467dfc0f46fe1f83ceea26f2ed7
LigthSpeechLoss
import torch from torch import nn import torch.utils.data class LigthSpeechLoss(nn.Module): """ LigthSpeech Loss """ def __init__(self): super(LigthSpeechLoss, self).__init__() def forward(self, mel, padd_predicted, cemb_out, mel_tac2_target, D, cemb): mel_loss = nn.MSELoss()(mel, mel_tac2_target) similarity_loss = nn.L1Loss()(cemb_out, cemb) duration_loss = nn.L1Loss()(padd_predicted, D.float()) return mel_loss, similarity_loss, duration_loss def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand( [4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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 from torch import nn import torch.utils.data assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_per_fused_mse_loss_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tl.load(in_ptr1 + r0, None) tmp2 = tmp0 - tmp1 tmp3 = tmp2 * tmp2 tmp4 = tl.broadcast_to(tmp3, [RBLOCK]) tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0)) tmp7 = 256.0 tmp8 = tmp6 / tmp7 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp8, None) @triton.jit def triton_per_fused_abs_mean_sub_1(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp1 = tl.load(in_ptr1 + r0, None) tmp2 = tmp0 - tmp1 tmp3 = tl_math.abs(tmp2) tmp4 = tl.broadcast_to(tmp3, [RBLOCK]) tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0)) tmp7 = 256.0 tmp8 = tmp6 / tmp7 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp8, None) def call(args): arg0_1, arg1_1, arg2_1, arg3_1, arg4_1, arg5_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg3_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg4_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg5_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf3 = buf0 del buf0 get_raw_stream(0) triton_per_fused_mse_loss_0[grid(1)](buf3, arg1_1, arg0_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 buf1 = empty_strided_cuda((), (), torch.float32) buf4 = buf1 del buf1 triton_per_fused_abs_mean_sub_1[grid(1)](buf4, arg3_1, arg2_1, 1, 256, num_warps=2, num_stages=1) del arg2_1 del arg3_1 buf2 = empty_strided_cuda((), (), torch.float32) buf5 = buf2 del buf2 triton_per_fused_abs_mean_sub_1[grid(1)](buf5, arg5_1, arg4_1, 1, 256, num_warps=2, num_stages=1) del arg4_1 del arg5_1 return buf3, buf4, buf5 class LigthSpeechLossNew(nn.Module): """ LigthSpeech Loss """ def __init__(self): super(LigthSpeechLossNew, self).__init__() def forward(self, input_0, input_1, input_2, input_3, input_4, input_5): arg0_1 = input_0 arg1_1 = input_1 arg2_1 = input_2 arg3_1 = input_3 arg4_1 = input_4 arg5_1 = input_5 output = call([arg0_1, arg1_1, arg2_1, arg3_1, arg4_1, arg5_1]) return output[0], output[1], output[2]
entn-at/LightSpeech
LigthSpeechLoss
false
6,654
[ "MIT" ]
1
48250fbcede4b258ba13ab17e3e83afc5fe85a01
https://github.com/entn-at/LightSpeech/tree/48250fbcede4b258ba13ab17e3e83afc5fe85a01
Net
import torch from torch import nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(in_channels=3, out_channels=10, kernel_size= (7, 3)) self.pool = nn.MaxPool2d(kernel_size=(1, 3)) self.conv2 = nn.Conv2d(in_channels=10, out_channels=20, kernel_size =(3, 3)) self.fc1 = nn.Linear(7 * 8 * 20, 100) self.fc2 = nn.Linear(100, 1) self.sigmoid = nn.Sigmoid() def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(7 * 8 * 20, -1) x = x.permute(1, 0) x = self.fc1(x) x = self.fc2(x) x = torch.squeeze(x) return x def get_inputs(): return [torch.rand([4, 3, 64, 64])] 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 import 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_poi_fused_convolution_relu_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 143840 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 3596 % 10 x0 = xindex % 3596 x4 = xindex // 3596 tmp0 = tl.load(in_ptr0 + x3, xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(out_ptr0 + (x0 + 3616 * x4), tmp4, xmask) @triton.jit def triton_poi_fused_max_pool2d_with_indices_1(in_ptr0, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 46400 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex % 20 x1 = xindex // 20 % 58 x2 = xindex // 1160 x3 = xindex % 1160 tmp0 = tl.load(in_ptr0 + (3 * x0 + 62 * x1 + 3616 * x2), xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 3 * x0 + 62 * x1 + 3616 * x2), xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (2 + 3 * x0 + 62 * x1 + 3616 * x2), xmask, eviction_policy='evict_last') tmp2 = triton_helpers.maximum(tmp1, tmp0) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp5 = tmp1 > tmp0 tmp6 = tl.full([1], 1, tl.int8) tmp7 = tl.full([1], 0, tl.int8) tmp8 = tl.where(tmp5, tmp6, tmp7) tmp9 = tmp3 > tmp2 tmp10 = tl.full([1], 2, tl.int8) tmp11 = tl.where(tmp9, tmp10, tmp8) tl.store(out_ptr0 + (x3 + 1184 * x2), tmp4, xmask) tl.store(out_ptr1 + (x3 + 1280 * x2), tmp11, xmask) @triton.jit def triton_poi_fused_convolution_relu_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 80640 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x3 = xindex x1 = xindex // 1008 % 20 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) tl.store(in_out_ptr0 + x3, tmp4, xmask) @triton.jit def triton_poi_fused_max_pool2d_with_indices_3(in_ptr0, out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr): xnumel = 26880 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 6720 x1 = xindex // 6720 tmp0 = tl.load(in_ptr0 + 3 * x2, xmask, eviction_policy='evict_last') tmp1 = tl.load(in_ptr0 + (1 + 3 * x2), xmask, eviction_policy='evict_last') tmp7 = tl.load(in_ptr0 + (2 + 3 * x2), xmask, eviction_policy='evict_last') tmp2 = tmp1 > tmp0 tmp3 = tl.full([1], 1, tl.int8) tmp4 = tl.full([1], 0, tl.int8) tmp5 = tl.where(tmp2, tmp3, tmp4) tmp6 = triton_helpers.maximum(tmp1, tmp0) tmp8 = tmp7 > tmp6 tmp9 = tl.full([1], 2, tl.int8) tmp10 = tl.where(tmp8, tmp9, tmp5) tmp11 = triton_helpers.maximum(tmp7, tmp6) tl.store(out_ptr0 + (x0 + 6784 * x1), tmp10, xmask) tl.store(out_ptr1 + x2, tmp11, xmask) def call(args): (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9) = args args.clear() assert_size_stride(primals_1, (10, 3, 7, 3), (63, 21, 3, 1)) assert_size_stride(primals_2, (10,), (1,)) assert_size_stride(primals_3, (4, 3, 64, 64), (12288, 4096, 64, 1)) assert_size_stride(primals_4, (20, 10, 3, 3), (90, 9, 3, 1)) assert_size_stride(primals_5, (20,), (1,)) assert_size_stride(primals_6, (100, 1120), (1120, 1)) assert_size_stride(primals_7, (100,), (1,)) assert_size_stride(primals_8, (1, 100), (100, 1)) assert_size_stride(primals_9, (1,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = extern_kernels.convolution(primals_3, primals_1, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf0, (4, 10, 58, 62), (35960, 3596, 62, 1)) buf1 = empty_strided_cuda((4, 10, 58, 62), (36160, 3616, 62, 1), torch.float32) get_raw_stream(0) triton_poi_fused_convolution_relu_0[grid(143840)](buf0, primals_2, buf1, 143840, XBLOCK=512, num_warps=8, num_stages=1) del buf0 del primals_2 buf2 = empty_strided_cuda((4, 10, 58, 20), (11840, 1184, 20, 1), torch.float32) buf3 = empty_strided_cuda((4, 10, 58, 20), (12800, 1280, 20, 1), torch.int8) triton_poi_fused_max_pool2d_with_indices_1[grid(46400)](buf1, buf2, buf3, 46400, XBLOCK=256, num_warps=4, num_stages=1) buf4 = extern_kernels.convolution(buf2, primals_4, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf4, (4, 20, 56, 18), (20160, 1008, 18, 1)) buf5 = buf4 del buf4 triton_poi_fused_convolution_relu_2[grid(80640)](buf5, primals_5, 80640, XBLOCK=1024, num_warps=4, num_stages=1) del primals_5 buf6 = empty_strided_cuda((4, 20, 56, 6), (6784, 336, 6, 1), torch.int8 ) buf7 = empty_strided_cuda((4, 20, 56, 6), (6720, 336, 6, 1), torch. float32) triton_poi_fused_max_pool2d_with_indices_3[grid(26880)](buf5, buf6, buf7, 26880, XBLOCK=256, num_warps=4, num_stages=1) buf8 = empty_strided_cuda((24, 100), (100, 1), torch.float32) extern_kernels.addmm(primals_7, reinterpret_tensor(buf7, (24, 1120), (1, 24), 0), reinterpret_tensor(primals_6, (1120, 100), (1, 1120), 0), alpha=1, beta=1, out=buf8) del primals_7 buf10 = empty_strided_cuda((24, 1), (1, 1), torch.float32) extern_kernels.addmm(primals_9, buf8, reinterpret_tensor(primals_8, (100, 1), (1, 100), 0), alpha=1, beta=1, out=buf10) del primals_9 return (reinterpret_tensor(buf10, (24,), (1,), 0), primals_1, primals_3, primals_4, buf1, buf2, buf3, buf5, buf6, reinterpret_tensor(buf7, ( 24, 1120), (1, 24), 0), reinterpret_tensor(primals_6, (1120, 100), (1, 1120), 0), buf8, primals_8) class NetNew(nn.Module): def __init__(self): super(NetNew, self).__init__() self.conv1 = nn.Conv2d(in_channels=3, out_channels=10, kernel_size= (7, 3)) self.pool = nn.MaxPool2d(kernel_size=(1, 3)) self.conv2 = nn.Conv2d(in_channels=10, out_channels=20, kernel_size =(3, 3)) self.fc1 = nn.Linear(7 * 8 * 20, 100) self.fc2 = nn.Linear(100, 1) self.sigmoid = nn.Sigmoid() def forward(self, input_0): primals_1 = self.conv1.weight primals_2 = self.conv1.bias primals_4 = self.conv2.weight primals_5 = self.conv2.bias primals_6 = self.fc1.weight primals_7 = self.fc1.bias primals_8 = self.fc2.weight primals_9 = self.fc2.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8, primals_9]) return output[0]
elliottwaissbluth/tensor-hero
Net
false
6,655
[ "MIT" ]
1
be99ca4380a5ec59c0826e5fc8a87ec0f8956201
https://github.com/elliottwaissbluth/tensor-hero/tree/be99ca4380a5ec59c0826e5fc8a87ec0f8956201
GaussianSample
import torch import torch.nn as nn class Stochastic(nn.Module): """ Base stochastic layer that uses the reparametrization trick [Kingma 2013] to draw a sample from a distribution parametrised by mu and log_var. """ def reparametrize(self, mu, logvar): epsilon = torch.randn(mu.size(), requires_grad=False, device=mu.device) std = logvar.mul(0.5).exp_() z = mu.addcmul(std, epsilon) return z class GaussianSample(Stochastic): """ Layer that represents a sample from a Gaussian distribution. """ def __init__(self, in_features, out_features): super(GaussianSample, self).__init__() self.in_features = in_features self.out_features = out_features self.mu = nn.Linear(in_features, out_features) self.log_var = nn.Linear(in_features, out_features) def forward(self, x): mu = self.mu(x) log_var = self.log_var(x) return self.reparametrize(mu, log_var), mu, log_var def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_features': 4, 'out_features': 4}]
import torch from torch import device 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_poi_fused_addcmul_exp_mul_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = tl.load(in_ptr1 + x0, xmask) tmp7 = tl.load(in_ptr2 + x0, xmask) tmp2 = 0.5 tmp3 = tmp1 * tmp2 tmp4 = tl_math.exp(tmp3) tmp5 = 1.0 tmp6 = tmp4 * tmp5 tmp8 = tmp6 * tmp7 tmp9 = tmp0 + tmp8 tl.store(out_ptr0 + x0, tmp9, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0 ), alpha=1, beta=1, out=buf0) del primals_1 del primals_2 buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0 ), alpha=1, beta=1, out=buf1) del primals_4 del primals_5 buf2 = torch.ops.aten.randn.default([4, 4, 4, 4], device=device( type='cuda', index=0), pin_memory=False) buf3 = buf2 del buf2 buf4 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_addcmul_exp_mul_0[grid(256)](buf0, buf1, buf3, buf4, 256, XBLOCK=256, num_warps=4, num_stages=1) return buf4, reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0 ), reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0 ), reinterpret_tensor(primals_3, (64, 4), (4, 1), 0 ), reinterpret_tensor(buf1, (4, 4, 4, 4), (64, 16, 4, 1), 0), buf3 class Stochastic(nn.Module): """ Base stochastic layer that uses the reparametrization trick [Kingma 2013] to draw a sample from a distribution parametrised by mu and log_var. """ def reparametrize(self, mu, logvar): epsilon = torch.randn(mu.size(), requires_grad=False, device=mu.device) std = logvar.mul(0.5).exp_() z = mu.addcmul(std, epsilon) return z class GaussianSampleNew(Stochastic): """ Layer that represents a sample from a Gaussian distribution. """ def __init__(self, in_features, out_features): super(GaussianSampleNew, self).__init__() self.in_features = in_features self.out_features = out_features self.mu = nn.Linear(in_features, out_features) self.log_var = nn.Linear(in_features, out_features) def forward(self, input_0): primals_1 = self.mu.weight primals_2 = self.mu.bias primals_4 = self.log_var.weight primals_5 = self.log_var.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0], output[1], output[2]
ericli0419/SCALEX
GaussianSample
false
6,656
[ "MIT" ]
1
2fedbe4c3287cf86de7b786c98122fe45707416e
https://github.com/ericli0419/SCALEX/tree/2fedbe4c3287cf86de7b786c98122fe45707416e
PatchedSelfAttentionLayer
import math import torch import torch.utils.data import torch from torch import nn import torch.nn.functional as F class SelfAttentionLayer(nn.Module): def __init__(self, elem_size, embd_size): super(SelfAttentionLayer, self).__init__() self.embd_size = embd_size self.query_lin = nn.Linear(elem_size, embd_size) self.key_lin = nn.Linear(elem_size, embd_size) self.softmax = nn.Softmax(dim=1) def forward(self, x): if len(x.shape) == 3: x = x.unsqueeze(1) _N, _num_patches, _seq_size, elem_size = x.shape Q = F.relu(self.query_lin(x)) K = F.relu(self.key_lin(x)) attention_mat = torch.matmul(Q, K.permute(0, 1, 3, 2)) / math.sqrt( elem_size) attention_mat = F.softmax(attention_mat, dim=-1) new_values = torch.matmul(attention_mat, x) out = new_values out = x + out return out, attention_mat class PatchedSelfAttentionLayer(nn.Module): def __init__(self, elem_size, embd_size, window_size, use_V=False): super(PatchedSelfAttentionLayer, self).__init__() self.sa_layer = SelfAttentionLayer(elem_size, embd_size) self.window_size = window_size self.embd_size = embd_size def forward(self, x): N, seq_size, elem_size = x.shape patches_num = seq_size // self.window_size add_patch = False if seq_size % self.window_size != 0: add_patch = True x_patches = x[:, :patches_num * self.window_size, :].reshape(N, patches_num, self.window_size, elem_size) if add_patch: rest_seq_padding = torch.zeros(N, 1, x_patches.shape[2], x_patches.shape[3]) rest_seq_values = x[:, patches_num * self.window_size:, :] rest_seq_padding[:, 0, :rest_seq_values.shape[1], : ] = rest_seq_values x_patches = torch.cat([x_patches, rest_seq_padding], dim=1) x_patches, attention_mat = self.sa_layer(x_patches) out = x_patches.reshape(x_patches.shape[0], x_patches.shape[1] * x_patches.shape[2], x_patches.shape[3])[:, :seq_size, :] attention_mat = attention_mat.reshape(attention_mat.shape[0], attention_mat.shape[1] * attention_mat.shape[2], attention_mat. shape[3])[:, :seq_size, :self.window_size] return out, attention_mat def get_inputs(): return [torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'elem_size': 4, 'embd_size': 4, 'window_size': 4}]
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 math import torch.utils.data import torch from torch import 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_relu_threshold_backward_0(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 x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, 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 + x2, tmp4, xmask) tl.store(out_ptr0 + x2, tmp6, xmask) @triton.jit def triton_poi_fused__softmax_1(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 x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp3 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp1 = 1.0 tmp2 = tmp0 * tmp1 tmp4 = tmp3 * tmp1 tmp6 = tmp5 * tmp1 tmp7 = triton_helpers.maximum(tmp4, tmp6) tmp9 = tmp8 * tmp1 tmp10 = triton_helpers.maximum(tmp7, tmp9) tmp12 = tmp11 * tmp1 tmp13 = triton_helpers.maximum(tmp10, tmp12) tmp14 = tmp2 - tmp13 tmp15 = 0.5 tmp16 = tmp14 * tmp15 tmp17 = tl_math.exp(tmp16) tl.store(out_ptr0 + x2, tmp17, xmask) @triton.jit def triton_poi_fused__softmax_2(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 x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) @triton.jit def triton_poi_fused_add_3(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 64 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp1 = tl.load(in_out_ptr0 + x0, xmask) tmp2 = tmp0 + tmp1 tl.store(in_out_ptr0 + x0, tmp2, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_2, (4, 4), (4, 1)) assert_size_stride(primals_3, (4,), (1,)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0) del primals_2 buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(primals_1, (16, 4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf1) del primals_4 buf2 = reinterpret_tensor(buf0, (4, 1, 4, 4), (16, 1, 4, 1), 0) del buf0 buf10 = empty_strided_cuda((4, 1, 4, 4), (16, 16, 4, 1), torch.bool) get_raw_stream(0) triton_poi_fused_relu_threshold_backward_0[grid(64)](buf2, primals_3, buf10, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_3 buf3 = reinterpret_tensor(buf1, (4, 1, 4, 4), (16, 1, 4, 1), 0) del buf1 buf9 = empty_strided_cuda((4, 1, 4, 4), (16, 16, 4, 1), torch.bool) triton_poi_fused_relu_threshold_backward_0[grid(64)](buf3, primals_5, buf9, 64, XBLOCK=64, num_warps=1, num_stages=1) del primals_5 buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(reinterpret_tensor(buf2, (4, 4, 4), (16, 4, 1), 0), reinterpret_tensor(buf3, (4, 4, 4), (16, 1, 4), 0), out=buf4) buf5 = empty_strided_cuda((4, 1, 4, 4), (16, 64, 4, 1), torch.float32) triton_poi_fused__softmax_1[grid(64)](buf4, buf5, 64, XBLOCK=64, num_warps=1, num_stages=1) buf6 = reinterpret_tensor(buf4, (4, 1, 4, 4), (16, 16, 4, 1), 0) del buf4 triton_poi_fused__softmax_2[grid(64)](buf5, buf6, 64, XBLOCK=64, num_warps=1, num_stages=1) buf7 = reinterpret_tensor(buf5, (4, 4, 4), (16, 4, 1), 0) del buf5 extern_kernels.bmm(reinterpret_tensor(buf6, (4, 4, 4), (16, 4, 1), 0), primals_1, out=buf7) buf8 = reinterpret_tensor(buf7, (4, 1, 4, 4), (16, 1, 4, 1), 0) del buf7 triton_poi_fused_add_3[grid(64)](buf8, primals_1, 64, XBLOCK=64, num_warps=1, num_stages=1) return reinterpret_tensor(buf8, (4, 4, 4), (16, 4, 1), 0 ), reinterpret_tensor(buf6, (4, 4, 4), (16, 4, 1), 0 ), primals_1, buf6, reinterpret_tensor(buf2, (4, 4, 4), (16, 1, 4), 0 ), reinterpret_tensor(buf3, (4, 4, 4), (16, 4, 1), 0), buf9, buf10 class SelfAttentionLayer(nn.Module): def __init__(self, elem_size, embd_size): super(SelfAttentionLayer, self).__init__() self.embd_size = embd_size self.query_lin = nn.Linear(elem_size, embd_size) self.key_lin = nn.Linear(elem_size, embd_size) self.softmax = nn.Softmax(dim=1) def forward(self, x): if len(x.shape) == 3: x = x.unsqueeze(1) _N, _num_patches, _seq_size, elem_size = x.shape Q = F.relu(self.query_lin(x)) K = F.relu(self.key_lin(x)) attention_mat = torch.matmul(Q, K.permute(0, 1, 3, 2)) / math.sqrt( elem_size) attention_mat = F.softmax(attention_mat, dim=-1) new_values = torch.matmul(attention_mat, x) out = new_values out = x + out return out, attention_mat class PatchedSelfAttentionLayerNew(nn.Module): def __init__(self, elem_size, embd_size, window_size, use_V=False): super(PatchedSelfAttentionLayerNew, self).__init__() self.sa_layer = SelfAttentionLayer(elem_size, embd_size) self.window_size = window_size self.embd_size = embd_size def forward(self, input_0): primals_2 = self.sa_layer.query_lin.weight primals_3 = self.sa_layer.query_lin.bias primals_4 = self.sa_layer.key_lin.weight primals_5 = self.sa_layer.key_lin.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0], output[1]
eldadp100/The-Mesh-Transformer
PatchedSelfAttentionLayer
false
6,657
[ "MIT" ]
1
b3ab18f774251feff1093040dfdcf7b836a43505
https://github.com/eldadp100/The-Mesh-Transformer/tree/b3ab18f774251feff1093040dfdcf7b836a43505
SpatialAttention
import torch import torch.nn as nn class SpatialAttention(nn.Module): def __init__(self, kernel_size=7): super(SpatialAttention, self).__init__() assert kernel_size in (3, 7), 'kernel size must be 3 or 7' padding = 3 if kernel_size == 7 else 1 self.conv1 = nn.Conv1d(2, 1, kernel_size, padding=padding, bias=False) self.sigmoid = nn.Sigmoid() def forward(self, x): avg_out = torch.mean(x, dim=1, keepdim=True) max_out, _ = torch.max(x, dim=1, keepdim=True) x = torch.cat([avg_out, max_out], dim=1) x = self.conv1(x) return self.sigmoid(x) def get_inputs(): return [torch.rand([4, 2, 64])] 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 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 @triton.jit def triton_poi_fused_cat_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 512 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x1 = xindex // 64 % 2 x0 = xindex % 64 x2 = xindex // 128 x3 = xindex tmp0 = x1 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 1, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (x0 + 128 * x2), tmp4 & xmask, eviction_policy ='evict_last', other=0.0) tmp6 = tl.load(in_ptr0 + (64 + x0 + 128 * x2), tmp4 & xmask, eviction_policy='evict_last', other=0.0) tmp7 = tmp5 + tmp6 tmp8 = 2.0 tmp9 = tmp7 / tmp8 tmp10 = tl.full(tmp9.shape, 0.0, tmp9.dtype) tmp11 = tl.where(tmp4, tmp9, tmp10) tmp12 = tmp0 >= tmp3 tl.full([1], 2, tl.int64) tmp15 = tl.load(in_ptr0 + (x0 + 128 * x2), tmp12 & xmask, eviction_policy='evict_last', other=0.0) tmp16 = tl.load(in_ptr0 + (64 + x0 + 128 * x2), tmp12 & xmask, eviction_policy='evict_last', other=0.0) tmp17 = triton_helpers.maximum(tmp15, tmp16) tmp18 = tl.full(tmp17.shape, 0.0, tmp17.dtype) tmp19 = tl.where(tmp12, tmp17, tmp18) tmp20 = tl.where(tmp4, tmp11, tmp19) tl.store(out_ptr0 + x3, tmp20, xmask) @triton.jit def triton_poi_fused_sigmoid_1(in_out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 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 = tl.sigmoid(tmp0) tl.store(in_out_ptr0 + x0, tmp1, xmask) def call(args): primals_1, primals_2 = args args.clear() assert_size_stride(primals_1, (4, 2, 64), (128, 64, 1)) assert_size_stride(primals_2, (1, 2, 7), (14, 7, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 2, 64), (128, 64, 1), torch.float32) get_raw_stream(0) triton_poi_fused_cat_0[grid(512)](primals_1, buf0, 512, XBLOCK=128, num_warps=4, num_stages=1) del primals_1 buf1 = extern_kernels.convolution(buf0, primals_2, stride=(1,), padding=(3,), dilation=(1,), transposed=False, output_padding=( 0,), groups=1, bias=None) assert_size_stride(buf1, (4, 1, 64), (64, 64, 1)) buf2 = buf1 del buf1 triton_poi_fused_sigmoid_1[grid(256)](buf2, 256, XBLOCK=128, num_warps=4, num_stages=1) return buf2, primals_2, buf0, buf2 class SpatialAttentionNew(nn.Module): def __init__(self, kernel_size=7): super(SpatialAttentionNew, self).__init__() assert kernel_size in (3, 7), 'kernel size must be 3 or 7' padding = 3 if kernel_size == 7 else 1 self.conv1 = nn.Conv1d(2, 1, kernel_size, padding=padding, bias=False) self.sigmoid = nn.Sigmoid() def forward(self, input_0): primals_2 = self.conv1.weight primals_1 = input_0 output = call([primals_1, primals_2]) return output[0]
esbgkannan/GT-CNN
SpatialAttention
false
6,658
[ "MIT" ]
1
4f3828d7ed8f6c3ed796fa4e2e166ef5c16cb3d9
https://github.com/esbgkannan/GT-CNN/tree/4f3828d7ed8f6c3ed796fa4e2e166ef5c16cb3d9
MyLinear
import torch from torch import nn from torch.nn import functional as F class MyLinear(nn.Module): def __init__(self, in_units, units): super().__init__() self.weight = nn.Parameter(torch.randn(in_units, units)) self.bias = nn.Parameter(torch.randn(units)) def forward(self, X): linear = torch.matmul(X, self.weight.data) + self.bias.data return F.relu(linear) def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'in_units': 4, 'units': 4}]
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 import 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_poi_fused_add_relu_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl. constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, xmask) def call(args): arg0_1, arg1_1, arg2_1 = args args.clear() assert_size_stride(arg0_1, (4, 4), (4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg2_1, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.mm(reinterpret_tensor(arg1_1, (64, 4), (4, 1), 0), arg0_1, out=buf0) del arg0_1 del arg1_1 buf1 = reinterpret_tensor(buf0, (4, 4, 4, 4), (64, 16, 4, 1), 0) del buf0 get_raw_stream(0) triton_poi_fused_add_relu_0[grid(256)](buf1, arg2_1, 256, XBLOCK= 256, num_warps=4, num_stages=1) del arg2_1 return buf1, class MyLinearNew(nn.Module): def __init__(self, in_units, units): super().__init__() self.weight = nn.Parameter(torch.randn(in_units, units)) self.bias = nn.Parameter(torch.randn(units)) def forward(self, input_0): arg0_1 = self.weight arg2_1 = self.bias arg1_1 = input_0 output = call([arg0_1, arg1_1, arg2_1]) return output[0]
eunice012716/Intern-Training
MyLinear
false
6,659
[ "MIT" ]
1
c3bbf42448a0b41e96d88569b6cfd57d78338716
https://github.com/eunice012716/Intern-Training/tree/c3bbf42448a0b41e96d88569b6cfd57d78338716
BCE_Dice
import torch import torch.nn as nn def IoU(logit, truth, smooth=1): prob = torch.sigmoid(logit) intersection = torch.sum(prob * truth) union = torch.sum(prob + truth) iou = (2 * intersection + smooth) / (union + smooth) return iou class DiceLoss(nn.Module): def __init__(self, smooth=1): super(DiceLoss, self).__init__() self.smooth = smooth def forward(self, logit, truth): iou = IoU(logit, truth, self.smooth) loss = 1 - iou return loss class BCE_Dice(nn.Module): def __init__(self, smooth=1): super(BCE_Dice, self).__init__() self.smooth = smooth self.dice = DiceLoss(smooth=smooth) self.bce = nn.BCEWithLogitsLoss() def forward(self, logit, truth): dice = self.dice(logit, truth) bce = self.bce(logit, truth) return dice + bce def get_inputs(): return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {}]
import torch 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, 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 @triton.jit def triton_per_fused_add_binary_cross_entropy_with_logits_div_mul_rsub_sigmoid_sum_0( in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel): XBLOCK: tl.constexpr = 1 RBLOCK: tl.constexpr = 256 xoffset = tl.program_id(0) * XBLOCK tl.full([1], xoffset, tl.int32) tl.full([RBLOCK], True, tl.int1) rindex = tl.arange(0, RBLOCK)[:] tl.full([RBLOCK], True, tl.int1) r0 = rindex tmp0 = tl.load(in_ptr0 + r0, None) tmp2 = tl.load(in_ptr1 + r0, None) tmp1 = tl.sigmoid(tmp0) tmp3 = tmp1 * tmp2 tmp4 = tl.broadcast_to(tmp3, [RBLOCK]) tmp6 = triton_helpers.promote_to_tensor(tl.sum(tmp4, 0)) tmp7 = tmp1 + tmp2 tmp8 = tl.broadcast_to(tmp7, [RBLOCK]) tmp10 = triton_helpers.promote_to_tensor(tl.sum(tmp8, 0)) tmp11 = 1.0 tmp12 = tmp11 - tmp2 tmp13 = tmp12 * tmp0 tmp14 = 0.0 tmp15 = triton_helpers.minimum(tmp14, tmp0) tmp16 = tl_math.abs(tmp0) tmp17 = -tmp16 tmp18 = tl_math.exp(tmp17) tmp19 = libdevice.log1p(tmp18) tmp20 = tmp15 - tmp19 tmp21 = tmp13 - tmp20 tmp22 = tl.broadcast_to(tmp21, [RBLOCK]) tmp24 = triton_helpers.promote_to_tensor(tl.sum(tmp22, 0)) tmp25 = 2.0 tmp26 = tmp6 * tmp25 tmp27 = tmp26 + tmp11 tmp28 = tmp10 + tmp11 tmp29 = tmp27 / tmp28 tmp30 = tmp11 - tmp29 tmp31 = 256.0 tmp32 = tmp24 / tmp31 tmp33 = tmp30 + tmp32 tl.debug_barrier() tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp33, None) def call(args): arg0_1, arg1_1 = args args.clear() assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((), (), torch.float32) buf3 = buf0 del buf0 get_raw_stream(0) triton_per_fused_add_binary_cross_entropy_with_logits_div_mul_rsub_sigmoid_sum_0[ grid(1)](buf3, arg0_1, arg1_1, 1, 256, num_warps=2, num_stages=1) del arg0_1 del arg1_1 return buf3, def IoU(logit, truth, smooth=1): prob = torch.sigmoid(logit) intersection = torch.sum(prob * truth) union = torch.sum(prob + truth) iou = (2 * intersection + smooth) / (union + smooth) return iou class DiceLoss(nn.Module): def __init__(self, smooth=1): super(DiceLoss, self).__init__() self.smooth = smooth def forward(self, logit, truth): iou = IoU(logit, truth, self.smooth) loss = 1 - iou return loss class BCE_DiceNew(nn.Module): def __init__(self, smooth=1): super(BCE_DiceNew, self).__init__() self.smooth = smooth self.dice = DiceLoss(smooth=smooth) self.bce = nn.BCEWithLogitsLoss() def forward(self, input_0, input_1): arg0_1 = input_0 arg1_1 = input_1 output = call([arg0_1, arg1_1]) return output[0]
evilidol/kaggle-Steel-Defect-Detection
BCE_Dice
false
6,660
[ "MIT" ]
1
41e3e360f49d706c8c79bcd442342c529648a736
https://github.com/evilidol/kaggle-Steel-Defect-Detection/tree/41e3e360f49d706c8c79bcd442342c529648a736
PrimaryCaps
import torch import torch.nn as nn class PrimaryCaps(nn.Module): """Creates a primary convolutional capsule layer that outputs a pose matrix and an activation. Note that for computation convenience, pose matrix are stored in first part while the activations are stored in the second part. Args: A: output of the normal conv layer B: number of types of capsules K: kernel size of convolution P: size of pose matrix is P*P stride: stride of convolution Shape: input: (*, A, h, w) output: (*, h', w', B*(P*P+1)) h', w' is computed the same way as convolution layer parameter size is: K*K*A*B*P*P + B*P*P """ def __init__(self, A=32, B=32, K=1, P=4, stride=1): super(PrimaryCaps, self).__init__() self.pose = nn.Conv2d(in_channels=A, out_channels=B * P * P, kernel_size=K, stride=stride, bias=True) self.a = nn.Conv2d(in_channels=A, out_channels=B, kernel_size=K, stride=stride, bias=True) self.sigmoid = nn.Sigmoid() def forward(self, x): p = self.pose(x) a = self.a(x) a = self.sigmoid(a) out = torch.cat([p, a], dim=1) out = out.permute(0, 2, 3, 1) return out def get_inputs(): return [torch.rand([4, 32, 64, 64])] 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 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_poi_fused_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 128 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] tl.full([XBLOCK, YBLOCK], True, tl.int1) x2 = xindex y3 = yindex y0 = yindex % 32 y1 = yindex // 32 tmp0 = tl.load(in_ptr0 + (x2 + 4096 * y3), ymask, eviction_policy= 'evict_last') tl.store(out_ptr0 + (y0 + 32 * x2 + 131072 * y1), tmp0, ymask) @triton.jit def triton_poi_fused_convolution_1(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 % 32 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_poi_fused_cat_2(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] tl.full([XBLOCK], True, tl.int1) x1 = xindex // 4096 % 544 x0 = xindex % 4096 x2 = xindex // 2228224 x3 = xindex tmp0 = x1 tl.full([1], 0, tl.int64) tmp3 = tl.full([1], 512, tl.int64) tmp4 = tmp0 < tmp3 tmp5 = tl.load(in_ptr0 + (512 * x0 + 2097152 * x2 + x1), tmp4, eviction_policy='evict_last', other=0.0) tmp6 = tl.load(in_ptr1 + x1, tmp4, eviction_policy='evict_last', other=0.0) tmp7 = tmp5 + tmp6 tmp8 = tl.full(tmp7.shape, 0.0, tmp7.dtype) tmp9 = tl.where(tmp4, tmp7, tmp8) tmp10 = tmp0 >= tmp3 tl.full([1], 544, tl.int64) tmp13 = tl.load(in_ptr2 + (32 * x0 + 131072 * x2 + (-512 + x1)), tmp10, eviction_policy='evict_last', other=0.0) tmp14 = tl.sigmoid(tmp13) tmp15 = tl.full(tmp14.shape, 0.0, tmp14.dtype) tmp16 = tl.where(tmp10, tmp14, tmp15) tmp17 = tl.where(tmp4, tmp9, tmp16) tl.store(out_ptr0 + x3, tmp17, None) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (512, 32, 1, 1), (32, 1, 1, 1)) assert_size_stride(primals_2, (512,), (1,)) assert_size_stride(primals_3, (4, 32, 64, 64), (131072, 4096, 64, 1)) assert_size_stride(primals_4, (32, 32, 1, 1), (32, 1, 1, 1)) assert_size_stride(primals_5, (32,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 32, 64, 64), (131072, 1, 2048, 32), torch.float32) get_raw_stream(0) triton_poi_fused_0[grid(128, 4096)](primals_3, buf0, 128, 4096, XBLOCK=32, YBLOCK=32, num_warps=4, num_stages=1) del primals_3 buf1 = extern_kernels.convolution(buf0, primals_1, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf1, (4, 512, 64, 64), (2097152, 1, 32768, 512)) buf2 = extern_kernels.convolution(buf0, primals_4, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf2, (4, 32, 64, 64), (131072, 1, 2048, 32)) buf3 = buf2 del buf2 triton_poi_fused_convolution_1[grid(524288)](buf3, primals_5, 524288, XBLOCK=512, num_warps=8, num_stages=1) del primals_5 buf4 = empty_strided_cuda((4, 544, 64, 64), (2228224, 4096, 64, 1), torch.float32) triton_poi_fused_cat_2[grid(8912896)](buf1, primals_2, buf3, buf4, 8912896, XBLOCK=512, num_warps=8, num_stages=1) del buf1 del primals_2 return reinterpret_tensor(buf4, (4, 64, 64, 544), (2228224, 64, 1, 4096), 0 ), primals_1, buf0, primals_4, buf3 class PrimaryCapsNew(nn.Module): """Creates a primary convolutional capsule layer that outputs a pose matrix and an activation. Note that for computation convenience, pose matrix are stored in first part while the activations are stored in the second part. Args: A: output of the normal conv layer B: number of types of capsules K: kernel size of convolution P: size of pose matrix is P*P stride: stride of convolution Shape: input: (*, A, h, w) output: (*, h', w', B*(P*P+1)) h', w' is computed the same way as convolution layer parameter size is: K*K*A*B*P*P + B*P*P """ def __init__(self, A=32, B=32, K=1, P=4, stride=1): super(PrimaryCapsNew, self).__init__() self.pose = nn.Conv2d(in_channels=A, out_channels=B * P * P, kernel_size=K, stride=stride, bias=True) self.a = nn.Conv2d(in_channels=A, out_channels=B, kernel_size=K, stride=stride, bias=True) self.sigmoid = nn.Sigmoid() def forward(self, input_0): primals_1 = self.pose.weight primals_2 = self.pose.bias primals_4 = self.a.weight primals_5 = self.a.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
esdrascosta/Matrix-Capsules
PrimaryCaps
false
6,661
[ "MIT" ]
1
ddf35dfa1acfb51a11a3ec27e15fe863a2ff6fa4
https://github.com/esdrascosta/Matrix-Capsules/tree/ddf35dfa1acfb51a11a3ec27e15fe863a2ff6fa4
Highway
import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.utils import torch.onnx class Highway(nn.Module): def __init__(self, e_word): super(Highway, self).__init__() self.embed_size = e_word self.w_proj = nn.Linear(self.embed_size, self.embed_size, bias=True) self.w_gate = nn.Linear(self.embed_size, self.embed_size, bias=True) def forward(self, x_convout: 'torch.Tensor') ->torch.Tensor: x_proj = F.relu(self.w_proj(x_convout)) sig = nn.Sigmoid() x_gate = sig(self.w_gate(x_convout)) x_highway = x_gate * x_proj + (1 - x_gate) * x_convout return x_highway def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'e_word': 4}]
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 torch.nn as nn import torch.nn.utils import torch.onnx 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_add_mul_relu_rsub_sigmoid_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x0 = xindex tmp0 = tl.load(in_ptr0 + x0, xmask) tmp2 = tl.load(in_ptr1 + x0, xmask) tmp8 = tl.load(in_ptr2 + x0, xmask) tmp1 = tl.sigmoid(tmp0) tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tmp5 = tmp1 * tmp4 tmp6 = 1.0 tmp7 = tmp6 - tmp1 tmp9 = tmp7 * tmp8 tmp10 = tmp5 + tmp9 tl.store(out_ptr0 + x0, tmp10, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (4,), (1,)) assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_1, (4, 4), (1, 4), 0 ), alpha=1, beta=1, out=buf0) del primals_1 del primals_2 buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32) extern_kernels.addmm(primals_5, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0 ), alpha=1, beta=1, out=buf1) del primals_4 del primals_5 buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused_add_mul_relu_rsub_sigmoid_0[grid(256)](buf1, buf0, primals_3, buf2, 256, XBLOCK=128, num_warps=4, num_stages=1) return buf2, primals_3, buf0, buf1 class HighwayNew(nn.Module): def __init__(self, e_word): super(HighwayNew, self).__init__() self.embed_size = e_word self.w_proj = nn.Linear(self.embed_size, self.embed_size, bias=True) self.w_gate = nn.Linear(self.embed_size, self.embed_size, bias=True) def forward(self, input_0): primals_1 = self.w_proj.weight primals_2 = self.w_proj.bias primals_4 = self.w_gate.weight primals_5 = self.w_gate.bias primals_3 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
evazhang612/honygenerator
Highway
false
6,662
[ "MIT" ]
1
cafcf1736faba978ecaed624b949ebc1498477ee
https://github.com/evazhang612/honygenerator/tree/cafcf1736faba978ecaed624b949ebc1498477ee
P2SActivationLayer
import torch import torch.nn as torch_nn from torch.nn import Parameter import torch.utils class P2SActivationLayer(torch_nn.Module): """ Output layer that produces cos heta between activation vector x and class vector w_j in_dim: dimension of input feature vectors output_dim: dimension of output feature vectors (i.e., number of classes) Usage example: batchsize = 64 input_dim = 10 class_num = 5 l_layer = P2SActivationLayer(input_dim, class_num) l_loss = P2SGradLoss() data = torch.rand(batchsize, input_dim, requires_grad=True) target = (torch.rand(batchsize) * class_num).clamp(0, class_num-1) target = target.to(torch.long) scores = l_layer(data) loss = l_loss(scores, target) loss.backward() """ def __init__(self, in_dim, out_dim): super(P2SActivationLayer, self).__init__() self.in_dim = in_dim self.out_dim = out_dim self.weight = Parameter(torch.Tensor(in_dim, out_dim)) self.weight.data.uniform_(-1, 1).renorm_(2, 1, 1e-05).mul_(100000.0) return def forward(self, input_feat): """ Compute P2sgrad activation input: ------ input_feat: tensor (batchsize, input_dim) output: ------- tensor (batchsize, output_dim) """ w = self.weight.renorm(2, 1, 1e-05).mul(100000.0) x_modulus = input_feat.pow(2).sum(1).pow(0.5) w.pow(2).sum(0).pow(0.5) inner_wx = input_feat.mm(w) cos_theta = inner_wx / x_modulus.view(-1, 1) cos_theta = cos_theta.clamp(-1, 1) return cos_theta def get_inputs(): return [torch.rand([4, 4])] def get_init_inputs(): return [[], {'in_dim': 4, 'out_dim': 4}]
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 torch_nn from torch.nn import Parameter import torch.utils assert_size_stride = torch._C._dynamo.guards.assert_size_stride empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda @triton.jit def triton_poi_fused_mul_renorm_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 x0 = xindex % 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp3 = tl.load(in_ptr0 + (4 + x0), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (8 + x0), xmask, eviction_policy='evict_last') tmp9 = tl.load(in_ptr0 + (12 + x0), 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-05 tmp14 = tmp12 > tmp13 tmp15 = 1e-07 tmp16 = tmp12 + tmp15 tmp17 = tl.full([1], 1, tl.int32) tmp18 = tmp17 / tmp16 tmp19 = tmp18 * tmp13 tmp20 = 1.0 tmp21 = tl.where(tmp14, tmp19, tmp20) tmp22 = tmp0 * tmp21 tmp23 = 100000.0 tmp24 = tmp22 * tmp23 tl.store(out_ptr0 + x2, tmp24, xmask) @triton.jit def triton_poi_fused_clamp_div_ge_le_logical_and_1(in_out_ptr0, in_ptr0, out_ptr0, out_ptr1, 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_out_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 = tmp0 / tmp12 tmp14 = -1.0 tmp15 = triton_helpers.maximum(tmp13, tmp14) tmp16 = 1.0 tmp17 = triton_helpers.minimum(tmp15, tmp16) tmp18 = tmp13 >= tmp14 tmp19 = tmp13 <= tmp16 tmp20 = tmp18 & tmp19 tl.store(out_ptr0 + x2, tmp17, xmask) tl.store(out_ptr1 + x2, tmp20, xmask) def call(args): primals_1, primals_2 = args args.clear() assert_size_stride(primals_1, (4, 4), (4, 1)) assert_size_stride(primals_2, (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_mul_renorm_0[grid(16)](primals_1, buf0, 16, XBLOCK =16, num_warps=1, num_stages=1) buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32) extern_kernels.mm(primals_2, buf0, out=buf1) buf2 = buf1 del buf1 buf3 = buf0 del buf0 buf4 = empty_strided_cuda((4, 4), (4, 1), torch.bool) triton_poi_fused_clamp_div_ge_le_logical_and_1[grid(16)](buf2, primals_2, buf3, buf4, 16, XBLOCK=16, num_warps=1, num_stages=1) del buf2 return buf3, primals_1, primals_2, buf4 class P2SActivationLayerNew(torch_nn.Module): """ Output layer that produces cos heta between activation vector x and class vector w_j in_dim: dimension of input feature vectors output_dim: dimension of output feature vectors (i.e., number of classes) Usage example: batchsize = 64 input_dim = 10 class_num = 5 l_layer = P2SActivationLayer(input_dim, class_num) l_loss = P2SGradLoss() data = torch.rand(batchsize, input_dim, requires_grad=True) target = (torch.rand(batchsize) * class_num).clamp(0, class_num-1) target = target.to(torch.long) scores = l_layer(data) loss = l_loss(scores, target) loss.backward() """ def __init__(self, in_dim, out_dim): super(P2SActivationLayerNew, self).__init__() self.in_dim = in_dim self.out_dim = out_dim self.weight = Parameter(torch.Tensor(in_dim, out_dim)) self.weight.data.uniform_(-1, 1).renorm_(2, 1, 1e-05).mul_(100000.0) return def forward(self, input_0): primals_1 = self.weight primals_2 = input_0 output = call([primals_1, primals_2]) return output[0]
eurecom-asp/raw-pc-darts-anti-spoofing
P2SActivationLayer
false
6,663
[ "MIT" ]
1
f2dcb5a8fc0cb811328a341a9bd90ffb292adaa1
https://github.com/eurecom-asp/raw-pc-darts-anti-spoofing/tree/f2dcb5a8fc0cb811328a341a9bd90ffb292adaa1
ChannelGate2d
import torch import torch.nn as nn class ChannelGate2d(nn.Module): def __init__(self, channels, reduction=2): super(ChannelGate2d, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc1 = nn.Conv2d(channels, channels // reduction, kernel_size=1, padding=0) self.relu = nn.ReLU(inplace=True) self.fc2 = nn.Conv2d(channels // reduction, channels, kernel_size=1, padding=0) self.sigmoid = nn.Sigmoid() def forward(self, x): module_input = x x = self.avg_pool(x) x = self.fc1(x) x = self.relu(x) x = self.fc2(x) x = self.sigmoid(x) return module_input * x def get_inputs(): return [torch.rand([4, 4, 4, 4])] def get_init_inputs(): return [[], {'channels': 4}]
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 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_mean_0(in_out_ptr0, in_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr): xnumel = 16 RBLOCK: tl.constexpr = 16 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 + 16 * x0), xmask, other=0.0) tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK]) tmp3 = tl.where(xmask, tmp1, 0) tmp4 = tl.sum(tmp3, 1)[:, None] tmp5 = 16.0 tmp6 = tmp4 / tmp5 tl.debug_barrier() tl.store(in_out_ptr0 + x0, tmp6, xmask) @triton.jit def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 8 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 2 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tmp3 = tl.full([1], 0, tl.int32) tmp4 = triton_helpers.maximum(tmp3, tmp2) tl.store(in_out_ptr0 + x2, tmp4, xmask) @triton.jit def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl .constexpr): xnumel = 16 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x0 = xindex % 4 tmp0 = tl.load(in_out_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last') tmp2 = tmp0 + tmp1 tl.store(in_out_ptr0 + x2, tmp2, xmask) @triton.jit def triton_poi_fused_mul_sigmoid_3(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr): xnumel = 256 xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:] xmask = xindex < xnumel x2 = xindex x1 = xindex // 16 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last') tmp2 = tl.sigmoid(tmp1) tmp3 = tmp0 * tmp2 tl.store(out_ptr0 + x2, tmp3, xmask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1)) assert_size_stride(primals_2, (2, 4, 1, 1), (4, 1, 1, 1)) assert_size_stride(primals_3, (2,), (1,)) assert_size_stride(primals_4, (4, 2, 1, 1), (2, 1, 1, 1)) assert_size_stride(primals_5, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((4, 4, 1, 1), (4, 1, 16, 16), torch.float32) buf1 = reinterpret_tensor(buf0, (4, 4, 1, 1), (4, 1, 1, 1), 0) del buf0 get_raw_stream(0) triton_per_fused_mean_0[grid(16)](buf1, primals_1, 16, 16, XBLOCK=8, num_warps=2, num_stages=1) buf2 = extern_kernels.convolution(buf1, primals_2, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf2, (4, 2, 1, 1), (2, 1, 1, 1)) buf3 = buf2 del buf2 triton_poi_fused_convolution_relu_1[grid(8)](buf3, primals_3, 8, XBLOCK=8, num_warps=1, num_stages=1) del primals_3 buf4 = extern_kernels.convolution(buf3, primals_4, stride=(1, 1), padding=(0, 0), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=1, bias=None) assert_size_stride(buf4, (4, 4, 1, 1), (4, 1, 1, 1)) buf5 = buf4 del buf4 triton_poi_fused_convolution_2[grid(16)](buf5, primals_5, 16, XBLOCK=16, num_warps=1, num_stages=1) del primals_5 buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32) triton_poi_fused_mul_sigmoid_3[grid(256)](primals_1, buf5, buf6, 256, XBLOCK=256, num_warps=4, num_stages=1) return buf6, primals_1, primals_2, primals_4, buf1, buf3, buf5 class ChannelGate2dNew(nn.Module): def __init__(self, channels, reduction=2): super(ChannelGate2dNew, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc1 = nn.Conv2d(channels, channels // reduction, kernel_size=1, padding=0) self.relu = nn.ReLU(inplace=True) self.fc2 = nn.Conv2d(channels // reduction, channels, kernel_size=1, padding=0) self.sigmoid = nn.Sigmoid() def forward(self, input_0): primals_2 = self.fc1.weight primals_3 = self.fc1.bias primals_4 = self.fc2.weight primals_5 = self.fc2.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0]
evilidol/kaggle-Steel-Defect-Detection
ChannelGate2d
false
6,664
[ "MIT" ]
1
41e3e360f49d706c8c79bcd442342c529648a736
https://github.com/evilidol/kaggle-Steel-Defect-Detection/tree/41e3e360f49d706c8c79bcd442342c529648a736
SelfAttention
from _paritybench_helpers import _mock_config import math import torch import torch.nn as nn from torch.nn import functional as F class SelfAttention(nn.Module): def __init__(self, config): super().__init__() assert config.n_embd % config.n_head == 0 self.qkv = nn.Linear(config.n_embd, config.n_embd * 3) self.split_size = config.n_embd self.proj = nn.Linear(config.n_embd, config.n_embd) self.register_buffer('mask', torch.tril(torch.ones(config. block_size, config.block_size)).view(1, 1, config.block_size, config.block_size)) self.n_head = config.n_head def forward(self, x, attn_mask=None): B, T, C = x.size() q, k, v = self.qkv(x).split(self.split_size, 2) att = q @ k.transpose(-2, -1) * (1.0 / math.sqrt(k.size(-1))) if attn_mask is not None: att = att + attn_mask att = F.softmax(att, dim=-1) y = att @ v y = y.transpose(1, 2).contiguous().view(B, T, C) y = self.proj(y) return y, att def get_inputs(): return [torch.rand([4, 4, 4])] def get_init_inputs(): return [[], {'config': _mock_config(n_embd=4, n_head=4, block_size=4)}]
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 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_poi_fused__softmax_0(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 x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp3 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp5 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp8 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp11 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last' ) tmp1 = 1.0 tmp2 = tmp0 * tmp1 tmp4 = tmp3 * tmp1 tmp6 = tmp5 * tmp1 tmp7 = triton_helpers.maximum(tmp4, tmp6) tmp9 = tmp8 * tmp1 tmp10 = triton_helpers.maximum(tmp7, tmp9) tmp12 = tmp11 * tmp1 tmp13 = triton_helpers.maximum(tmp10, tmp12) tmp14 = tmp2 - tmp13 tmp15 = 0.5 tmp16 = tmp14 * tmp15 tmp17 = tl_math.exp(tmp16) tl.store(out_ptr0 + x2, tmp17, xmask) @triton.jit def triton_poi_fused__softmax_1(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 x2 = xindex x1 = xindex // 4 tmp0 = tl.load(in_ptr0 + x2, xmask) tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last') tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last') tmp4 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last') tmp6 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last') tmp3 = tmp1 + tmp2 tmp5 = tmp3 + tmp4 tmp7 = tmp5 + tmp6 tmp8 = tmp0 / tmp7 tl.store(out_ptr0 + x2, tmp8, xmask) @triton.jit def triton_poi_fused_clone_2(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl. constexpr, XBLOCK: tl.constexpr): ynumel = 16 xnumel = 4 yoffset = tl.program_id(1) * YBLOCK yindex = yoffset + tl.arange(0, YBLOCK)[None, :] ymask = yindex < ynumel xoffset = tl.program_id(0) * XBLOCK xindex = xoffset + tl.arange(0, XBLOCK)[:, None] xmask = xindex < xnumel x2 = xindex y0 = yindex % 4 y1 = yindex // 4 y3 = yindex tmp0 = tl.load(in_ptr0 + (y0 + 4 * x2 + 16 * y1), xmask & ymask, eviction_policy='evict_last') tl.store(out_ptr0 + (x2 + 4 * y3), tmp0, xmask & ymask) def call(args): primals_1, primals_2, primals_3, primals_4, primals_5 = args args.clear() assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1)) assert_size_stride(primals_2, (12, 4), (4, 1)) assert_size_stride(primals_3, (12,), (1,)) assert_size_stride(primals_4, (4, 4), (4, 1)) assert_size_stride(primals_5, (4,), (1,)) with torch.cuda._DeviceGuard(0): torch.cuda.set_device(0) buf0 = empty_strided_cuda((16, 12), (12, 1), torch.float32) extern_kernels.addmm(primals_3, reinterpret_tensor(primals_1, (16, 4), (4, 1), 0), reinterpret_tensor(primals_2, (4, 12), (1, 4), 0), alpha=1, beta=1, out=buf0) del primals_2 del primals_3 buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) extern_kernels.bmm(reinterpret_tensor(buf0, (4, 4, 4), (48, 12, 1), 0), reinterpret_tensor(buf0, (4, 4, 4), (48, 1, 12), 4), out=buf1) buf2 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) get_raw_stream(0) triton_poi_fused__softmax_0[grid(64)](buf1, buf2, 64, XBLOCK=64, num_warps=1, num_stages=1) buf3 = buf1 del buf1 triton_poi_fused__softmax_1[grid(64)](buf2, buf3, 64, XBLOCK=64, num_warps=1, num_stages=1) buf4 = buf2 del buf2 extern_kernels.bmm(buf3, reinterpret_tensor(buf0, (4, 4, 4), (48, 12, 1), 8), out=buf4) buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32) triton_poi_fused_clone_2[grid(16, 4)](buf4, buf5, 16, 4, XBLOCK=4, YBLOCK=16, num_warps=1, num_stages=1) buf6 = reinterpret_tensor(buf4, (16, 4), (4, 1), 0) del buf4 extern_kernels.addmm(primals_5, reinterpret_tensor(buf5, (16, 4), ( 4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf6) del primals_5 return reinterpret_tensor(buf6, (4, 4, 4), (16, 4, 1), 0 ), buf3, reinterpret_tensor(primals_1, (16, 4), (4, 1), 0 ), buf3, reinterpret_tensor(buf5, (16, 4), (4, 1), 0 ), primals_4, reinterpret_tensor(buf0, (4, 4, 4), (48, 1, 12), 8 ), reinterpret_tensor(buf0, (4, 4, 4), (48, 1, 12), 0 ), reinterpret_tensor(buf0, (4, 4, 4), (48, 12, 1), 4) class SelfAttentionNew(nn.Module): def __init__(self, config): super().__init__() assert config.n_embd % config.n_head == 0 self.qkv = nn.Linear(config.n_embd, config.n_embd * 3) self.split_size = config.n_embd self.proj = nn.Linear(config.n_embd, config.n_embd) self.register_buffer('mask', torch.tril(torch.ones(config. block_size, config.block_size)).view(1, 1, config.block_size, config.block_size)) self.n_head = config.n_head def forward(self, input_0): primals_2 = self.qkv.weight primals_3 = self.qkv.bias primals_4 = self.proj.weight primals_5 = self.proj.bias primals_1 = input_0 output = call([primals_1, primals_2, primals_3, primals_4, primals_5]) return output[0], output[1]
evelynmitchell/rasp
SelfAttention
false
6,665
[ "MIT" ]
1
9b33bbf911e6c4ff018c9883c39eb698c0abe803
https://github.com/evelynmitchell/rasp/tree/9b33bbf911e6c4ff018c9883c39eb698c0abe803